移动刚体游戏对象的正确方法 [英] Proper way to move Rigidbody GameObject

查看:27
本文介绍了移动刚体游戏对象的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习 Unity.我尝试使用此脚本进行简单的框移动.前提是,每当有人按下w"时,框就会向前移动.

I just started learning Unity. I tried to make a simple box move by using this script. The premise is, whenever someone presses 'w' the box moves forward.

public class PlayerMover : MonoBehaviour {

public float speed;
private Rigidbody rb;


public void Start () {
    rb = GetComponent<Rigidbody>();
}

public void Update () {
    bool w = Input.GetButton("w");

    if (w) {
        Vector3 move = new Vector3(0, 0, 1) * speed;
        rb.MovePosition(move);
        Debug.Log("Moved using w key");

    }

}
}

每当我使用它时,框都不会在w"按键上向前移动.我的代码有什么问题?我想这可能是我设置 Vector 3 move 的方式,所以我尝试用速度替换 z 轴,但这没有用.有人能告诉我我哪里搞砸了吗?

Whenever I use this, the box doesn't move forward on a 'w' keypress. What is wrong with my code? I thought it might be the way I have my Vector 3 move set up so I tried replacing the z-axis with speed, but that didn't work. Could someone tell me where I am messing up?

推荐答案

您使用 Rigidbody.MovePosition 并使用 Rigidbody.MoveRotation 如果您希望它与周围的对象正确碰撞.Rigidbody 不应因它们的位置、旋转或平移变量/函数而移动.

You move Rigidbody with Rigidbody.MovePosition and rotate it with Rigidbody.MoveRotation if you want it to properly collide with Objects around it. Rigidbody should not be moved by their position, rotation or the Translate variables/function.

w"不是像提到的 SherinBinu 那样预定义的,但这并不是唯一的问题.如果您定义它并使用 KeyCode.W 它仍然不起作用.对象将移动一次并停止.

The "w" is not predefined like SherinBinu mentioned but that's not the only problem. If you define it and use KeyCode.W it still won't work. The object will move once and stop.

改变

Vector3 move = new Vector3(0, 0, 1) * speed;
rb.MovePosition(move);

tempVect = tempVect.normalized * speed * Time.deltaTime;
rb.MovePosition(transform.position + tempVect);

应该这样做:

public float speed;
private Rigidbody rb;


public void Start()
{
    rb = GetComponent<Rigidbody>();
}

public void Update()
{
    bool w = Input.GetKey(KeyCode.W);

    if (w)
    {
        Vector3 tempVect = new Vector3(0, 0, 1);
        tempVect = tempVect.normalized * speed * Time.deltaTime;
        rb.MovePosition(transform.position + tempVect);
    }
}

<小时>

最后,我想你想用 wasd 键移动你的对象.如果是这种情况,则使用 Input.GetAxisRawInput.GetAxis.

public void Update()
{
    float h = Input.GetAxisRaw("Horizontal");
    float v = Input.GetAxisRaw("Vertical");

    Vector3 tempVect = new Vector3(h, 0, v);
    tempVect = tempVect.normalized * speed * Time.deltaTime;
    rb.MovePosition(transform.position + tempVect);
}

这篇关于移动刚体游戏对象的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆