2011-09-23 56 views
1

我正在使用图像在屏幕上飞行的应用程序。 我需要实现:在XNA中拖动图像

  1. 不放任何飞行图像的自来水
  2. 拖动图像到用户选择的某一位置通过让用户拿着它。

回答

1

当你加载你的形象,你需要一个BoundingBox的或矩形对象来控制它在哪里。

因此,在手机上的XNA应用程序中,应该为纹理声明几个对象。

Texture2D texture; 
BoundingBox bBox; 
Vector2 position; 
bool selected; 

然后,在加载图像内容后,请使用图像位置更新边界框。

bBox.Min = new Vector3(position, 1.0f); 
bBox.Max = new Vector3(position.X + texture.Width, position.Y + texture.Height, 0f); 

也会显示在您更新方法,你应该有一个触摸集合初始化为从画面处理输入,得到了触摸集合的位置,依次通过他们,看看他们是否相交您的外接矩形框。

foreach (Vector2 pos in touchPositions) 
{ 
    BoundingBox bb = new BoundingBox(); 
    bb.Min = new Vector3(pos, 1.0f); 
    bb.Max = new Vector3(pos, 0f); 

    if (bb.Intersects(bBox) 
    { 
     if (selected) 
     { 
      //do something 
     } 
     else 
     { 
      selected = true; 
     } 
    } 
} 

从那里,你有你的对象是否被选中或没有。然后,只需使用手势事件来确定您想要对纹理对象执行什么操作。

3

这是另一种简单的拖动方法。 只需绘制您的图像(Texture2d)相对于矩形而不是Vector2。 您的图片变量应该是这样的

Texture2d image; 
Rectangle imageRect; 

在draw()方法对于“imageRect”画出你的形象。

spriteBatch.Draw(image,imageRect,Color.White); 

现在在Update()方法中用单点触摸输入处理图像。

//Move your image with your logic 

TouchCollection touchLocations = TouchPanel.GetState(); 
foreach(TouchLocation touchLocation in touchLocations) 
{ 
    Rectangle touchRect = new Rectangle 
    (touchLocation.Position.X,touchLocation.Position.Y,10,10); 
    if(touchLocation.State == TouchLocationState.Moved 
    && imageRect.Intersects(touchRect)) 
    { 
    imageRect.X = touchRect.X; 
    imageRect.Y = touchRect.Y; 
    } 
//you can bring more beauty by bringing centre point 
//of imageRect instead of initial point by adding width 
//and height to X and Y respectively and divide it by 2