2011-09-23 73 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