Search code examples
c#monogame

enemy ship rotates towards the player but does not lock into position


when my enemy ship moves towards the player i find the distance between them with

private float FindDistance(Vector2 heroCenter, Vector2 spritePos)
{
    var deltaX = Math.Pow((spritePos.X - heroCenter.X), 2); // the 2 is the power value (into the power of 2)
    var deltaY = Math.Pow((spritePos.Y - heroCenter.Y), 2);
    float distance = (float)Math.Sqrt(deltaX + deltaY);
    return distance; // returns the distance between the two objects
}

then I calculate the enemy ship angle of rotation with this code

distanceFromHero = FindDistance(Constants.heroCenter, spritePos);
if (distanceFromHero < Constants.HeroWithinRange)
{
    heroClose = true;
    VelocityX *= .985f; // enemy reduces vel X
    VelocityY *= .985f; // enemy reduces vel Y
    //atan2 for angle
    var radians = Math.Atan2((spritePos.Y - Constants.heroCenter.Y), (spritePos.X - Constants.heroCenter.X));
    //radians into degrees
    rotationAngle = (float)(radians * (180 / Math.PI));
}
else
{
    heroClose = false;
}

but strangely the enemy though moving towards the player does not lock on and stay steady but does a pendulum like movement and when they at the same point the enemy ship rotate endlessly. Some help with code would help.


Solution

  • The perfect answer to my question i found in an XBox forum which couldn't loaded into Visual Studio 2017 so I made a new solution. Hope others can benefit from this excellent tutorial made by Microsoft. The Solution is here.