简体   繁体   中英

How can I solve this collision detection bug?

In this code i'm trying to make collision detection between the Enemy (that is constantly moving)and the Player. I set so that the Enemy will go in the oposite direction when hit. But when the two hit each other from different directions, there is a bug: the Enemy gets stuck in the Player until I move him. I know that instead of moving in the oppoite direction, I should change so it goes away from the Player, but I don't know how. Please help me!

public Enemy(float x, float y, ID id, Handler handler) {
    super(x, y, id);
    this.handler = handler;
    vely = -6;
    velx = -6;
}


protected void tick(LinkedList<Object> object) {
    x += velx;
    y += vely;
    if(x <= 0){
        if(velx < 0) velx = velx * -1;
    }
    if(y <= 0) {
        if(vely < 0) vely = vely * -1;
    }
    if(x >= 605){
        if(velx > 0) velx = velx * -1;
    }
    if(y >= 418) {
        if(vely > 0) vely = vely * -1;
    }

    collision();    
}

private void collision() {
    for(int i = 0; i < handler.object.size(); i++) {
        Object obj = handler.object.get(i);
        if(obj.getId()== id.Player) {
            if(getBound().intersects(obj.getBound())) {
                velx = velx * -1;
                vely = vely * -1;
            }
        }
    }
}


protected void render(Graphics g) {
    g.setColor(Color.BLACK);
    g.fillOval((int)x, (int)y, 30, 30);
}
public Rectangle getBound() {
    return new Rectangle((int)x, (int)y, 30, 30);
}

If the enemy is to the left of the player, set the enemy's velx to negative, otherwise positive. Similarly for vely if enemy is above the player.

// on collision...
velx = Math.abs(velx);
vely = Math.abs(vely);
if ( enemy_left_of_player() )
    velx = -velx;
if ( enemy_above_player() )
    vely = -vely;

Exact left/above logic will depend on size of player (is it also 30 pixels?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM