Shachar Weis
Shachar Weis

Reputation: 946

Translating screen coordinates to sprite coordinates in XNA

I have a sprite object in XNA.
It has a size, position and rotation.
How to translate a point from the screen coordinates to the sprite coordinates ?
Thanks,
SW

Upvotes: 0

Views: 3621

Answers (4)

Tom Gillen
Tom Gillen

Reputation: 364

You need to calculate the transform matrix for your sprite, invert that (so the transform now goes from world space -> local space) and transform the mouse position by the inverted matrix.

Matrix transform = Matrix.CreateScale(scale) * Matrix.CreateRotationZ(rotation) * Matrix.CreateTranslation(translation);

Matrix inverseTransform = Matrix.Invert(transform);
Vector3 transformedMousePosition = Vector3.Transform(mousePosition, inverseTransform);

Upvotes: 3

rysama
rysama

Reputation: 1796

You might find the following XNA picking sample useful:

http://creators.xna.com/en-us/sample/picking

Upvotes: 0

Ryan Lundy
Ryan Lundy

Reputation: 210190

I think it may be as simple as using the Contains method on Rectangle, the rectangle being the bounding box of your sprite. I've implemented drag-and-drop this way in XNA; I believe Contains tests based on x and y being screen coordinates.

Upvotes: 0

Peter Lillevold
Peter Lillevold

Reputation: 33930

One solution is to hit test against the sprite's original, unrotated bounding box. So given the 2D screen vector (x,y):

  1. translate the 2D vector into local sprite space: (x,y) - (spritex,spritey)
  2. apply inverse sprite rotation
  3. perform hit testing against bounding box

The hit test can of course be made more accurate by taking into account the sprite shape.

Upvotes: 0

Related Questions