您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。