Skip to main content
GameDev.net gamedev.net
🔒 Locked

Tile Collision Detection

Started by gamedevnoob Mar 12, 2013 at 1:49 AM 2 replies 2.5k views
Original Post
gamedevnoob
gamedevnoob

Hello everyone, I am a noob game developer trying to make a tile based platformer game. I want to know which method is best for collision detection? Is the four corner method the best?What if the size of my sprite is greater then the tile size? And any examples available for it? I am not a native english speaker so it's a bit difficult to understand.

wfrye2005
wfrye2005

What programming language? If it's C#/XNA, this example project might help. I harvested a few of it's rectangle-related helper methods for my own collision system (particularly, getIntersectionDepth() was useful).

Otherwise, the basic logic I've been using is as follows:

1. Find what index in the tile array the sprite is currently in.

2. Based on it's size and velocity (speed+direction), determine the range of tiles to check.

3. Create a new rectangle identical to the sprite's collision rectangle (which should be smaller than its actual frame for gameplay reasons), and move it according to the sprites velocity--but only in the X direction (ignore Y velocity for now).

4. Check all tiles in range for non-zero intersection depth; if found, move the rectangle by that amount.

5. X check is done; sprite should now be in correct X position.

6. Repeat 3 and 4 using the adjusted X position and the Y velocity.

7. Your new rectangle should now be in the correct X and Y position; set your sprite's position accordingly.

Can't say it's the best way, but it worked for me. Arbitrarily changing the sprite's size doesn't even break it. Doesn't handle slopes or platforms yet, though.

gamedevnoob
gamedevnoob

I am using Actionscript 3. I haven't started coding the collision detection using the rectangles, currently I am doing it with the four corners but I can't get it to work, here's how I am working

Tile size : 32x32

Hero size : 28x30

// directionX = 1 RIGHT
// directionX = -1 LEFT

left X= (hero.x+dX)/ tile size

right X= (hero.x+hero.width+dX-1)/ tile size

top Y = (hero.y+dY) / tile size

bottom Y = (hero.y+hero.height+dY-1) / tile size

//THE RIGHT CASE ONLY

topRight = isWalkable(rightX,topY)

downRight = isWalkable(rightX,bottomY)

// IF BOTH ARE TRUE THEN YOU ARE FREE TO MOVE BUT I AM GOING OPPOSITE, IF ANY OF THEM IS FALSE MEANING I CANT MOVE

if( !(topRight && downRight))

{

// STOP THE X VELOCITY

dX = 0;

}

hero.x +=dX;

/************************************************/

the problem i am facing is that when i am almost about to hit the left tile, the hero stops 2 to 3 pixels back.
I think its because the X velocity is greater then 1, so is there any way to fix this? Same is the case with Vertical movement

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.