mat*_*ory 5 java collision-detection tile
我正在使用瓷砖制作java游戏.我遇到了碰撞元件的问题.我为地图上的每个图块定义矩形,为播放器定义另一个矩形.我遇到麻烦的是知道玩家在撞到矩形时从哪一边来,然后按照玩家来自的方向推动玩家.我已经创建了一个方法来检查字符在矩形内的多少,因此它可以知道将它推出多少,但我无法弄清楚如何判断字符来自哪一方.
这是我当前的碰撞方法 - 注意rect1是字符,rect2是tile
public void collision(Rectangle rect1, Rectangle rect2) {
float xAdd;
float xAdd2;
float yAdd;
float yAdd2;
boolean hitRight = false;
boolean hitLeft = false;
boolean hitTop = false;
boolean hitBot = false;
Vector2f rect1Origin = new Vector2f(rect1.x, rect1.y);
Vector2f rect2Origin = new Vector2f(rect2.x, rect2.y);
Vector2f rect1Mid = new Vector2f((rect1.x + rect1.width) / 2,(rect1.y + rect1.height) / 2);
Vector2f rect2Mid = new Vector2f((rect2.x + rect2.width) / 2,(rect2.y + rect2.height) / 2);
Vector2f rect1A = new Vector2f(rect1Origin.x + rect1.width, rect1.y);
Vector2f rect1B = new Vector2f(rect1Origin.x, rect1Origin.y+ rect1.height);
Vector2f rect1C = new Vector2f(rect1Origin.x + rect1.width,rect1Origin.y + rect1.height);
Vector2f rect2A = new Vector2f(rect2Origin.x + rect2.width, rect2.y);
Vector2f rect2B = new Vector2f(rect2Origin.x, rect2Origin.y
+ rect2.height);
Vector2f rect2C = new Vector2f(rect2Origin.x + rect2.width,
rect2Origin.y + rect2.height);
xAdd = rect2C.x - rect1B.x;
xAdd2 = rect1C.x - rect2B.x;
yAdd = rect2A.y - rect1B.y;
yAdd2 = rect2C.y - rect1A.y;
if (rect1Mid.y < rect2Mid.y) {
if (rect1.intersects(rect2)) {
y_pos += yAdd;
}
}
if (rect1Mid.y > rect2Mid.y) {
if (rect1.intersects(rect2)) {
System.out.println(yAdd2);
y_pos += yAdd2;
}
}
if(rect1Mid.x > rect2Mid.x){
if(rect1.intersects(rect2)){
hitRight = true; x_pos += xAdd;
}
}
if(rect1Mid.x< rect2Mid.x){
if(rect1.intersects(rect2)) {
x_pos += -xAdd2;
}
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激
谢谢
为您的角色保留两个位置 - 它所在的位置(截至最后一帧、移动等)以及您想要将其移动到的位置。然后仅在未检测到碰撞时才移动它 - 如果您不允许损坏状态,则不必修复它。
编辑:方法collision应该是boolean- 应该在实际移动角色之前完成,例如
if (!collision(character, tile))
{
doMove(character);
}
else
{
//custom handling if required
}
Run Code Online (Sandbox Code Playgroud)
Edit2:前面的方法仅适用于一小步,如果您需要部分移动,您确实需要知道角色的原始位置,例如move(originalPosition, desiredPosition, tile),您可以从originalPosition和推断出方向tile。
要点是,在获得有效的位置之前,您实际上并没有移动角色。
| 归档时间: |
|
| 查看次数: |
2523 次 |
| 最近记录: |