Physics.Raycast:光線投射
參數:
origin:射線起始點
direction:射線方向
distance:射線長度
layerMask:只選定Layermask層內的碰撞器,其它層內碰撞器忽略。
Returns
bool - True when the ray intersects any collider,otherwise false.
當光線投射與任何碰撞器交叉時爲真,否則爲假。
下面通過實現這個小例子來試驗一下:點擊哪裏就向哪裏移動
using UnityEngine;
using System.Collections;
public class capsule : MonoBehaviour {
public CharacterController cc;
public float speed;
public Camera camera;
public Vector3 targetPosition;
void Start () {
targetPosition=this.transform.position;//把初始的位置賦值給當前座標
cc=this.gameObject.GetComponent<CharacterController>();
}
//定義射線方法:
void getHitPoint(){
Ray ray;//創建一個新的射線,
RaycastHit hit;//光線投射碰撞qi
if(Input.GetMouseButtonDown(0)){//如果我點擊了屏幕之後才能觸發射線
ray=camera.ScreenPointToRay(Input.mousePosition);//屏幕位置轉射線
if(Physics.Raycast(ray,out hit,100)){//光線投射--當光線投射與任何碰撞器交叉時爲真,100射線距離
// Debug.Log (hit.point);
if(hit.collider.gameObject.name=="Terrain"){
targetPosition=hit.point;
//Debug.Log(targetPosition);
}
}
}
}
void walk(){
Vector3 v= Vector3.Normalize(targetPosition-this.transform.position);
cc.SimpleMove(v*speed*Time.deltaTime);//簡單移動方法。
}
void Update () {
// Vector3 v=new Vector3(0,0,10*speed*Time.deltaTime);
// if(Input.GetKey(KeyCode.A)){
// cc.SimpleMove(v);
// }
walk();
getHitPoint();
}
}