Use rigidbody2D.velocity instead of MoveTowards

Hello everybody!

I am trying to make an gameObject 1 to go from one point towards another. Together with this I want an another object 2 attached to the first to rotate following the direction of the velocity of 1. Right now to move the 1 I am using Vector2.MoveTowards, like this:

    rb.position = Vector2.MoveTowards(transform.position, wayPoints[randomSpot].position, speed * Time.deltaTime);

However, by doing this I have seen that the velocity of the rigidbody is always (0, 0). Is there a way to use velocity to perform this movement?
Any suggestion would be appreciated!

2 Answers

2

Try this

var position = Vector2.MoveTowards(transform.position, wayPoints[randomSpot].position, speed * Time.deltaTime);
rb.MovePosition(position);

Sadly it has the same result, rb.velocity is still (0, 0). I was wondering if there is a way from MovePosition to derive the mean velocity for instance?

Sometimes you have to calculate velocity yourself.

var velocity = (currentPosition - lastPosition) / Time.deltaTime;

I wanted to try something similar, however I am not sure how to store and update the lastPosition for each frame :/