2016-09-24 112 views
3

我有一个脚本,它允许你控制一个玩家,并跳转。然而,我正在努力让玩家不断移动,而不是通过键盘上的WASD键进行控制。 每当我尝试只使用controller.Move()我的重力功能消失。 现在,通过此代码Gravity可以工作,但WASD已启用。 我的问题是:我怎样才能让这段代码让我的玩家不断移动,并仍然使用重力?Unity3D玩家运动脚本

using UnityEngine; 
using System.Collections; 

public class PlayerMotor : MonoBehaviour { 

    public float speed = 6.0F; 
    public float jumpSpeed = 8.0F; 
    public float gravity = 20.0F; 

    private Vector3 moveDirection = Vector3.back; 
    void Update() { 
     CharacterController controller = GetComponent<CharacterController>(); 
     if (controller.isGrounded) 
     { 
      controller.Move (Vector3.back * Time.deltaTime); 
      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); 
    } 
} 

回答

2

每当我试着只用controller.Move()我的重力作用消失

这是因为在文档中陈述了预期的行为:https://docs.unity3d.com/ScriptReference/CharacterController.Move.html

moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); 

相反从玩家处获得输入信息,请指定您自己的moveDirection。例如:moveDirection = new Vector3(1, 0, 1); 看看的文档中可能的值:https://docs.unity3d.com/ScriptReference/Input.GetAxis.html

一个侧面说明:CharacterController controller = GetComponent<CharacterController>();

我知道你从文档,但GetComponent每一个更新的性能并不明智复制。反而缓存它!