处理平台游戏中两个矩形的交集

发布于 2024-10-28 15:50:17 字数 405 浏览 1 评论 0原文

我正在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流星番茄 2024-11-04 15:50:17

要获取矩形相对于另一个矩形的位置,您可以使用精灵矩形的中心并获取其相对于块的位置。
以下函数是获取一个点到另一个点的位置。它应该对你有帮助。只需要使用精灵的中心和块的中心进行调整以验证精灵到块的位置(或验证精灵中心到块的左上角和右下角的位置)

function positionOf(point, relativeTo) {
    var dx = point.x - relativeTo.x; // diff on x axis
    var dy = point.y - relativeTo.y; // diff on y axis

    if(dx >= dy) { // point is on top right half from relativeTo
             return dx >= - dy ? 'EAST' : 'NORTH';
    }
    else { // point is on bottom left half from relativeTo
             return dx >= - dy ? 'SOUTH' : 'WEST';
    }
}

编辑:全部当考虑 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)

function positionOf(point, relativeTo) {
    var dx = point.x - relativeTo.x; // diff on x axis
    var dy = point.y - relativeTo.y; // diff on y axis

    if(dx >= dy) { // point is on top right half from relativeTo
             return dx >= - dy ? 'EAST' : 'NORTH';
    }
    else { // point is on bottom left half from relativeTo
             return dx >= - dy ? 'SOUTH' : 'WEST';
    }
}

EDIT : all of this is good when considering x and y axis origin is at top left corner of viewport

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文