Skip to main content
1 of 2
DMGregory
  • 136.3k
  • 22
  • 247
  • 373

It looks like you're trying to implement a MoveTowards function. Try something more like this:

def moveTowards(mover, target, maxStep):

    deltaX = target.x - mover.x
    deltaY = target.y - mover.y

    mag = deltaX * deltaX + deltaY * deltaY

    if mag < maxStep * maxStep:
        mover.x = target.x
        mover.y = target.y 
    else:
        scale = maxStep / sqrt(mag)
    
        mover.x += deltaX * scale
        mover.y += deltaY * scale

Call this with moveTowards(obj, anchor, speed * dt).

This version...

  • Moves the object at most a distance of maxStep toward the target.

  • When the target is closer than maxStep, it snaps the object directly to the target, with no under- or over-shooting.

  • Uses no trigonometric functions, and no transcendentals at all when within one step of the target. It also handles all angles correctly, unlike the sample code (hint: you probably want atan2 when trying to find an angle from two coordinates)

You should also consider using a fixed timestep for your game simulation, so it's not subject to variation depending on the rendering framerate.

DMGregory
  • 136.3k
  • 22
  • 247
  • 373