矩形之间的2D碰撞检测 [英] Collision detection 2D between rectangles

查看:38
本文介绍了矩形之间的2D碰撞检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的游戏编写碰撞检测引擎,但遇到了一些问题.

I am writting a collision detection engine for my game and I have some problems.

确实,因为我有几个固定的矩形和一个移动的(玩家),所以我需要知道玩家首先碰撞了固定矩形的哪一侧,以正确替换他.

Indeed, since I have several fixed rectangle and one moving (the player), I need to know which side of the fixed one was collided at first by the player, to replace him correctly.

固定矩形不在网格中,因此它们可以放置在地图上的任何位置,并且它们的大小可以不同.它们没有旋转.

The fixed rectangle are NOT in a grid so they can be placed anywhere on the map and they can have diffents size. They are not rotated.

玩家类存储它的方向向量.

The player class stores it's direction vector.

有什么想法吗?

风筝

推荐答案

简而言之:
您将相互比较边界矩形的 Y 和 X 分量以检查碰撞.如果玩家的顶部(Y)小于敌人的底部,那么您就不需要再检查了,因为它们不可能发生碰撞.如果玩家的右侧(X)小于敌人的左侧,那么他们就不会发生碰撞.定义您打算在类中检查的每个对象的顶部、右侧、底部和左侧会有所帮助.这将使您也知道哪一侧被击中.这应该足以让您思考和尝试.
玩得开心!

In a nutshell:
You'll compare the Y and X components of the bounding rectangles to eachother to check for a collision. If the top(Y) of the player is less than the bottom of an enemy then you don't need to check anymore because it's not possible that they're colliding. If the right(X) side of the player is less than the left side of the enemy then they can't be colliding. It would help to define top, right, bottom, left of each object you intend to check inside the class. This will allow you to know which side is hit also. This should be enough to get you thinking and experimenting.
Have fun!

这篇关于矩形之间的2D碰撞检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆