Difficulty with projectile's tracking code

Posted by RCIX on Stack Overflow See other posts from Stack Overflow or by RCIX
Published on 2010-05-12T02:50:52Z Indexed on 2010/05/12 2:54 UTC
Read the original article Hit count: 326

I wrote some code for a projectile class in my game that makes it track targets if it can:

            if (_target != null && !_target.IsDead)
            {
                Vector2 currentDirectionVector = this.Body.LinearVelocity;
                currentDirectionVector.Normalize();
                float currentDirection = (float)Math.Atan2(currentDirectionVector.Y, currentDirectionVector.X);
                Vector2 targetDirectionVector = this._target.Position - this.Position;
                targetDirectionVector.Normalize();
                float targetDirection = (float)Math.Atan2(targetDirectionVector.Y, targetDirectionVector.X);
                float targetDirectionDelta = targetDirection - currentDirection;
                if (MathFunctions.IsInRange(targetDirectionDelta, -(Info.TrackingRate * deltaTime), Info.TrackingRate * deltaTime))
                {
                    Body.LinearVelocity = targetDirectionVector * Info.FiringVelocity;
                }
                else if (targetDirectionDelta > 0)
                {
                    float newDirection = currentDirection + Info.TrackingRate * deltaTime;
                    Body.LinearVelocity = new Vector2(
                        (float)Math.Cos(newDirection),
                        (float)Math.Sin(newDirection)) * Info.FiringVelocity;
                }
                else if (targetDirectionDelta < 0)
                {
                    float newDirection = currentDirection - Info.TrackingRate * deltaTime;
                    Body.LinearVelocity = new Vector2(
                        (float)Math.Cos(newDirection),
                        (float)Math.Sin(newDirection)) * Info.FiringVelocity;
                }
            }

This works sometimes, but depending on the relative angle to the target projectiles turn away from the target instead. I'm stumped; can someone point out the flaw in my code?

© Stack Overflow or respective owner

Related posts about c#

Related posts about trigonometry