2013-10-27 110 views
1

我试图实现新闻和发布按钮功能,并得到一个非工作的结果,我不明白为什么。TouchLocation对象无法正常工作

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; 

    } 
} 

首先,当我给你以下对象:

currentTouch = touchCollection [0]; 

我得到

红色

为 “的类型或参数数目不正确”在本地调试窗口中的值(没有错误,只是红色的短信值)。
它仍然正确地通过检查IF语句的位置,但它不通过Pressed/Release IF语句。如果我用touchCollection[0]替换currentTouch,那么一切都按预期工作。
我是否正确使用/分配了TouchLocation对象?
或者我可能只是忽略了一个简单的错误?

回答

2

我总是用touchCollection.Last()touchCollection.First()这样的东西来得到TouchCollection的一个组件。无论如何,我没有看到你在那里做什么错误。

对于你的问题,我认为你不能只做

oldTouch.State == TouchLocationState.Pressed 

,但你必须检查:

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

,因为你不知道最后的接触是如何被检测到XNA 。

作为一个建议,你为什么不使用Rectangle作为你的按钮的对撞机?通过这种方式,您可以简单地致电:

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

而不是这样做if声明。