unity3d 我怎样才能使这个团结运动的剧本发挥作用呢?

qyyhg6bp  于 2023-01-26  发布在  其他
关注(0)|答案(3)|浏览(186)

我怎样才能使这个脚本工作,或者另一个替代的球员运动脚本?这个基本的运动脚本在Unity中不做任何事情,当我按下WASD的原因。我是一个初学者在C#和Unity,我需要一个替代的球员运动脚本,实际上工作。

void Update()
{
    if (Input.GetKeyDown(KeyCode.W))
        transform.Translate(Vector3.forward);
    if (Input.GetKeyDown(KeyCode.S))
        transform.Translate(Vector3.back);
    if (Input.GetKeyDown(KeyCode.A))
        transform.Translate(Vector3.left);
    if (Input.GetKeyDown(KeyCode.D)) 
        transform.Translate(Vector3.right);
hujrc8aj

hujrc8aj1#

我建议使用GetAxis(“Horizontal”)和GetAxis(“Vertical”)方法,默认情况下Mapwasd和箭头键,以帮助精简您的大型if树。
下面是我以前大学项目的一个小例子。
注:“* speed * Time.deltaTime”用于在时间/帧移动时帮助转换,在这种情况下,速度只是一个乘数。

public float speed = 10.0f;
private float translation;
private float straffe;

// Use this for initialization
void Start()
{
    // turn off the cursor
    Cursor.lockState = CursorLockMode.Locked;
}

// Update is called once per frame
void Update()
{
    // Input.GetAxis() is used to get the user's input
    // You can further set it on Unity. (Edit, Project Settings, Input)
    translation = Input.GetAxis("Vertical") * speed * Time.deltaTime;
    straffe = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
    transform.Translate(straffe, 0, translation);

    if (Input.GetKeyDown("escape"))
    {
        // turn on the cursor
        Cursor.lockState = CursorLockMode.None;
    }
}
0sgqnhkj

0sgqnhkj2#

Input.GetKeyDown检查您是否在该帧上按了w键。您需要Input.GetKey。它检查您是否正在按住

wnvonmuf

wnvonmuf3#

您应该使用GetAxis(“水平”)和GetAxis(“垂直”);下面是我的项目默认移动的基本代码:

//movement
Rigidbody rb;
float xInput;
float yInput;
public float speed;
public float defSpeed;
public float sprint;
public bool isGrounded = true;
public float jump;

// Start is called before the first frame update

private void Awake()
{
    rb = GetComponent<Rigidbody>();
}

void Start()
{

}

// Update is called once per frame
void Update()
{
    xInput = Input.GetAxis("Horizontal");
    yInput = Input.GetAxis("Vertical");

    //Things is still can't understand
    Vector3 input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    float cameraRot = Camera.main.transform.rotation.eulerAngles.y;
    rb.position += Quaternion.Euler(0, cameraRot, 0) * input * speed * Time.deltaTime;

    //sprint
    if (Input.GetKeyDown(KeyCode.LeftShift)) 
    {
        speed = sprint;
    }
    else if (Input.GetKeyUp(KeyCode.LeftShift))
    {
        speed = defSpeed;
    }

    //jump
    if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
    {
        rb.AddForce(0, jump, 0);
        //Debug.Log("Jump!");
    }

希望这有帮助:)

相关问题