如何将力添加到“刚体2D”游戏对象并使其以固定速度运动?游戏对象还附加了弹跳材质。
private Rigidbody2D rb2D;
private float thrust = 10.0f;
void Start() {
}
void FixedUpdate() {
rb2D.AddForce(new Vector2(0, 1) * thrust);
}
这是我从Unity文档网站获得的信息,但这似乎无济于事。
这是我最终使用的代码,它似乎运行正常。可以根据质量/重力来调整Vector2的方向和速度。
float topSpeed = 15;
private Rigidbody2D rb2D;
private float thrust = 0.1f;
void Start()
{
rb2D = gameObject.GetComponent<Rigidbody2D>();
rb2D.AddForce(new Vector2(0, 1) * thrust);
}
void Update()
{
if (rb2D.velocity.magnitude > topSpeed || rb2D.velocity.magnitude < topSpeed)
rb2D.velocity = rb2D.velocity.normalized * topSpeed;
}
答案 0 :(得分:1)
您编写的代码一旦起作用,将无限加速刚体。您需要将速度限制为最大速度:http://answers.unity.com/answers/330805/view.html
rigidbody.AddForce(new Vector2(0, 1) * thrust * Time.deltaTime);
if (rigidbody.velocity.magnitude > topSpeed)
rigidbody.velocity = rigidbody.velocity.normalized * topSpeed;
如果希望它立即将速度设置为固定值,则只需在每帧上设置速度:
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
void FixedUpdate()
{
if (Input.GetButtonDown("Jump"))
{
// the cube is going to move upwards in 10 units per second
rb2D.velocity = new Vector3(0, 10, 0);
moving = true;
Debug.Log("jump");
}
if (moving)
{
// when the cube has moved over 1 second report it's position
t = t + Time.deltaTime;
if (t > 1.0f)
{
Debug.Log(gameObject.transform.position.y + " : " + t);
t = 0.0f;
}
}
}
您的代码没有显示出来,以防万一您还没有这样做,您需要确保将rb2D
实际设置为要处理的对象上的Rigidbody2d。例如。通过执行start方法:
void Start()
{
rb2D = gameObject.GetComponent<Rigidbody2D>();
}