Unity3D 字符控制器通过脚本设置速度



我如何设置在Void FixedUpdate中前进和后退的速度?或者有更好的方法吗?不过我需要使用角色控制器。

using UnityEngine;
using System.Collections;
public class CharacterControllerz : MonoBehaviour {
public float speed;
private CharacterController playerController;
void Start()
{
    playerController = GetComponent<CharacterController>();
}
void Update()
{
}
void FixedUpdate()
{
    if (Input.GetKey("right"))
    {
        playerController.Move (Vector3.forward);
        Debug.Log ("RIGHT");
    }
    if (Input.GetKey("left"))
    {
        playerController.Move (Vector3.back);
        Debug.Log ("LEFT");
    }       
    playerController.Move (Vector3.left);
}
}
        public float speed = 5f;
        public float jumpStrenght = 8f;
        public float gravity = 20f;
        private Vector3 moveDirections = new Vector3();
        private Vector3 inputs = new Vector3();
        void FixedUpdate()
        {
            CharacterController cc = GetComponent<CharacterController>();
            if (cc.isGrounded) 
            {
                if (Input.GetKey("right"))
                    inputs.z = 1;
                if (Input.GetKey("left"))
                    inputs.z = -1;
                if (Input.GetKey("up"))
                    inputs.y = jumpStrenght;
                moveDirections = transform.TransformDirection(inputs.x, 0, inputs.z) * speed;                    
            }
            moveDirections.y = inputs.y - gravity;
            cc.Move(moveDirections * Time.deltaTime);
        }

我认为这就是你想要的,但你可能不得不切换轴。

编辑:为什么使用TransformDirection?因为我们想将物体移动到一个不应该与物体旋转相对的方向。

最新更新