处理平台游戏中两个矩形的交集
我正在 HTML5/Canvas/Javascript/jQuery 中开发一个简单的平台游戏。您可以在此处查看它。
我知道如何检查两个矩形的交集(这里有几个与此相关的问题),并且我的游戏检查并处理两个矩形的交集,但仅在非常特定的情况下,并且仅因为角色是不比我的街区宽。
我的问题:如何计算两个矩形的交集,以便我可以知道交集发生在哪个方向?我能想到的唯一方法包括 20 多个 if 语句(这不是正确的方法吗?)。
我需要知道相交的方向,因为我“窥视”前方,看看我的精灵坐标 (x + dx, y + dy) 是否会与矩形相交,如果会相交,则将精灵的新坐标设置为矩形的边缘下一个刻度上的矩形。
I am working on a simple platform game in HTML5/Canvas/Javascript/jQuery. You can see it here.
I'm aware of how to check the intersection of two rectangles (there are several questions on here regarding that), and my game checks and handles the intersection of the two rectangles, but only under very specific circumstances, and only because the character is not wider than my block.
My question: how do I calculate the intersection of two rectangles in a way which I can tell which direction the intersection occurs from? The only way I can think of includes 20+ if statements (this cannot be the proper way?).
I need to know the direction of intersection because I "peek" ahead to see if my sprite coordinates (x + dx, y + dy) will intersect a rectangle, and if they will, set the sprite's new coordinates to just the edge of the rectangle on the next tick.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要获取矩形相对于另一个矩形的位置,您可以使用精灵矩形的中心并获取其相对于块的位置。
以下函数是获取一个点到另一个点的位置。它应该对你有帮助。只需要使用精灵的中心和块的中心进行调整以验证精灵到块的位置(或验证精灵中心到块的左上角和右下角的位置)
编辑:全部当考虑 x 和 y 轴原点位于视口的左上角时,这很好
To get the position of a rectangle relatively to an other, you could use the center the sprite rectangle and get its position to the block.
The following function is to get position of a point to another. It should help you. Just need to adapt to verify the position of your sprite to your block using the center of the sprite and the center of the block (or verify the position of the sprite center to the top left and bottom right corners of the block)
EDIT : all of this is good when considering x and y axis origin is at top left corner of viewport