usingUnityEngine;
usingSystem.Collections;
publicclassCubeMove:MonoBehaviour{
Rayray;//聲明射線
RaycastHit?? hit;//射線碰撞信息
voidStart(){
}
voidUpdate(){
Move();
//從自身位置發射射線
//發射一條射線,返回檢測到的第一個物體,返回值為bool值
//Rayray=newRay(transform.position,transform.forward);
//一般射線(只能檢測到一個物體)
//Debug.DrawLine(transform.position,hit.point,Color.red);
//if(Physics.Raycast(ray,outhit,10)){
//
//print("有敵情");
//}
//可以檢測所有物體
//RaycastHit[]hits=Physics.RaycastAll(ray);
//
//if(hits.Length>0){
//
//print(hits.Length);
//}
//從攝像頭位置發出的射線(特殊射線)
if(Input.GetMouseButtonDown(0)){
Rayray=Camera.main.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(ray,out hit);
}
if(hit.collider){
Vector3 tempV3=Vector3.Lerp(transform.position,hit.point,Time.deltaTime);
transform.position=newVector3(tempV3.x,0.5f,tempV3.z);
}
//打開第N層,射線只能檢測到這一層
//LayerMaskmask=1<<(LayerMask.NameToLayer("Cube"));//只能檢測到Layer為Cube的物體
//1<<10打開第十層,當前射線只能檢測到第10層上的碰撞體
//~(1<<10)打開除第10層以外的所有層,除第10層以外的碰撞體都能被檢測到
//~(1<<0)打開所有層
//(1<<8)| (1<<10)同時打開第8層和第10層
Rayray2=newRay(transform.position,transform.forward);
LayerMaskmask=~(1<<LayerMask.NameToLayer("Cube"));//可以檢測到除“Cube”以外的所有物體
if(Physics.Raycast(ray2,outhit,100,mask.value)){
print(hit.collider.gameObject.name);
}
}
voidMove(){
float hor=Input.GetAxis("Horizontal");
float ver=Input.GetAxis("Vertical");
transform.position+=(transform.forward*ver+transform.right*hor)*Time.deltaTime*20;
}
}