0

I have a turret that predicts a moving targets position and fires a projectile to intersect.

The method it uses is based on the checked answer in this post (2d game : fire at a moving target by predicting intersection of projectile and unit)

and return a a float angle calculated with atan2, I also add TwoPI to remove negatives.

If I lerp the turrets movement like this

currentAngle = MathHelper.Lerp(currentAngle, newAngle, speed)'

It means the closer the turret gets the smaller steps it takes, lowering the rotation speed and the accuracy falls away.

If I use fixed steps doing something like this

if (_angle < newAngle)
{
    _angle += fixedStep;
}
if (_angle > newAngle)
{
    _angle -= fixedStep;
}

a somewhat better result but I lose the pinpoint accuracy where the angle can't get any closer than the size of the fixed step.

Is there a better way to do something like this?

The desired end result would be smooth movement over anything, with the turret able to accelerate or decelerate from a top speed as it needs to reach the correct angle, with some added inertia when suddenly having to rotate the other way.

Hopefully I can work some of it out eventually but any tips appreciated.

Community
  • 1
  • 1

1 Answers1

0

You can get this accuracy by seeing if you've "overshot" the angle movement using your fixed step. For example:

if (_angle < newAngle)
{
    _angle += fixedStep;
    if(_angle > targetAngle)
    {
        _angle = targetAngle;
    }
}
if (_angle > newAngle)
{
    _angle -= fixedStep;
    if(_angle < targetAngle)
    {
        _angle = targetAngle;
    }
}

Of course you may need to modify this code to account for wrapping angles (like -1 becoming 359) depending on how you are storing angles.

Victor Chelaru
  • 4,491
  • 3
  • 35
  • 49