简体   繁体   中英

How to check if wp7 XNA touch event is within a defined rectangle

I want to check if a user click is within a set of retangles I have defined, but should I do it another way to do this check?

This is what I have now, but I am in doubt how to compare the rectangle object with the touches object

private bool CheckEnemyClicked(Vector2 vector2, out Enemy enemyOut)
{
    TouchCollection touches = TouchPanel.GetState();

    foreach (Enemy enemy in enemies)
    {
        //Find the rectangle of the sprite
        Rectangle rectangle = new Rectangle(
                                  (int)enemy.Position.X, 
                                  (int)enemy.Position.Y, 
                                  enemy.Width, 
                                  enemy.Height);

        //Check if click is hitting enemy
        if(touchinput is within rectangle)
        {
            enemyOut = enemy;
            return true;
        }
    }
    enemyOut = null;
    return false;
}

TouchCollection returns a collection of TouchLocation objects which has a "Position" member. Rectangle has a Contains method which has an overload that can check if a particular point is contained within it. So the XNA framework does all the hard work for you.

Your code would look something like this for the collision checking part for Touch.

//Check if click is hitting enemy
foreach (TouchLocation location in collection)
{
     if (rectangle.Contains((int)location.Position.X, (int)location.Position.Y))
     {
          enemyOut = enemy;
          return true;
     }
}

TouchCollection is a collection of touch points (as user may be touching the screen in several places). You should check for the individual touch points within the TouchCollection and find the position of those relative to your enemy rectangle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM