使用 Vector2 系列创建形状 - XNA
在我的 XNA 游戏中,我需要基于 2D 空间中的多个 Vector2 坐标定义不规则形状。原因是要进行碰撞检查(如 Rectangle.Intersects() )。
例如:
Vector2 point1 = new Vector(20,30);
Vector2 point2 = new Vector(60,30);
Vector2 point3 = new Vector(60,80);
Vector2 point4 = new Vector(40,90);
Vector2 point5 = new Vector(20,80);
将创建一个具有从 point1
-> 出发的路径的形状。 点2
-> point3
-> point4
-> point5
然后返回point1
。
但是我找不到合适的解决方案来实现这一点。请帮忙。谢谢。
In my XNA game, I needed to define an irregular shape based on several Vector2 coordinates in the 2D space. The reason was to do collision check (like Rectangle.Intersects()
).
For example:
Vector2 point1 = new Vector(20,30);
Vector2 point2 = new Vector(60,30);
Vector2 point3 = new Vector(60,80);
Vector2 point4 = new Vector(40,90);
Vector2 point5 = new Vector(20,80);
would create a shape that has paths that goes from point1
-> point2
-> point3
-> point4
-> point5
then back to point1
.
However I couldn't find a proper solution to implement this. Please help. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于您想要做的事情,有几种不同的方法。您提到了碰撞检测:您想确定一个点是否与形状相交,还是想确定两个多边形是否相交?
如果您想要一个点,您要查找的内容称为“多边形测试中的点”。有许多不同的方法,但最快、最直接的方法之一是射线测试。您从您的点创建一条射线并计算它穿过边缘的次数。如果数字是偶数,则该点在外部。如果是奇数,则该点在内部。
您可以在这里找到一篇关于此的好文章: http:// www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
文章中的代码实现如下所示:
确定两个多边形是否相交更复杂,但并非完全不同。许多游戏实际上只是使用多边形点检查多边形的角点,因为它既简单又便宜,但也可以检查完整的交点。
实现它的一种方法是将每条边视为分割平面/半空间。半空间的交集确定两个多边形是否相交。
尝试搜索“分离轴定理”。
There are a couple of different approaches to what you want to do. You mentioned collision detection: do you want to determine if a point intersects the shape, or do you want to determine if two polygons intersect?
If you want a point, what you're looking for is called a "point in polygon test". There are a number of different approaches, but one of the quickest and most straight forward approaches is a ray test. You create a ray from your point and count the number of times it crosses the edges. If the number is even, the point is outside. If it's odd, the point is inside.
You can find a good article on this here: http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
The code implementation from the article looks like so:
Determining if two polygons intersect is more complicated, but not entirely dissimilar. A lot of games actually just check the corners of the polygons with point-in-poly as its easy and cheap, but it is possible to check the complete intersection as well.
One way you can approach it is to treat each edge as a dividing plane / halfspace. The intersection of the halfspaces determines if the two polygons intersect.
Try searching for "Separating Axis Theorem".
ZiggyWare(以前是 www.ziggyware.com)有一个关于 2D 多边形碰撞检测的教程,但 ZW 似乎正在搬到新家。 这里有一个视频,介绍了教程的外观。
ZiggyWare (formerly www.ziggyware.com) have a tutorial on 2D polygon collision detection but it seems that ZW is in the process of moving to a new home. Here's a video though, of how the tutorial looks like.