Unity3D角色控制器通过脚本设置速度?

时间:2016-02-07 11:55:18

标签: 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);
}
}

1 个答案:

答案 0 :(得分:2)

        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?因为我们想要将物体移动到一个不应该与物体旋转相对的方向上。

相关问题