2012-02-17 126 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