简体   繁体   中英

Collision in 2D game

I'm trying to make a little game, where you have a little cube you can control with the arrows. When the cube intersects with another block object, I want it to go back and stop by the edge of the block object. So basically I want my block to stop when it intersects the block object, instead, it moves a bit in to it, and then when I move it again it jumps back. How can I make it so first checks if it will intersect, and if it will not move into it?

My drawing class extends JPanel and I'm painting with paintComponent .

 if(keyCode == e.VK_RIGHT) {
        if(xRightCollision()){
            hero.x -= xVel;
        }
        else {
            hero.x += xVel;
        }
    }

So let's say the cube is at the edge of the block object, but it's not intersecting it yet, so I press right and it moves into it, I press right again and it jumps back 5 pixels(xVel = 5).

public boolean xRightCollision(){
    for(int i = 0; i < obstacles.size(); i++) {
        if (hero.intersects(obstacles.get(i))) {
            return true;
        }
    }
    return false;
}

I've actually tried a similar thing with paint() on the JFrame , and since you have to call repaint() there, I could check first and then repaint. I don't really understand how paintComponent works since you can't control when it should be repainted.

Just use a temporary value to check, if the cube intersects with an obstacle, and reset to the original position, if necessary:

if(keyCode == e.VK_RIGHT) {
    //backup of the cubes position
    int tmp = hero.x;

    //move the hero to the right
    hero.x += xVel;

    if(xRightCollision())
        //cube intersects with an obstacle -> restore original position
        hero.x = tmp;
}

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