Sign in to follow this  
MatejaS

Another collision question

Recommended Posts

Hello,

I tried to make a top-down collision system, but it (again) didn't work... :(

The problem is, when I'm colliding from the left / right and then press up / down, it will correct the Y position, and the player would jump to the top or the bottom of the colliding rectangle.When I change the code to be X first, then the same problem happens for Y collisions.

Here's my code:

if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
	player.y--;
        dirY = 2;
} else if (dirY == 2) {
	dirY = -1;
}
if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
	player.y++;
        dirY = 3;
} else if (dirY == 3) {	
        dirY = -1;
}
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
	player.x--;
        dirX = 0;
} else if (dirX == 0) {
	dirX = -1;
}
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
	player.x++;
        dirX = 1;
} else if (dirX == 1) {
	dirX = -1;
}

if (player.overlaps(rect)) {
	switch (dirX) {
	case 0: // left
		player.x += ((rect.x + rect.width) - player.x);

	break;
	case 1: // right
		player.x -= (player.x + player.width - rect.x);
		break;
	}
}

if (player.overlaps(rect)) {
	switch (dirY) {
	case 2: // down
	        player.y += rect.y + rect.height - player.y;
		break;
	case 3: // up
		player.y -= player.y + player.height - rect.y;
		break;
	}
}

(I use Java and LibGDX, but the code should be understandable)

As you can see, collisions aren't my strongest skill.

If anyone could help me, I would greatly appreciate it.

MatejaS

 

Share this post


Link to post
Share on other sites

Doesn't matter, solved it using pre-processing. Here's my new code, hopefully it'll help someone :)

if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
			offY = -1.0f;
		}
		
		if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
			offY = 1.0f;
		}
		
		if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
			offX = -1.0f;
		}
		
		if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
			offX = 1.0f;
		}
		
		Rectangle np = new Rectangle(player.x, player.y + offY, 12, 11);
		
		if (np.overlaps(rect)) {
			if (offY > 0.0f) {
				offY -= np.y + player.height - rect.y;
			} else if (offY < 0.0f) {
				offY += rect.y + rect.height - np.y;
			}
		}
		
		np.setPosition(player.x + offX, player.y);
		
		if (np.overlaps(rect)) {
			if (offX > 0.0f) {
				offX -= np.x + player.width - rect.x;
			} else if (offX < 0.0f) {
				offX += rect.x + rect.width - np.x;
			}
		}
		
		player.x += offX;
		player.y += offY;

(You can optimize this by not creating new Rectangle every frame)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this