JuniorCodeCommonNot answered yet
How do you move an object at a constant speed from point A to point B?
Inside an actor's Tick, move it at a constant speed from its current location toward PointB, stopping exactly on arrival.
Constraints:
- Use a normalized direction so the speed does not depend on the A→B distance.
- Multiply the per-frame step by
DeltaTimeso the speed is framerate-independent. - Clamp the final step to the remaining distance — snap onto
PointB, do not overshoot.
void AMover::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// your code here
}
Write the implementation.
Compute the normalized direction (B - A).GetSafeNormal(), then each frame add Direction * Speed * DeltaTime to the location. Multiplying by DeltaTime keeps the speed framerate-independent; stop when the remaining distance is reached.
- ✗Forgetting
* DeltaTime, so movement speed scales with the frame rate - ✗Using a non-normalized direction, making speed depend on the distance to B
- ✗Overshooting B because the last frame's step is not clamped to the remaining distance
- →How do you detect and snap to B exactly on the frame that would overshoot it?
- →How would constant-velocity movement differ from
VInterpTotoward B?
Constant-speed movement
// In the header: FVector PointA, PointB; float Speed = 300.0f;
void AMover::BeginPlay()
{
Super::BeginPlay();
PointA = GetActorLocation();
// PointB is set externally, e.g. in the editor
}
void AMover::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
const FVector Current = GetActorLocation();
const FVector ToTarget = PointB - Current;
const float Remaining = ToTarget.Size();
// This frame's step: speed × frame time (framerate-independent)
const float Step = Speed * DeltaTime;
if (Step >= Remaining)
{
// We would otherwise overshoot — snap exactly onto B
SetActorLocation(PointB);
SetActorTickEnabled(false);
return;
}
const FVector Direction = ToTarget.GetSafeNormal();
SetActorLocation(Current + Direction * Step);
}
Key points:
Directionis normalized, so the speed is independent of theA → Bdistance.- Multiplying by
DeltaTimegives the same speed at any frame rate. - The final frame checks
Step >= Remainingand snaps exactly ontoB, with no overshoot.