1
\$\begingroup\$

I am new to Monogame. I am currently developing a simple game, just to learn some basics of Monogame development. The idea here is to detect whether or not the user has tapped on a a rectangle (represented by moving sprite) and return true if they did or false if they did not, but it always returns false, even if I tap on the sprite. The pertaining functions are here:

// Part of Update function
protected override void Update(GameTime gameTime)
{
    touches = TouchPanel.GetState();

    if (CheckRectangleTouch(arlington.BoundingBox, touches)) 
    {
        arlington.spritePosition = new Vector2(200, 200); 
    }
    else 
    {
        arlington.spritePosition = new Vector2(100, 100); 
    }
}

// Collision function
private bool CheckRectangleTouch(Rectangle target, TouchCollection touchCollection)
{
    if (touchCollection.Count > 0) 
    {
        if (target.Contains(touchCollection[0].Position)) 
        {
            return true; 
        }
    }
    return false;
}

Any idea why is this code not working, or about a better method for collision detection?

\$\endgroup\$
0
\$\begingroup\$

The most likely reason that your sprite is not reacting to your touch is that you are touching at multiple places on the screen, according to Monogame, which probably don't all collide with the sprite. When you check for touch, you only check the first detected touch position, which here does not seem to come in contact with your sprite based on your results. The touch you are detecting is most likely on the sides of the phone where you are holding it or something similar. The solution to this is to check all of the touches within the TouchCollection instead of just the first one in the array.

private bool CheckRectangleTouch(Rectangle target, TouchCollection touchCollection)
    {
        if (touchCollection.Count > 0) 
        {
            foreach (var touch in touchCollection) 
            {
                if (target.Contains(touch.Position))
                {
                    return true;
                }
            }
        }
        return false;
    }

Note that in this version of the function, I am looping through the collection with a foreach loop and checking if any of the touches collide with the sprite, instead of just the first element.

\$\endgroup\$
1
  • \$\begingroup\$ This will work even when the sprite is moving, because the sprite's position does not change during this logic, just between iterations of it. \$\endgroup\$ – Pip Dec 9 '14 at 20:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.