我目前正在C#中使用GDI+开发2D游戏引擎,并且已经达到了添加简单碰撞检测的程度。
到目前为止,我可以使用以下代码检查我的玩家是否与另一个游戏对象相交:
public static bool IntersectGameObject(GameObject a, GameObject b)
{
Rectangle rect1 = new Rectangle((int)a.Position.X, (int)a.Position.Y, a.Sprite.Bitmap.Width, a.Sprite.Bitmap.Height);
Rectangle rect2 = new Rectangle((int)b.Position.X, (int)b.Position.Y, b.Sprite.Bitmap.Width, b.Sprite.Bitmap.Height);
return rect1.IntersectsWith(rect2);
}
这太棒了,我很高兴我走了这么远,但是我想知道我的玩家是否与游戏对象的顶部、底部、左边或右侧相交,这样我就可以阻止我的玩家朝那个方向移动。他与一堵墙相撞。我该怎么做呢?有人能帮我吗?)
顺便说一句,游戏对象有位图,都是32 * 32像素,所以我不需要每个像素碰撞
(预先谢谢:)
发布于 2017-01-09 00:11:09
计算两个矩形是否相交只是几个比较问题(我知道您已经在使用IntersectsWith
):
if (Left > other.Right) return false;
if (Right < other.Left) return false;
if (Top > other.Bottom) return false;
if (Bottom < other.Top) return false;
return true;
为了确定碰撞的方向,你必须考虑到这样的可能性:
无论如何,要确定它是否在左侧发生了碰撞:
if (Right > other.Left && Right < other.Right && Left < other.Left)
{
// the right side of "this" rectangle is INSIDE the other
// and the left side of "this" rectangle is to the left of it
}
最后但并非最不重要的一点是,如果您正在逐帧计算此帧,则有可能一个对象“跳过”另一个对象。对于更现实的物理,你必须跟踪时间,并计算它何时会与矩形(每边)相交。
发布于 2017-01-10 04:27:27
如果您正在逐帧处理,一个很好的选择可能是存储上一个位置P0x,P0y
和当前位置P1x,P1y
。
然后,你可以计算一个向量Vx,Vy,你可以计算交点Ix,Iy
。这样你就能得到更精确的碰撞信息。
发布于 2017-01-08 23:10:03
如果你需要碰撞检测,你需要一个刚体,你通常用物理来移动刚体。据我所见,上面的代码片段可能会出现问题。如果你用变换移动它们,你应该标记为是运动学的。这意味着它不会被物理所动,而是会被变换所动。
一个运动刚体,你想要移动,应该做在FixedUpdate期间,以适当地应用碰撞。
如果你想知道你撞到哪一边,你可以用光线投射到物体上。
这个代码片段给出了一个例子,它显示了您可以在碰撞时执行的光线投射。最终,您使用的是哪个游戏引擎?
//this ray will generate a vector which points from the center of
//the falling object TO object hit. You subtract where you want to go from where you are
Ray MyRay = ObjectHit.position - ObjectFalling.position;
//this will declare a variable which will store information about the object hit
raycasthit MyRayHit;
//this is the actual raycast
raycast(MyRay, out MyRayHit);
//this will get the normal of the point hit, if you dont understand what a normal is
//wikipedia is your friend, its a simple idea, its a line which is tangent to a plane
vector3 MyNormal = MyRayHit.normal;
//this will convert that normal from being relative to global axis to relative to an
//objects local axis
MyNormal = MyRayHit.transform.transformdirection(MyNormal);
//this next line will compare the normal hit to the normals of each plane to find the
//side hit
if(MyNormal == MyRayHit.transform.up)
{
you hit the top plane, act accordingly
}
//important note the use of the '-' sign this inverts the direction, -up == down. Down doesn't exist as a stored direction, you invert up to get it.
if(MyNormal == -MyRayHit.transform.up)
{
you hit the bottom plane act accordingly
}
if(MyNormal == MyRayHit.transform.right)
{
hit right
}
//note the '-' sign converting right to left
if(MyNormal == -MyRayHit.transform.right)
{
hit left
}
https://stackoverflow.com/questions/41542507
复制相似问题