0
\$\begingroup\$

Im trying to get a rigidbody2D to move around and got it working with this script:

public class RubyController : MonoBehaviour
{
public Rigidbody2D rigidbody2d;
public float speed = 5.0f;
Vector2 movement;

void Start()
{
    rigidbody2d = GetComponent<Rigidbody2D>();
}

void Update()
{
    movement.x = Input.GetAxis("Horizontal");
    movement.y = Input.GetAxis("Vertical");
}

private void FixedUpdate()
{
    rigidbody2d.MovePosition(rigidbody2d.position + movement * speed * Time.deltaTime);
}

but not with this, and I can't understand why:

public class RubyController : MonoBehaviour
{
public Rigidbody2D rb2d;
float horizontal;
float vertical;
public float speed = 5f;

private void Start()
{
    rb2d = GetComponent<Rigidbody2D>();
}

private void Update()
{
    horizontal = Input.GetAxis("Horizontal");
    vertical = Input.GetAxis("Vertical");
}

private void FixedUpdate()
{
    Vector2 position = this.rb2d.position;
    position.x = position.x * speed * horizontal * Time.deltaTime;
    position.y = position.y * speed * vertical * Time.deltaTime;

    rb2d.MovePosition(position);
}
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ It looks like maybe you wrote a * where you meant to write a +? \$\endgroup\$
    – DMGregory
    Jun 16 '20 at 18:13
  • \$\begingroup\$ Omg sorry! Yes! Should have taken a break before posting! Ty so much! \$\endgroup\$ Jun 16 '20 at 18:17
1
\$\begingroup\$

It looks like you want:

private void FixedUpdate()
{
    Vector2 position = this.rb2d.position;
    position.x = position.x + speed * horizontal * Time.deltaTime;
    position.y = position.y + speed * vertical * Time.deltaTime;

    rb2d.MovePosition(position);
}

Note that the operator before speed is a + for addition (we want to add this frame's movement to the current position), not a * for multiplication (multiplying our position by this frame's movement... doesn't make much sense geometrically)

Or, a little less typing:

private void FixedUpdate()
{
    Vector2 position = rb2d.position;
    position.x += speed * horizontal * Time.deltaTime;
    position.y += speed * vertical * Time.deltaTime;

    rb2d.MovePosition(position);
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .