Java 2D collision detection

Hi, I learning java about 5 days, and today I wanted to make a game, I stuck on collision detection in my game. If someone can take a look on source code I will be appreciate. Already I made the collsion “system” but character just only slowing the move when it colliding and do not stop as I want. Colliding system is based on Rectangles and intersects.

Its a link for source code for my game http://www.mediafire.com/download.php?wlk8dh1a4v8axfm

Ps
I’m new on this forum and If you wrote something wrong in my post or put this post in wrong place just say and I will fix this. Thanks.

Posted your code on forum’s pastebin. It’s bothering to go to MF.

I havent seen your code, but had you reset the colliding object when it intersected? If not then the method keep returning true.

Afterall like I said, post your code on pastebin and post the link here for futher diagnose. Welcome to JGO :slight_smile:

Main game class Game.class
http://pastebin.java-gaming.org/7508a212028

Movement.class
http://pastebin.java-gaming.org/508a1302829

Map render map.class
http://pastebin.java-gaming.org/08a1048292b

For help big thanks.

Had tried to set the Movement.Speed to 0?

I do not know to to explain you this but if you can download the project and run him and you will see whats happening when character colliding with wall. I tried many ways to make this work, and finally I found this forum.
Yeah I tried setting up speed to 0 but this don’t work, character just passes through the wall slowly.
Please check the project if you can then you will see what happening. Thanks for any advice.

It looks like you are doing game logic inside you rendering loop…Never ever do that.

Have a game update or tick method that updates everything. Then have a render method that ONLY renders. g.drawStuff at x and y

Confusing game logic and rendering is a very bad idea.

I can help you out with the error part. It is at class Map on line 52. You are checking to see if the guy collides with “every” block in the entire map. He is going to move for each of those blocks little by little.

To fix, you might want to iterate through the block loop once and see if the guy is colliding with “1” red block. If he is, break out of the loop and stop his movement. You might want to position your movement code within the Map class, and if possible, get a separate update and render phase. It’ll make the process easier. Hope this helps.

@OP
Not everybody want to be bothered DLing project, open eclipse then import it. That’s why JGO has pastebin for long code so we can diagnose with mind and imagination.

Your 0 setting wont work because of this


if(!hero2.hero.intersects(blocks.get(i))){
                  Movement.isCollUp = false;
                  Movement.isCollDown = false;
                  Movement.isCollLeft = false;
                  Movement.isCollRight = false;         
            }

That IF, acts like “else” for

if(hero2.hero.intersects(blocks.get(i)))

. If the player doesn’t collide with last block on the ArrayList (no matter he collides with other block), all booleans will be false resulting movement not to be 0 anymore.

So where I can put this code which resuming the movement. Because I know what you mean but I don’t know where I can put this code to resume the movement. I don’t have any idea. For help big thanks.

Not really clear by “resuming the movement”. If by collision the move will be change then you only need to deal with one block collision at one time loop check (at least for debugging sake if it isn’t what you want).

Ok I tried to fix this. It is a code:

public void checkcoll(){
		if (MemoryCollision == null){
			System.out.println("LASD");
			if(blocks.size() != 0){
				for (int i=0; i<blocks.size();i++){
					if(hero2.hero.intersects(blocks.get(i))){
						
						MemoryCollision = blocks.get(i);
						
						if(Movement.up == true){
							Movement.Speed = 0;
							Movement.isCollUp = true;
							Movement.up = false;						
							break;
						}
						if(Movement.down == true){
							Movement.Speed = 0;
							Movement.down = false;
							Movement.isCollDown = true;
							break;
						}
						if(Movement.left == true){
							Movement.Speed = 0;
							Movement.left = false;
							Movement.isCollLeft = true;
							
						}
						if(Movement.right == true){
							Movement.Speed = 0;
							Movement.right = false;
							Movement.isCollRight = true;
							break;
						}
					}
				}
			}
		}
		
		if (MemoryCollision != null){
System.out.println("Parameters: " + MemoryCollision"); //This method showing only this the if statement don't working.
			if(!hero2.hero.intersects(MemoryCollision)){ //Here is problem, this method don't checking if character don not colliding with this 1 object.
				Movement.isCollUp = false;
				Movement.isCollDown = false;
				Movement.isCollLeft = false;
				Movement.isCollRight = false;
				MemoryCollision = null;
			}
		}
	}

So I made that when character collide with 1 of the objects, this 1 object parameters going to the memory and I stoping checking for collision. And then I only checking if character stop colliding with this object if yes then I resuming the movement that character can move if no I resuming checking that character not colliding with this object. Thanks for any help.

OK, I think I got this:

It looks to me like you are checking for collision with any block in the map (brute force method), but then you get out of the loop and check again if he is still colliding. Well if you don’t do anything of course he is still going to be colliding! :wink:

Simple (not the best, but easy to understand, which is key!) method of resolving the collsion:

Rectangle collision = hero.intersection(collisionBlock); //  Get the intersection itself
            
            if(hero.collUp) {              // If he was colliding upwards,
                hero.y -= collision.height;// move him back down
                
            } else if(hero.collDown) {     // If he was colliding downwards,
                hero.y += collision.height;// move him back up
                
            } else if(hero.collRight) {    // If he was colliding to the right,
                hero.x -= collision.width; // move him to the left
                
            } else if(hero.collLeft) {     // If he was colliding to the left,
                hero.x += collision.width; // move him to the right
            }

Put that in between the end of the collision check loop and the is-he-still-colliding check, and tell me how it goes! :slight_smile:

(Also I have more code if you need to see it to get the picture)

I know that this is not the actual question but you are doing your game loop wrong.

This is the part which you mentioned.


public void run(){
    while(Running){
        movechar();
        repaint();
        try{
            Thread.sleep(10);
        }catch(Exception ex){}
    }      
}

You are moving the character and repainting the panel. It’s fine and the error lies in your timing mechanism. Let’s see this in a timeline.

The time taken by the the functions will depend on the machine. So assume that at first you are running the game on a fast computer and the updating takes 10 milliseconds (Suppose). Then you sleep for another 10 millis and one loop takes 20 millis. So for one second, you would move 50 pixels if your position increments by 1 every loop.

If you are running on a slow computer, the time may take more and result in slowing down the game.

I recommend you reading the following articles on game-loops.

http://www.koonsolo.com/news/dewitters-gameloop/
http://www.java-gaming.org/index.php?topic=24220.0

I use the algorithm described in the top answer of this question. It’s very easy to implement, and works pretty well for most purposes. I don’t have a Java example, but I could post a javascript implementation from my last game if you’re interested.this question