0
\$\begingroup\$

I use the unreal engine 4 to bounce a ball off of walls in a 2D space, but over time the ball gets slower and slower.

Movement happens in the tick function of the ball

FVector location = GetActorLocation();

location.X += this->Velocity.X * DeltaSeconds;
location.Y += this->Velocity.Y * DeltaSeconds;

SetActorLocation(location, true);

When a wall gets hit I get a Hit Event with the normal of the collision. This is how I calculate the new velocity of the ball:

FVector2D V = this->Velocity;
FVector2D N = FVector2D(HitNormal.X, HitNormal.Y);

FVector2D newVelocity = -2 * (V.X * N.X + V.Y * N.Y) * N + V;

this->Velocity = newVelocity;

Over time, the more the ball bounced around, the velocity gets smaller and smaller. How do I prevent speed loss when bouncing off walls like that? It's supposed to be a perfect bounce without friction or anything.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

One way to circumvent the accumulation of rounding errors is to re-normalize your vector when you calculate newVelocity. This might look like such:

FVector2D V = this->Velocity;
FVector2D N = FVector2D(HitNormal.X, HitNormal.Y);

FVector2D newVelocity = -2 * (V.X * N.X + V.Y * N.Y) * N + V;
newVelocity *= targetSpeed / newVelocity.Size();

this->Velocity = newVelocity;
\$\endgroup\$
0

You must log in to answer this question.

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