任何人都知道为什么这对我的敌人的碰撞不起作用?似乎从侧面击中时它会通过他而不是反弹。
if(new Rectangle((int) position.x, (int) position.y, size, size).intersects(
new Rectangle((int) enemy.x, (int) enemy.y, enemy.width, enemy.height))){
if(position.y + size >= enemy.y && position.y + size <= enemy.y + (enemy.height/6))
velo.y = -velo.y;
else if(position.y <= enemy.y + enemy.height && position.y >=
enemy.y + enemy.height - (enemy.height/6))
velo.y = -velo.y;
else
velo.x = -velo.x;
enemy.hp--;
}
答案 0 :(得分:3)
您正在使用这些职位来确定您是否来自顶层。
考虑以下图表:
\ | / Assume enemy is at the center.
\ y | y / Assume each angle is 45°
\ | / Marked x or y is what you will reverse
x \ | / X
_____\|/_____ An important feature of this is that
/|\ the Y marked areas will have a slope
x / | \ X through the origin where
/ | \ abs(slope) > 1
/ y | y \ And the X will have the remainder
/ | \
我会用这样的东西:
// split these out just for code clarity hilarity
Rectangle me = new Rectangle((int) position.x, (int) position.y, size, size);
Rectangle them = new Rectangle((int) enemy.x, (int) enemy.y, enemy.width, enemy.height);
if(me.intersects(them)){
enemy.hp--;
// find the relative location
double relx = enemy.x - position.x;
double rely = enemy.y - position.y;
// find slope of line between the two of you
double slope = relx / rely;
// if abs(slope) > 1, you're in y territory, otherwise, x territory
if(Math.abs(slope) > 1.0) {
velo.y = -velo.y;
}
else {
velo.x = -velo.x;
}
}
答案 1 :(得分:0)
如果你的位置和敌人的y位置是相同的,而你只是向左或向右移动,那么第一个if块将是真的,你会做
velo.y = -velo.y;
但由于velo.y为0,你不会注意到它。