在XNA中拖动图像

时间:2011-09-23 06:32:46

标签: windows-phone-7 xna xna-4.0

我正在制作一个应用程序,其中图像在屏幕上飞行。 我需要实现:

  1. 抓住Tap上的任何飞行图像
  2. 通过让用户按住图像,将图像拖动到用户选择的某个位置。

3 个答案:

答案 0 :(得分:3)

这是另一种简单的拖动方式。 只需相对于Rectangle而不是Vector2绘制图像(Texture2d)。 您的图像变量应如下所示

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

答案 1 :(得分:2)

答案 2 :(得分:1)

当你加载图像时,你需要一个BoundingBox或Rectangle Object来控制它的位置。

因此,在手机上的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;
       }
   }
}

从那里,您可以选择是否选择了对象。然后只需使用手势事件来确定您想要对纹理对象执行的操作。