2012-02-17 161 views
2

我一個簡單的遊戲,你在廣場的精靈點擊它們消失前的工作採摘旋轉精靈。我決定變得花哨,並使方塊旋轉。現在,當我點擊廣場時,他們並不總是響應點擊。我認爲我需要圍繞矩形的中心(方形)旋轉點擊位置,但我不知道如何做到這一點。這裏是我的鼠標點擊代碼:鼠標XNA遊戲

if ((mouse.LeftButton == ButtonState.Pressed) && 
    (currentSquare.Contains(mouse.X , mouse.Y))) 

這裏是旋轉邏輯:

float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; 

     RotationAngle += elapsed; 
     float circle = MathHelper.Pi * 2; 
     RotationAngle = RotationAngle % circle; 

我是新來的XNA和編程一般,所以任何幫助表示讚賞。

非常感謝,

比爾

回答

1

所以你要確定一個點爲矩形,但是當矩形旋轉?

的包含()方法將僅在當前旋轉是0工作(I猜currentSquare是表示不旋轉圖像位置的矩形?)。

你需要做的是做反轉的圖像在鼠標座標上(鼠標座標應該圍繞圖像的原點旋轉),然後計算新的位置是否在currentSquare內。你應該能夠使用矢量做所有這些。 (未經測試)

bool MouseWithinRotatedRectangle(Rectangle area, Vector2 tmp_mousePosition, float angleRotation) 
{ 
    Vector2 mousePosition = tmp_mousePosition - currentSquare.Origin; 
    float mouseOriginalAngle = (float)Math.Atan(mousePosition.Y/mousePosition.X); 
    mousePosition = new Vector2((float)(Math.Cos(-angleRotation + mouseOriginalAngle) * mousePosition.Length()), 
           (float)(Math.Sin(-angleRotation + mouseOriginalAngle) * , mousePosition.Length())); 
    return area.Contains(mousePosition); 
} 
+0

你好,我仍然有點失落。這裏是我的Game.cs文件:pastebin.com/b4T3bKT3我有麻煩搞清楚如何使用你們給我的代碼。 – 2012-02-18 22:51:19

+0

你好,你還在堆棧溢出嗎?我想問你一些關於這個問題的更多的東西 – 2012-05-14 00:19:22

+0

什麼不起作用? – Msonic 2012-05-15 15:42:48

0

如果你是懶惰和我一樣,你可以只是做一個圓形的距離檢查。

假設鼠標和box.center是Vector2

#gets us C^2 according to the pythagorean Theorem 
var radius = (box.width/2).squared() + (box.height/2).square 

#distance check 
(mouse - box.center).LengthSquared() < radius 

不完全準確,但用戶將很難察覺的時間和離開擊中格不準確略有偏大總是原諒。更不用說檢查速度非常快,只需計算正方形創建時的半徑即可。

+0

你好,我仍然有點失落。這是我的Game.cs文件:http://pastebin.com/b4T3bKT3我無法弄清楚如何使用你們給我看的代碼。 – 2012-02-18 22:48:26

1

如果你不需要像素pefect檢測您可以爲每件這樣的包圍球。

 var PieceSphere = new BoundingSphere() 
         { 
          Center =new Vector3(new Vector2(Position.X + Width/2, Position.Y + Height/2), 0f), 
          Radius = Width/2 
         }; 

然後在鼠標指針周圍創建另一個邊界球。對於位置使用鼠標座標和半徑1f。由於鼠標指針將會移動,因此它將改變其座標,因此您還必須在每次更新時更新球體的中心。

檢查點擊會真的那麼簡單。

foreach(Piece p in AllPieces) 
{ 
    if ((mouse.LeftButton == ButtonState.Pressed) && p.BoundingSphere.Intersects(MouseBoundingSphere)) 
    { 
     //Do stuff 
    } 
} 
+0

我想實現這一點,我很難。 https://github.com/tertl2/squarechase_modded如果你有一分鐘​​,你可以把你的上面的代碼放入github並提交它。我不明白爲什麼我需要鼠標指針的邊界球體? – 2012-06-13 19:53:09

+0

什麼是Position.X,Width等...是那些新的變量,還是它們是正方形的位置? – 2012-06-13 19:57:00

+0

不好意思問,但AllPieces是什麼?我認爲我幾乎可以正常工作.. :)我只需要一點幫助:) – 2012-06-13 20:04:22