2
\$\begingroup\$

I know things similar to this have been posted, but I'm still trying to find a good solution... I'm drawing Texture2D objects on the ground in my game, and for Mouse-Over or targeting methods, I'm detecting whether or not the pixel in that Texture at the mouse position is Color.Transparent. This works perfectly when I do not rotate the texture, but I'd like to be able to rotate textures to add realism/variety. However, I either need to create a new Texture2D that is rotated at the correct angle so that I can detect its pixels, or I need to find some other method of detection... Any thoughts?

\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

You need to convert the mouse position to image coordinates by 'reverse' rotating the mouse vector. Technically, what you are doing is transforming the mouse position from screen coordinates to image coordinates.

  1. get the position of the mouse relative to the position of the image
  2. rotate this vector by the inverse of the angle the image was rotated
  3. use this new vector to inspect the pixel

     protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();
    
        // TODO: Add your update logic here
        MouseState ms=Mouse.GetState();
    
        //convert mouse position to a vector
        Vector2 mPos = new Vector2(ms.X, ms.Y);
    
        //get mouse position relative to image position
        mPos = mPos - spritePos;
    
        //rotate the relative mouse vector in the opposite angle that we rotated the image
        Matrix rot = Matrix.CreateRotationZ(-spriteAngle);
        mPos = Vector2.Transform(mPos,rot);
        //add the image origin (if used in drawing)
        mPos += imageOrigin;
        //now the mouse position is Image coordinates
        //convert mouse position to a point for next stage
        Point mP=new Point((int)mPos.X,(int)mPos.Y);
    
        if(imageRect.Contains(mP)){// check if point is in the image rectangle
            //get the index of the pixel in the color array
            int index = mP.X +mP.Y * image.Width;
    
            if (imageData[index] == Color.Transparent)
            {
                //do stuff;
            }
    
        }
        base.Update(gameTime);
    }
    
\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .