正确的方法来移动刚体GameObject [英] Proper way to move Rigidbody GameObject

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

问题描述

我刚刚开始学习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.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);
}

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

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