【Unity 3D学习】键盘控制人物在场景中移动

来源:互联网 发布:网络兼职在校学生 编辑:程序博客网 时间:2024/04/30 12:27

一、第一种情况,键盘左右键控制人物旋转,让人物可以面向四方,然后上下键控制移动。

public float speed = 3.0F;public float rotateSpeed = 3.0F;CharacterController controller;void Start () {     controller = GetComponent<CharacterController>();}void Update() {     transform.Rotate(0, Input.GetAxis("Horizontal") * rotateSpeed, 0);     Vector3 forward = transform.TransformDirection(Vector3.forward);  //注意这个方法     float curSpeed = speed * Input.GetAxis("Vertical");     controller.SimpleMove(forward * curSpeed);}
第二种情况,键盘四个键可以同时控制人物移动。

public float speed = 6.0F;public float jumpSpeed = 8.0F;public float gravity = 20.0F;private Vector3 moveDirection = Vector3.zero;CharacterController controller;void Start () {     controller = GetComponent<CharacterController>();}void Update() {     if (controller.isGrounded) {          moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));          moveDirection = transform.TransformDirection(moveDirection);          moveDirection *= speed;          if (Input.GetButton("Jump"))               moveDirection.y = jumpSpeed;     }     moveDirection.y -= gravity * Time.deltaTime;     controller.Move(moveDirection * Time.deltaTime);}


ps:这里使用了组件“Character Controller”,要注意的是使用了这个之后好像会和组件“Nav Mesh Agent”冲突。所以使用键盘调试的时候不要使用“Nav Mesh Agent”,这个组件应该是和鼠标点击地面事件相结合的。因为自己同时测键盘和鼠标点击事件对人物移动的影响,所以才发生这样的问题,特地记录一下,找到原因的话再更。

0 0
原创粉丝点击