2D tile based collision

Started by
9 comments, last by Inferiarum 11 years, 6 months ago
I have been seriously trying at this for just about a day now. Such as simple thing is creating big problems.

I am trying to implement 2D tile based collision. All have failed. Should I create a algorithm that calculates the velocity to apply to the position (the velocity calculated by the algorithm will insure that the non-static (moving) entity will not hit solid tiles) or create a algorithm that calculates the position of the entity after the velocity has been applied to it (resulting in directly changing the position to ensure that it will not collide with another tile). All in all this is a generic question, how can this be done properly? (A real example of what I want to do is terraria's character movement).

All replies are appriciated.
Thanks, Xanather.

Edit: One of the algorithms ive tried to implemented checks each velocity axis negativity/positivity and works along that. Edit 2: Entities have the same axis scale as the tiles (1, 1) would mean the player would be drawn at (16, 16) on the screen).

[source lang="csharp"] Vector2 result = position + velocity;
Vector2 nposition = new Vector2(position.X + velocity.X, position.Y);
Vector2 topleft = new Vector2(nposition.X - (width / 2), nposition.Y - (height / 2));
Vector2 topright = new Vector2(nposition.X + (width / 2), nposition.Y - (height / 2));
Vector2 bottomleft = new Vector2(nposition.X - (width / 2), nposition.Y + (height / 2));
Vector2 bottomright = new Vector2(nposition.X + (width / 2), nposition.Y + (height / 2));
if (velocity.X > 0)
{
for (int y = (int)topright.Y; y < (int)bottomright.Y + 1; y++)
{
if (engine.main.tiles[(int)topright.X, y].solid)
{
result.X = (int)topright.X - (width / 2);
break;
}
}
}
else if (velocity.X < 0)
{
for (int y = (int)topleft.Y; y < (int)bottomleft.Y + 1; y++)
{
if (engine.main.tiles[(int)topleft.X, y].solid)
{
result.X = (int)topleft.X + 1 + (width / 2);
break;
}
}
}
nposition = new Vector2(position.X, position.Y + velocity.Y);
topleft = new Vector2(nposition.X - (width / 2), nposition.Y - (height / 2));
topright = new Vector2(nposition.X + (width / 2), nposition.Y - (height / 2));
bottomleft = new Vector2(nposition.X - (width / 2), nposition.Y + (height / 2));
bottomright = new Vector2(nposition.X + (width / 2), nposition.Y + (height / 2));
if (velocity.Y > 0)
{
for (int x = (int)bottomleft.X; x < bottomright.X + 1; x++)
{
if (engine.main.tiles[x, (int)bottomleft.Y].solid)
{
result.Y = (int)bottomleft.Y - (height / 2);
}
}
}
else if (velocity.Y < 0)
{
for (int x = (int)topleft.X; x < topright.X + 1; x++)
{
if (engine.main.tiles[x, (int)topleft.Y].solid)
{
result.Y = (int)topleft.Y + 1 + (height / 2);
}
}
}
return result;[/source]
Advertisement
Ooh... I think you might be over thinking this a bit. C# comes with a Rectangle class, which comes with a built-in collision check method called Contains. If you use that, you can probably reduce your 54 lines of complicated looking code into about 5 lines of code. Ideally, this is what your code should look like in your update method:

pseudo code:

public void Update(GameTime gameTime)
{

position += velocity * gameTime.elapsedMS;

foreach(GameObject obj in AllMyCollidableGameObjectsList)
{
if(obj.rect.Contains(this.rect))
{
this.HandleCollision(); //varies by what your colliding with (bullets, terrain, items, etc)
}
}
}


The collision detection is overly simplistic here just for illustratation purposes. In your code, you'd want to handle the extra stuff, like object elasticity, overlap of bounding areas, pushback, changes in velocity, etc.
Yeah, that sounds about right, but I am working with a tile based world which is contained within a 2 dimensional array (unless I should create a bounding box for each tile, which i don't think is really necessary unless I either:
1. calculate the bounding boxes (rectangle) every update, or,
2. save the bounding box for each tile object and with many tiles (16000x4000) RAM usage will increase three times over (rectangle has 4 integers = 16 bytes).

What I really want is a collision algorithm that would indeed push back the player if it were to intersect with a solid x/y tile, and the velocity at which the object is traveling does not determine weather the collision check will be successful or not (say if the object was moving at 10000km/h it should not skip tiles in the collision check due to its speed).

I hope you understand what I'm saying :( Maybe I am just horrible at explaining things...

Anyway thanks for the reply,
Xanather.
I think I understand what you're asking.
The advantage of using a Rect is that it saves you CPU cycles and it simplifies your code. If you're not using a quad tree and just going with a dirty O(n^2) collision check, your going to have to spend extra cpu cycles calculating the bounding areas of each rectangle. You're right about the rect consuming more ram though.
Idea #1:
You could create your own rect class. Have two versions:
Version 1: It's just a wrapper for the build in Rect. If this becomes too ram heavy, switch to version 2:
Version 2: Assuming your rects are all squares of a fixed dimension, all it stores is the center X/Y coordinate. But, it has the same methods as the built in rect.

Idea #2: Collision detection with really fast objects.
The general idea is to draw a line from your moving objects current position to the next position its going to occupy. Then, do a line intersection test with all collidable objects. If there isn't anything colliding with the line, it's safe to move the object to the next position. If there is a collision, then you know the position on the line you're colliding at and you set your objects position to that point on the line. If your moving object is thicker than a pixel, then you have to find the edges and draw two lines to represent the thickness. Example: If your object is 5px wide and is falling straight down, then your first line starts at x, second at x + 5, and the end points are the velocity position with the same X offsets.
Yeah but I don't even know why I should use bounding boxes in the first place if I am just checking for collision against static (not moving) tiles. It would be much more efficient to check for the x/y tiles that are within the players bounds (using the method i first posted) and see if they are solid?

Your idea #2 looks like it could work though, thanks I will try and implement that. biggrin.png

Xanather.
Hi, Xanther. Algorithm is as follows: if a.x<=(b.x+b.w) and (a.x+a.w)>=b.x and a.y<=(b.y+b.h) and (a.y+a.h)>=b

My ASM programming site: http://sungod777.zxq.net/
I will look at that thanks :)
For tile based collision, what I do is I check the tiles close to my player, so I won't have to check my entire array all the time, while at the same time temporarily creating the rectangles to check for collision. so basically you could do something like this:


for(int x = Player.Position.X - collisionRange, x < Player.Position.X + collisionRange; x++)
{
for(int y = Player.Position.Y - collisionRange, y < Player.Position.Y + collisionRange; y++)
{
if(!world[x, y].IsCollidable)
continue;
if(Player.BoundingRectangle.Intersects(New Rectangle(x, y, TileSize, TileSize)
{
//Collision Logic goes here.
}
}
}


Note that doing it this way, you need to know the players position in your Grid space. This is easily calculated by dividing your worldspace position with the size of your tiles.
At least this is the approach I more or less use in my game.

Check out the game I am making here - http://www.youtube.com/user/NasarethMekuri

Hi Xanther,

I have a snippet of code that handles movement in a 2d platformer-type game that I've posted in other topics. It handles jumping, but it also handles collision in X direction, and moving the player out of the collision zone. It should work with almost any situation and map for falling off ledges, hitting head on platform above you, or moving against a wall, which slides up and down, you will wlak past once it's out of the collision zone. BTW, the numbers below are just guesses, make them what you want to make a good game.

// Speed player moves left or right
#define MOVEMENT_SPEED 10.0f
// initial velocity given to player when he jumps
#define JUMP_VELOCITY 20.0f
void Player::HandleInput()
{
if (LeftIsPressed()) {
this.xVelocity = -MOVEMENT_SPEED;
}
else if (RightIsPressed()) {
this.xVelocity = MOVEMENT_SPEED;
else {
this.xVelocity = 0.0f;
}
// Only jump if we're not already jumping or falling
if (JumpIsPressed() && this.OnGround) {
this.yVelocity = -JUMP_VELOCITY;
}
}
// defines amount to increase downward velocity every frame
#define GRAVITY_FORCE 4.0f
void Player::Update()
{
// Apply downward force to player
this.yVelocity += GRAVITY_FORCE;
// Move the Player
this.xLocation += this.xVelocity;
this.yLocation += this.yVelocity;
// Check we've collide with something above or below us
bool CollideBelow;
if (CheckCollisionY(CollideBelow)) {
// move us back to previous location and Stop Y Velocity
this.yLocation -= this.yVelocity;
this.yVelocity = 0.0f;
if (CollideBelow) {
this.OnGround = true;
}
}
else {
this.OnGround = false;
}
// Check if we've collided with anything on our left or right
if (CheckCollisionX()) {
// move us back to previous location and Stop X Velocity
this.xLocation -= this.xVelocity;
this.xVelocity = 0.0f;
}
}


Have fun and Good Luck!

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

This one is actually a very good resource that describe different approaches for this, you should take a look:
http://www.gamedev.net/page/resources/_/technical/game-programming/the-guide-to-implementing-2d-platformers-r2936
Game making is godlike

LinkedIn profile: http://ar.linkedin.com/pub/andres-ricardo-chamarra/2a/28a/272


This topic is closed to new replies.

Advertisement