Search code examples
c#xnaspritemonogame

Getting the position of the the tip of a sprite, while rotated


I want to get the position of the sprite while its rotated, Example

The bigger dot is the location i want to get (while rotated), and the sprite is rotated so its quite hard to get that, and im clueless of how to get it, the origin is (0,0) for anyone asking, is there any math that needs to be done to get this?


Solution

  • What you need to do is create a Vector2 from the origin to the rotated point before it's rotated and then rotate that vector.

    For example, let's say we have a sprite with the origin point in the center and we want to know where the front point will be when the sprite is rotated.

    enter image description here

    First, create a vector from the origin to the point you want rotated on the unrotated sprite. In this case it's probably going to be something like 20 pixels to the right of the center:

    var vector = new Vector2(20, 0);
    

    Now we can rotate our vector with this simple function (borrowed from MonoGame.Extended)

    public static Vector2 Rotate(Vector2 value, float radians)
    {
        var cos = (float) Math.Cos(radians);
        var sin = (float) Math.Sin(radians);
        return new Vector2(value.X*cos - value.Y*sin, value.X*sin + value.Y*cos);
    }.
    

    Now we can get our rotated vector like so:

    var radians = MathHelper.ToRadians(degrees: -33);
    var rotatedVector = Rotate(vector, radians);
    

    To get this vector back into "sprite" space we can add it back to our origin point:

    var point = origin + rotatedVector;
    

    Or alternately if you want it in "world" space you can also add it to your sprites position.

    var worldPoint = position + origin + rotatedVector;
    

    Happy coding!