美文网首页
【Unity 3D学习】键盘控制人物在场景中移动

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

作者: 夏亦流风 | 来源:发表于2019-03-12 21:51 被阅读0次

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

     public float speed = 3.0F;

     public float rotateSpeed = 3.0F;

     Character Controller controller;

     void Start () {

     controller = GetComponent();

     }

    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;

publicfloatjumpSpeed = 8.0F;

publicfloatgravity = 20.0F;

privateVector3 moveDirection = Vector3.zero;

CharacterController controller;

voidStart () {

controller = GetComponent();

}

voidUpdate() {

if(controller.isGrounded) {

moveDirection =newVector3(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”,这个组件应该是和鼠标点击地面事件相结合的。因为自己同时测键盘和鼠标点击事件对人物移动的影响,所以才发生这样的问题,特地记录一下,找到原因的话再更。

相关文章

网友评论

      本文标题:【Unity 3D学习】键盘控制人物在场景中移动

      本文链接:https://www.haomeiwen.com/subject/oitibttx.html