Ben Krueger
Ben Krueger

Reputation: 1546

TouchLocation object not working properly

I am trying to implement a press and release button functionality and am getting a non-working result that I can't figure out why.

public class Button
{
    public TouchLocation oldTouch, currentTouch;

    public virtual void Update(GameTime gameTime)
    {
        TouchCollection touchCollection = TouchPanel.GetState ();

        if (touchCollection.Count > 0) {
            currentTouch = touchCollection [0];

            if (currentTouch.Position.X > position.X && currentTouch.Position.X < position.X + width &&
               currentTouch.Position.Y > position.Y && currentTouch.Position.Y < position.Y + height) {

                if (currentTouch.State == TouchLocationState.Released && oldTouch.State == TouchLocationState.Pressed) {
                    buttonEvent.Invoke (this, new EventArgs ());
                }
            }
        }

        oldTouch = currentTouch;

    }
}

First of all when I assign the below object:

currentTouch = touchCollection [0];

I get

"Incorrect number of types or arguments"

in red as the value in the locals debug window (no error, just red texted value).
It still however correctly passes through the position checking IF statement but it does not pass the Pressed/Release IF statement. If I replace currentTouch with touchCollection[0] then everything works as expected.
Am I using/assigning the TouchLocation object incorrectly?
Or am I maybe just overlooking an easy mistake?

Upvotes: 1

Views: 205

Answers (1)

pinckerman
pinckerman

Reputation: 4213

I always use something like touchCollection.Last() or touchCollection.First() to get only one component of TouchCollection. Anyway I don't see any error in what you are doing there.

For your problem, I think you can't do only

oldTouch.State == TouchLocationState.Pressed

but you have to check:

oldTouch.State == TouchLocationState.Pressed || oldTouch.State == TouchLocationState.Moved

because you don't know how the last touch was detected by XNA.

And as a suggestion, why don't you use Rectangles for your button's collider? In this way you can simply call:

Rectangle.Contains(new Point(int)currentTouch.Position.X, (int)currentTouch.Position.Y))

instead of doing that if statement.

Upvotes: 2

Related Questions