Hello Unity noob here,
I had a question about moving a rigid body for a top-down RTS space game. In the game, the player controls a spaceship (attached to a rigid body) and can click on the map to move it to that position. I ideally want the ship to accelerate up to a maximum velocity and when it gets close to the target, decelerate. I really like the acceleration/deceleration effect that Lerp gives but it does not cap the velocity (i.e. the farther the distance the faster the maximum velocity on that journey). I understand that this is by design and thus I’m looking for ways to either modify Lerp or create an equivalent function which mirrors the acceleration/deceleration but caps the velocity. I have tried MoveTowards and AddForce methods but was dissatisfied with both (the former is too jerky and AddForce is not accurate enough to stop the ship on the target). Any suggestions? Thanks in advance!
Below is what I have so far in my FixedUpdate(). “velocity” is my maximum velocity but obviously the way I used it doesn’t work in this context.
void FixedUpdate()
{
Vector2 player_position = new Vector2(player_body.position.x, player_body.position.y);
if (rotating)
{
float angle = Mathf.Atan2(current_direction.y, current_direction.x) * Mathf.Rad2Deg;
player_body.rotation = Mathf.LerpAngle(player_body.rotation, Quaternion.AngleAxis(angle - 90, Vector3.forward).eulerAngles.z, angular_velocity * Time.fixedDeltaTime);
rotating = Mathf.Abs(player_body.rotation - angle) < 0.001f ? false : true;
}
if (moving)
{
player_body.MovePosition(Vector2.Lerp(player_position, current_destination, Time.fixedDeltaTime * velocity));
moving = Vector3.Distance(transform.position, current_destination) <= 0.001f ? false : true;
}
}