CyanPrime
CyanPrime

Reputation: 5193

collision detection question

Anyone know why this collision for my enemy doesn't work right? It seems when hit from the side it goes through him instead of bouncing off.

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

Upvotes: 2

Views: 310

Answers (2)

corsiKa
corsiKa

Reputation: 82579

You're using the positions to determine whether or not you are coming from the top or not.

consider the following chart:

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

I would use something like this:

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

Upvotes: 3

MeBigFatGuy
MeBigFatGuy

Reputation: 28568

if your position and the enemy y positions are the same, and you are only moving left or right, then the first if block will be true, and you will do

velo.y = -velo.y;

but since velo.y is 0, you won't notice it.

Upvotes: 0

Related Questions