How would I add basic collision to my game? (2D Topdown)

Started by silk, April 17, 2016, 02:45:11

Previous topic - Next topic

silk

I have no problem detecting collision, but I want players to not be able to go through boxes and that isn't working, I've tried to do it a few different ways and it didn't work, this code for example:

        if ((x > 180)&&(x < 260)&&
        (y > 100)&&(y < 132)){
         xspeed =0;
         yspeed =0;
        }

it didn't work, the player still goes through the box, he just goes through it very slowly. Is there anything I can do? Sorry if this is a stupid question.

SilverTiger

When detecting a collision you should set your players position to be outside of the box.
Something like this pseudocode:

if (player.collidedWith(box.getLeftBorder())) {
    player.setX(box.getX() - player.getWidth());
}

if (player.collidedWith(box.getRightBorder())) {
    player.setX(box.getX() + box.getWidth());
}

if (player.collidedWith(box.getTopBorder())) {
    player.setY(box.getY() + box.getHeight());       // use this with bottom-left origin
    //player.setY(box.getY() - player.getHeight());  // use this with top-left origin
}

if (player.collidedWith(box.getBottomBorder())) {
    player.setY(box.getY() - player.getHeight());    // use this with bottom-left origin
    //player.setY(box.getY() + box.getHeight());     // use this with top-left origin
}

Cornix

Alternatively you could first check for any potential collision and only move your objects after no collision was detected.

silk

That makes sense, but how would I define the width and height of the box? I suppose I could hard code it, but how would I define them? Sorry if it's obvious, but I'm a little new to this, here's what the size of my box looks like:

glBegin(GL_QUADS);
		
		glColor3d(0.5, 0.5, 0.5);
		glVertex2d(180, 100);
		glVertex2d(260, 100);
		glVertex2d(260, 132);
		glVertex2d(180, 132);
		
		glEnd();

Cornix

You have to learn to program object oriented.
Write a class for your game objects. This class will hold important information like the size and position.
In a separate class you can manage all your game objects, have update cycles and collision detection / prevention.
Another class can hold your OpenGL loop and your rendering logic for showing game objects on screen.

Maybe this rough outline can help:
class GameObject {
	
	public int getX()
	
	public int getY()
	
	public int getWidth()
	
	public int getHeight()
	
	public boolean hasCollisionWith(GameObject obj)
	
}
class Game {
	
	public void addGameObject(GameObject obj)
	
	public void removeGameObject(GameObject obj)
	
	public void getAllGameObjects()
	
	public void updateAllGameObjects()
	
}
class OpenGLView {
	
	public void gameLoop()
	
	public void renderGameObject(GameObject obj)
	
}