简体   繁体   中英

Collision Detection between player and tiles almost works

I have been stuck on making some collision detection in my game (its kind of like Terraria ) for a while but i made this code and... well, it kind of works. It works if the collision is above or on the left of the player, but if the collision is on the right, or below, instead of bouncing back, the player accelerates through the blocks until there is empty space. Here is the code that i made:

private void checkCollision() {
    for(int x = (int) (xpos-1); x <= xpos+1; x++){
        if(x < 0 || x > main.mw-1) continue;

        for(int y = (int) (ypos-2); y <= ypos+1; y++){
            if(y < 0 || y > main.mh-1) continue;

            if(main.map[x][y] == null) continue;
            if(!main.map[x][y].solid) continue;
            if(main.map[x][y].blocktype == -1) continue;

            double distance = Math.sqrt((xpos-x)*(xpos-x) + (ypos-y)*(ypos-y));

            if(distance > 1.0){
                continue;
            }else{

                double x_overlap = Math.max(0, Math.min(xpos + 16, x + 16) - Math.max(xpos, x));
                double y_overlap = Math.max(0, Math.min(ypos + 32, y + 16) - Math.max(ypos, y));
                double overlapArea = x_overlap * y_overlap;

                if(overlapArea > 0){

                    if(x_overlap > y_overlap){
                        yblock += y_overlap/2;
                    }
                    if(x_overlap < y_overlap){
                        xblock += x_overlap/2;
                    }

                    //guessing i need to do something here to make player 
                      go other way if block is on other side
                }
            }
        }
    }
}

So how would i make the player bounce back if the block that he is colliding with is on the right or below. Also is there any way i can make this smoother - right now the player be bouncing all over the place. Thanks! :)

What you want to do is keep track of the player's location, and if the location after moving is out of bounds you can reset the player's position to be right on the edge of the limit.

That's how I dealt with collision detection, I answered another question similar to this one though some folk decided to downvote the answer, go figure.

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