2011-03-29 4 views
2

Quelqu'un sait pourquoi cette collision pour mon ennemi ne fonctionne pas correctement? Il semble que lorsqu'il est frappé de côté, il passe à travers lui au lieu de rebondir.question de détection de collision

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--; 
     } 

Répondre

0

si votre position et les positions y ennemi sont les mêmes, et vous ne mouvement vers la gauche ou la droite, le premier si le bloc sera vrai, et vous feront

velo.y = -velo.y; 

mais depuis velo.y est 0, vous ne le remarquerez pas.

3

Vous utilisez les positions pour déterminer si vous venez du haut ou non.

considèrent le tableau suivant:

\ | / 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 
/ | \ 

Je voudrais utiliser quelque chose comme ceci:

// 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

C'était un poste génial, mais il salit quand la balle frappe l'ennemi à un angle. Je pense que j'ai besoin de quelque chose qui fera rebondir la balle de n'importe quel angle. Pourtant, c'est mieux que ce que j'avais, donc +1 – CyanPrime

+0

Définir "désordre" – corsiKa

+0

se bloque rebondissant à l'intérieur de l'ennemi. – CyanPrime