今天我們主要學習了角色控制和射線。
角色控制
通過調用SimpleMove()使物體移動(只適用於平面移動)
爲移動物體添加CharacterController(角色控制器)
-
private CharacterController controller=null ;
-
//聲明角色控制器
-
private float speed=30.0f;
-
-
void Start () {
-
-
controller =GetComponent <CharacterController >();
-
-
//添加角色控制器
-
-
}
-
-
void Update () {
-
-
controller.SimpleMove(new Vector3(Input .GetAxis ("Horizontal")*speed ,0,Input .GetAxis ("Vertical")*speed ));
-
-
//調用SimpleMove()方法來實現
-
-
}
-
-
}
複製代碼
|
移動和飛翔
可以通過調用Move()方法來實現
先定義一個三維向量的方向,然後通過調用Move()方法來實現。
float speed=10f;
if (Input.GetKeyDown(KeyCode.W)) {
Vector3 forward=transform.TransformDirection(Vector3.forward);
//定義三維向量的方向
controller.Move(forward*speed);
//調用Move()方法。
}
射線
定義一條射線
Ray ray=new Ray(Vector.zero,transform.possition);
參數一個爲起點座標,一個爲它的物理座標
定義一個光線投射碰撞
RaycastHit hit ;
Physics.Raycast(ray,out hit,100); //在Scene中生成這條射線,起點爲射線的起點,終點爲射線與物體的碰撞點
畫出射線
Debug.Drawline(ray.origin,hit.point);
在實際中使用的案例
點擊鼠標,物體移動
-
<div class="blockcode"><blockquote> private CharacterController controller = null;
-
-
void Start () {
-
-
controller = GetComponent<CharacterController>();
-
-
}
-
-
-
void Update () {
-
-
if (Input.GetMouseButtonDown(0))
-
-
{
-
-
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
-
-
RaycastHit hit;
-
-
if (Physics.Raycast(ray, out hit, 100))
-
-
{
-
-
print (Input .mousePosition .x+" "+Input .mousePosition .y);//鼠標點擊的地方
-
-
print(hit.point);
-
-
controller.SimpleMove(new Vector3(Input.mousePosition.x, 0, Input.mousePosition.y));
-
-
}
-
-
}
複製代碼
|