Jump to content

  • Log In with Google      Sign In   
  • Create Account

Check if objects collide in 2d, without specifying which objects?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
16 replies to this topic

#1 timgranstrom   Members   -  Reputation: 556

Like
0Likes
Like

Posted 19 April 2013 - 03:43 AM

Hey, I'am currently developing a pong Game for learning experience.

 

I've got a fully working collision detection system going, but in my game update method I have to add which objects I'm checking if they collide..

 

I was wondering if I could make this more general, like that I check if any objects of the type Entity or Obstacle collide at any point.

example of possible collision:

entity - entity

entity - obstacle.

 

Currently I have to check if my:

player paddle collides with a wall above or a wall beneeth or with a ball.

ball collides with a wall above or a wall beneeth or with a paddle or ai.

ai collides with a wall above or a wall beneeth or with a ball.

 

I was thinking something along the lines of adding all entities and obstacles in an array, and then check everything at once for every update.

But would this be inneffective considering I shouldn't need to check if the ball collides with the ai while it's moving away from it, and vice versa with the player paddle.

 

any suggestions or tips would be appreciated.

 

Note: I'm currently using polymorphism in the collision detection. So it takes Entities and obstacles as parameters instead of for example: ball and wall etc..

 

code:

 

Main game project:

package engine;


import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.KeyListener;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

import engine.entities.Ai;
import engine.entities.Ball;
import engine.entities.Paddle;
import engine.walls.Wall;



public class PongGame extends BasicGameState implements KeyListener {
	private boolean gameStarted = false;
	private String start = "                Pong V2\nA self-educational game by Tim Granström\n\n\n       Press SPACE to start game.";
	private int width;
	private int height;
	private float ballX = 400.0f;
	private float ballY = 250.0f;
//---------------------------------------------------------------------
//          NEW STUFF
//---------------------------------------------------------------------
	private Paddle paddle;
	private Ai ai;
	private Ball ball;
	private Wall wallUp;
	private Wall wallDown;
	//private Wall wallRight;
	private CollisionDetection collision;
	boolean key_space = false;
	

	//Creates the objects for the game.
	public void init(GameContainer gc, StateBasedGame sbg)
			throws SlickException {
		gc.setTargetFrameRate(60);
		width = gc.getWidth();
		height = gc.getHeight();
		paddle = new Paddle(5,150,7,55,gc);
		ball = new Ball(ballX,ballY,15,15);
		ai = new Ai(width-10,400,7,55,gc);
		wallUp = new Wall(0,0, width, 8);
		wallDown = new Wall(0, height - 8, width, 8);
		//wallRight = new Wall(width - 8, 0, 8, height);
		collision = new CollisionDetection();

		
	}

	//Renders all the objects in the game
	public void render(GameContainer gc, StateBasedGame sbg, Graphics g)
			throws SlickException {
		
		g.setColor(Color.white);
		g.drawString(start, (width/2)-175, (height/2)-60);

		
//---------------------------------------------------------------------
//      NEW STUFF
//---------------------------------------------------------------------
		wallUp.render(g);
		wallDown.render(g);
		//wallRight.render(g);
		paddle.render(g);
		ball.render(g);
		ai.render(g);
	}
	
	
	//Check what key is pressed
	public void keyPressed(int key, char c) {
		
        if (key == Input.KEY_SPACE) {
            key_space = true;
        }
    }
	
	public void keyReleased(int key, char c){
		if (key == Input.KEY_SPACE) {
            key_space = false;
        }
	}

	

	public void update(GameContainer gc, StateBasedGame sbg, int delta)
			throws SlickException {
		
		if(!gameStarted){
		if (key_space == true) {
			ball.resetBall();
			start = "";
			gameStarted = true;
			
		}
		}
		if(gameStarted){
			
		//checks if the paddle collides with the upper and lower wall.
		paddle.checkCollisionDown(wallDown);
		paddle.checkCollisionUp(wallUp);
		paddle.update(delta);
		
		ai.checkCollisionDown(wallDown);
		ai.checkCollisionUp(wallUp);
		ai.update(ball, delta);
		
		// check if ball collide with paddle or AI
		if (collision.collidesWith(ball, paddle) || collision.collidesWith(ball, ai)) {
			ball.invGoingLeft();
		}
		
		// check if ball collide down
		if(collision.collidesWith(ball, wallDown)){
			ball.invGoingDown();
		}
		
		// check if ball collide up
		if(collision.collidesWith(ball, wallUp)){
			ball.invGoingDown();
		}
		
		ball.update(delta); //updates the ball coordinates etc. NOTE: important to update AFTER collision has been checked.
		
		
		// check if ball has passed the paddle. If true, resets the game.
		if(ball.getX()<0){
			ai.getPlayer().addScore();
			ball.resetBall();
			gameStarted = false;
		}
		if(ball.getX()>this.width){
			paddle.getPlayer().addScore();
			ball.resetBall();
			gameStarted = false;
		}
		}

	}

	@Override
	public int getID() {
		return 0;
	}

}

 

Collision detection class:

package engine;

import engine.entities.Entity;
import engine.walls.Obstacle;

public class CollisionDetection {
	
	
	//Check if two entities intersect.
	public boolean collidesWith(Entity b, Entity p){
		boolean collided = b.getRect().intersects(p.getRect());
		return collided;	
	}
	

		
		//Check if entity and obstacle intersect.
		public boolean collidesWith(Entity e, Obstacle w){
			return e.getRect().intersects(w.getRect());
		}

	
}

 

You can check the other classes in my journal, they are not all updated in the journal though.

JOURNAL

 

thanks,

Tim

 



Sponsor:

#2 CJ_COIMBRA   Crossbones+   -  Reputation: 837

Like
0Likes
Like

Posted 19 April 2013 - 04:54 AM

Have each of your Entity and Obstacle run their own Update method so they will keep track of their own collisions. Of course they would still need to know what's around and this is where your idea of having an array (or list) of things to collide with should be worked.



#3 timgranstrom   Members   -  Reputation: 556

Like
0Likes
Like

Posted 19 April 2013 - 08:40 AM

I've already got an Update method in each entity, that updates their current position. I don't have one in my obstacles (wall) since they are not supposed to move, hence no need to update the x and y coords.

 

But the problem is, I'am not sure HOW I should implement it etc..



#4 PsychotikRabbit   Members   -  Reputation: 171

Like
1Likes
Like

Posted 19 April 2013 - 01:38 PM

You can change your CollisionDetection class to an utility class, with static-only methods and therefore you could access it from anywhere.
As CJ_COIMBRA said, you could create a new collection of Entity object and store them in the CollisionDetection class.
 

public class CollisionDetection {
    private static ArrayList<Entity> entities = new ArrayList<Entity>();

    public static boolean collides(Entity e) {
        return collidesWith(e) != null;
    }

    public static Entity collidesWith(Entity e) {
        Entity obstacle = null;

        for(Entity entity: entities) {
            //If its not the same entity
            if(entity!= e) {
                if(e.getRect().intersects(entity.getRect()) {
                    obstacle = entity;
                }
            }
        }

        return obstacle;
    }

    //Add obstacle to detect
    public static void addEntity(Entity entity) {
        entities.add(entity);
    }

    //Remove obstacle to detect
    public static void removeEntity(Entity entity) {
        entities.remove(entity);
    }
}


You could consider your walls and other obstacles as Entity. With this utility class you can initialize the detection in your init method like this:
 

CollisionDetection.addEntity(ball);
CollisionDetection.addEntity(topWall);
etc...


Then in the entities that you need to manage collision (like the ball) in the update method, after updating the position of the ball you can detect collision with any other entities and handle it.

 

//Detect if the ball (this) collides with any other entities
boolean collision = CollisionDetection.collides(this);

//Detect with which entity the ball collides
//If its not colliding with anything it will return null.
//Its your job to ensure that it will not collide with more than one entity at the time
//by reacting on collision.
Entity obstacle = CollisionDetection.collidesWith(this);

 


 


Edited by PsychotikRabbit, 19 April 2013 - 01:43 PM.


#5 timgranstrom   Members   -  Reputation: 556

Like
0Likes
Like

Posted 19 April 2013 - 02:46 PM

You could consider your walls and other obstacles as Entity.

 

The problem with this is that the obstacle class i another abstract class that I made for objects that does not have "life" as in moving etc, they are static. such as Walls.

While the entity class is supposed to be for Entities such as "living things" that are moving, etc!

 

I'm not sure as to how I should handle this issue..

 

Other then that, it's kind of brilliant! It took me a while to figure out what the code meant(it's kinda "late" here and I've been up since 5AM). But it sounds really good and I'm definitely gonna try to implement this!

 

Thank you :)



#6 PsychotikRabbit   Members   -  Reputation: 171

Like
0Likes
Like

Posted 20 April 2013 - 07:47 AM

The problem with this is that the obstacle class i another abstract class that I made for objects that does not have "life" as in moving etc, they are static. such as Walls.

While the entity class is supposed to be for Entities such as "living things" that are moving, etc!



It's simple, you can use Entity as the base class. Entity is anything that has a position,a size and is renderable in the game.
Then for your "living things" you can create a MovingEntity class which extends from Entity.

Now with that, all your entities/obstacles descend from Entity.

 

Entity.java
---------------------------
public class Entity {
    int position x;
    int position y;
    int width;
    int height;
    
    //Here go your getters/setters and contructors
}


 

MovableEntity.java
---------------------------------------
public class MovableEntity extends Entity {
    int speed;

    //Here goes your setters/getters/constructors

    public void update() {
        //Detect collision and move
    }
}


Now your walls can now extends from Entity or directly be directly a Entity.
Your ball/paddle/ai can extends from MovableEntity or be directly a MovableEntity.


Edited by PsychotikRabbit, 20 April 2013 - 07:48 AM.


#7 timgranstrom   Members   -  Reputation: 556

Like
0Likes
Like

Posted 20 April 2013 - 07:59 PM

The problem with this is that the obstacle class i another abstract class that I made for objects that does not have "life" as in moving etc, they are static. such as Walls.

While the entity class is supposed to be for Entities such as "living things" that are moving, etc!



It's simple, you can use Entity as the base class. Entity is anything that has a position,a size and is renderable in the game.
Then for your "living things" you can create a MovingEntity class which extends from Entity.

Now with that, all your entities/obstacles descend from Entity.

 

Entity.java
---------------------------
public class Entity {
    int position x;
    int position y;
    int width;
    int height;
    
    //Here go your getters/setters and contructors
}


 

MovableEntity.java
---------------------------------------
public class MovableEntity extends Entity {
    int speed;

    //Here goes your setters/getters/constructors

    public void update() {
        //Detect collision and move
    }
}


Now your walls can now extends from Entity or directly be directly a Entity.
Your ball/paddle/ai can extends from MovableEntity or be directly a MovableEntity.

hmm thats brilliant!

 

I'm gonna try to implement this tomorrow or so! I'll post here if I bump into any issues!

Thank you :)



#8 timgranstrom   Members   -  Reputation: 556

Like
0Likes
Like

Posted 22 April 2013 - 03:02 AM

I'am having one issue with this..

 

I'm not sure how to make the entities respond correctly..

 

for example: when I check the ball, if it collides with a wall above it, then the balls Y-direction should change, and if it collides with the wall below it should also change Y-direction.

Now this I can do. but the problem is that it also has to check if it collides to the left or right and in that case it has to invert the X-direction!

 

Now thats a bigger problem.. because then returning "true" or "false" won't cut it in the collision method...



#9 PsychotikRabbit   Members   -  Reputation: 171

Like
0Likes
Like

Posted 22 April 2013 - 06:21 AM

Since this is a ball specific collision implementation, you could add in the ball's update method some code to manage it.

 

//ball update method
public void update() {
    //Check collision
    Entity obstacle = CollisionDetection.collidesWith(this);

    //If there is an obstacle
    if(obstacle != null) {
        if(obstacle.getX() < getX()) {
            //Bouce Right;
        } else {
            //Bounce Left;
        }
        
        if(obstacle.getY() < getY() {
            //Bounce Bottom
        } else {
            //Bounce Top
        }
    }
}

 


Of course you can adapt this code to your needs.



#10 timgranstrom   Members   -  Reputation: 556

Like
0Likes
Like

Posted 22 April 2013 - 10:07 AM

this won't work since it checks for everything and it just really freaks out haha..

 

I found a "solution" to this problem though, but I'm not sure it's a good one or not..

 

in the Entity Class, I made another variable.

protected String entityName; //The name of an entity

This works so that if you want to, you can give your entity object a name for various reasons.

 

then in the ball,paddle and ai class, I add their entity names in their constructors like this:

this.entityName = "Paddle";

and so on.

 

Then the collision detection in their update methods looks like this:

 

 

ball:

//If there is an obstacle
	    if(obstacle != null) {
	        if(obstacle.entityName == "Paddle") {
	           this.invGoingLeft();
	        }
	        
	        if(obstacle.entityName == "Wall") {
	          this.invGoingDown();
	        }
	    }

paddle and ai are identical in the collision detection:

 if(obstacle != null) {
		        if(obstacle.entityName == "Wall") {
		        	
		        if(obstacle.getY() < getY()){
		           this.collideDown = false;
		           this.collideUp = true;
		        } else {
		            this.collideDown = true;
		            this.collideUp = false;
		        }
		        }
		        if(obstacle.entityName != "Wall"){
		        	this.collideDown = false;
		            this.collideUp = false;
		        }
		    }

 

 

Is this a good way or would this be considered a bad way to check what it collides with?

 

I get that in more advanced games where there are more objects and factors etc this would probably be a bad way.

 

But what about in this game?


Edited by timgranstrom, 22 April 2013 - 10:09 AM.


#11 PsychotikRabbit   Members   -  Reputation: 171

Like
0Likes
Like

Posted 22 April 2013 - 10:53 AM

It's not a bad way, but you can improve it. Instead of adding an entityName, when you check collision you can verify the type of the obstacle instance:

 

//If there is an obstacle
if(obstacle != null) {
   if(obstacle instanceof Paddle) {
      this.invGoingLeft();
   }
	        
   if(obstacle instanceof Wall) {
      this.invGoingDown();
   }
}

 


Also in the second snippet of code your posted you have two if
 

if(obstacle.entityName == "Wall")

 

and
 

if(obstacle.entityName != "Wall") 

 


Consider using "else" instead of the second condition.
Also if you don't want to get lost in your code and follow standards go read about Indentation at  http://en.wikipedia.org/wiki/Indent_style .

Is this a good way or would this be considered a bad way to check what it collides with?
 
I get that in more advanced games where there are more objects and factors etc this would probably be a bad way.



It is a simple game, I think this collision detection is good for a pong game, though if you start making bigger projects, you might consider more advanced techniques which will fits your needs. As for now it's very good to start somewhere less complicated to get more experience.

#12 timgranstrom   Members   -  Reputation: 556

Like
0Likes
Like

Posted 22 April 2013 - 01:25 PM

It's not a bad way, but you can improve it. Instead of adding an entityName, when you check collision you can verify the type of the obstacle instance:

I see, it's just that I read somewhere that (and I semi-quote it) "If you need to use instanceof, it means your code is bad/needs improvement" and many agreed on what that person said. I dunno though how true it is and I don't remember if it was in game-development or general programing (as these are different in my opinion).

What do you think?

 

Consider using "else" instead of the second condition.

Yes I normaly use that, but for some reason the program didn't like it. It might have been a bug though, I'm gonna try again :)

 

Also if you don't want to get lost in your code and follow standards go read about Indentation at http://en.wikipedia.org/wiki/Indent_style .

I will do that, thanks! :)



#13 PsychotikRabbit   Members   -  Reputation: 171

Like
0Likes
Like

Posted 22 April 2013 - 01:40 PM

I see, it's just that I read somewhere that (and I semi-quote it) "If you need to use instanceof, it means your code is bad/needs improvement" and many agreed on what that person said. I dunno though how true it is and I don't remember if it was in game-development or general programing (as these are different in my opinion).

What do you think?



I don't think it's bad to use instanceof for this part of the code. Storing a string for the name would be perfect if it would be used as an unique Identifiant. Though,
all your paddles will be name "paddle" and all your walls will be named "wall". I think you must adjust your code with the functionnalities that you are looking for. Therefore, as you don't need 1000 different entities and you have to implement collision detection differently on each of your entity, it is a good way to do it.

#14 timgranstrom   Members   -  Reputation: 556

Like
0Likes
Like

Posted 22 April 2013 - 01:53 PM

I don't think it's bad to use instanceof for this part of the code. Storing a string for the name would be perfect if it would be used as an unique Identifiant. Though,
all your paddles will be name "paddle" and all your walls will be named "wall". I think you must adjust your code with the functionnalities that you are looking for. Therefore, as you don't need 1000 different entities and you have to implement collision detection differently on each of your entity, it is a good way to do it

 

I see, that seems reasonable!

 

Okay I've edited the collision so that it uses instanceof.

 

Though the collision is sometimes a bit buggy, for example: if the ball hits the top or bottom edge of the paddles it kinda goes into it and bounces inside until it gets out haha..

 

Not sure how to stop this though!



#15 jHaskell   Members   -  Reputation: 1109

Like
0Likes
Like

Posted 23 April 2013 - 03:17 PM

I find a cleaner solution to these sorts of problems is to give your Entity a reflection 'property' that you just multiply by the ball's velocity.  This property or properties sets a value that applies the appropriate reflection to the colliding ball.  There are only two values to consider, a value of 1 does not modify the velocity while a value of -1 reflects it.

 

So, some pseudo code (as I'm not a java programmer)

if(ObjA collides with Ball)
{
	Ball.xVelocity *= ObjA.xReflection;
	Ball.yVelocity *= ObjA.yReflection;
}

Set ObjAs x and y reflection to 1 and -1, and you get reflection appropriate for a horizontal wall (y velocity is reflected, but x velocity remains unchanged).

Set it to -1 and 1, and you get reflection appropriate to a vertical paddle.

 

The code doesn't really care what type of Object it is working with.  There aren't any additional conditions beyond the test for collision.  You aren't writing separate methods for each collision case.  If the objects have collided, apply the reflection to the balls velocity.



#16 Satharis   Members   -  Reputation: 1281

Like
0Likes
Like

Posted 23 April 2013 - 04:21 PM

Personally if I just want to do "simple" collision checking without regards to spatial comparisons, I just make a like "world" object and add all the entities to that, and have it manage it. A bonus to that method is you can just run a collisioncheck method on it and have it automatically check each object against each other(since the world would contain a list of them) and call something like HandleCollision(target) on each entity that's colliding.

 

This lets you do things like make walls change sprites if they're collided with, or nothing at all if you prefer. Of course the ball has a reference to whatever it collided with so it can compare itself to the object and figure out which velocity to reverse along with shifting it out of the other object's bounding box.



#17 jellyfishchris   Members   -  Reputation: 300

Like
0Likes
Like

Posted 23 April 2013 - 11:05 PM

The problem your coming into is your trying to merge collision detection (Maths), and collision resolution (game logic).
And you want this to be eligate, you might have to think your design a little bit and have a detection facility and this is then passed to the resolution section to handle how a ball hits a wall for example!

Hope this helps






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS