您好,登錄后才能下訂單哦!
unity中控制人物移動有很多方法,經過這么長時間的學習后,我總結了一些;
利用transform的translate方法控制人物移動;(結合動畫的控制就不說了)
float mx = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime; float mz = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime; transform.translate(mx,0,mz);
2.利用Rigidbody組件rigidbody.MovePosition()方法進行移動(包含動畫控制部分),鼠標控制人物移動;
void FixedUpdate() { float h=Input.GetAxis("Horizontal"); float v=Input.GetAxis("Vertical"); Move(h,v); Turning(); Animating(h,v); } void Move(float h,float v) { Vector3 movement; movement.Set(h,0,v); movement=movement.normalized*speed*Time.deltaTime; rigidbody.MovePosition(transform.position+movement); } void Turning() { Ray camRay=Camera.main.ScreenPointToRay(Input.mousePosition); RayCastHit hitInfo; if(Physics.RayCast(camRay,out hitInfo,distance,floorMask)) { Vector3 playerToMouse=hitInfo.point-transform.position; playerToMouse.y=0; Quaternion newRotation=Quaternion.LookRotation(playerToMouse); rigidbody.MovePosition(newRotation); } } void Animating(float h,float v) { bool walking=h!=0||v!=0; m_ator.SetBool("Walk",walking); }
3.還有一種就是利用Rigidbody的velocity屬性來控制人物移動了
float moveSpeed =10; Animator m_ator; Rigidbody rigid; Vector3 m_Pos; void Start () { m_ator = transform.GetComponent<Animator>(); rigid = transform.GetComponent<Rigidbody>(); m_Pos = transform.position; } void Update () { float mx = Input.GetAxis("Horizontal") ; float mz = Input.GetAxis("Vertical") ; Vector3 nowVelocity = rigid.velocity; if (Mathf.Abs(mx) > 0.01f || Mathf.Abs(mz) > 0.01f) { m_Pos = transform.position; transform.LookAt(m_Pos+new Vector3(mx, 0, mz)); rigid.velocity = new Vector3(mx * moveSpeed, nowVelocity.y * moveSpeed, mz * moveSpeed); m_ator.SetBool("Walk",true); } else { rigid.velocity = new Vector3(0,nowVelocity.y*moveSpeed,0); m_ator.SetBool("Walk",false); } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。