2011-03-29 109 views
2

任何人都知道为什么我的敌人碰撞不能正常工作?它似乎从侧面撞到它时会穿过他而不是弹开。碰撞检测问题

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

,如果你的位置和敌人y位置是一样的,你只向左或向右移动,然后第一个if块将是真实的,你会做

velo.y = -velo.y; 

但由于velo.y是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; 
    } 
} 
+0

这是一个真棒职位,但是当球在击中角度敌它搅乱了。我想我需要一些能够从任何角度反弹球的东西。尽管如此,这比我所拥有的要好,所以+1 – CyanPrime 2011-03-29 01:39:51

+0

定义“混乱” – corsiKa 2011-03-29 01:49:24

+0

卡住在敌人内部弹跳。 – CyanPrime 2011-03-29 02:00:20