Unity3D虛擬現實開發之實現人物轉向與移動

來源:互聯網
上載者:User

       在網上有很多通過射線方式實現的人物行走控制指令碼,但是如果只是想通過鍵盤按鍵來控制的話,比如進行第三人稱視角控制,其實只需要進行簡單的角度變換即可。思路如下:

1、按照順時針方向設定前、右、後、左分別為0,1,2,3。

2、設定狀態初值0,即朝向前方。

3、通過當前方向值減去前一次方向值,乘以90°即為轉向角,然後進行旋轉變換即可。

using UnityEngine;using System.Collections;using System.Linq;public class move: MonoBehaviour{private int State;//角色狀態private int oldState=0;//前一次角色的狀態private int UP = 0;//角色狀態向前private int RIGHT =1;//角色狀態向右private int DOWN = 2;//角色狀態向後private int LEFT = 3;//角色狀態向左public float speed=8;void Start(){}void Update(){if (Input.GetKey("w")){setState(UP);}else if (Input.GetKey("s")){setState(DOWN);}if (Input.GetKey("a")){setState(LEFT);}else if (Input.GetKey("d")){setState(RIGHT);}}void setState(int currState){Vector3 transformValue = new Vector3();//定義平移向量int rotateValue = (currState - State) * 90;transform.animation.Play("walk");//播放角色行走動畫switch (currState){case 0://角色狀態向前時,角色不斷向前緩慢移動transformValue = Vector3.forward * Time.deltaTime * speed;break;case 1://角色狀態向右時,角色不斷向右緩慢移動transformValue = Vector3.right * Time.deltaTime * speed;break;case 2://角色狀態向後時,角色不斷向後緩慢移動transformValue = Vector3.back * Time.deltaTime * speed;break;case 3://角色狀態向左時,角色不斷向左緩慢移動transformValue = Vector3.left * Time.deltaTime * speed;break;}transform.Rotate(Vector3.up, rotateValue);//旋轉角色transform.Translate(transformValue, Space.World);//平移角色oldState = State;//賦值,方便下一次計算State = currState;//賦值,方便下一次計算}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.