Collision in Tiled Map - LibGDX
Posted
by
user43353
on Game Development
See other posts from Game Development
or by user43353
Published on 2014-04-18T23:10:04Z
Indexed on
2014/08/21
10:31 UTC
Read the original article
Hit count: 741
I have collision code that deals with left or right or top or bottom. I am using Tiled Map with LibGDX.
Question is: How do I detect collision with other cells by all 4 sides, and not specifically by left/right or top/bottom.
Here is my top/bottom and left/right collision code:
private boolean isCellBlocked(float x, float y) {
Cell cell = collisionLayer.getCell((int) (x / collisionLayer.getTileWidth()), (int) (y / collisionLayer.getTileHeight()));
return cell != null && cell.getTile() != null && cell.getTile().getProperties().containsKey(blockedKey);
}
public boolean collidesRight() {
for(float step = 0; step < getHeight(); step += collisionLayer.getTileHeight() / 2)
if(isCellBlocked(getX() + getWidth(), getY() + step))
return true;
return false;
}
public boolean collidesLeft() {
for(float step = 0; step < getHeight(); step += collisionLayer.getTileHeight() / 2)
if(isCellBlocked(getX(), getY() + step))
return true;
return false;
}
public boolean collidesTop() {
for(float step = 0; step < getWidth(); step += collisionLayer.getTileWidth() / 2)
if(isCellBlocked(getX() + step, getY() + getHeight()))
return true;
return false;
}
public boolean collidesBottom() {
for(float step = 0; step < getWidth(); step += collisionLayer.getTileWidth() / 2)
if(isCellBlocked(getX() + step, getY()))
return true;
return false;
}
What I'm trying to achieve is simple: I'm trying to make code that will detect by all 4 sides,
collidesRight + collidesLeft + collidesTop + collidesBottom in one boolean.
For some reason, I cant seem to figure it out. I tried to use Rectangles (the Java Class) on the specific tile I want to be detected, but was messy and I have multiple maps. Having a Rectangle (from Java's API) around the player is no problem.
It's just the tiles I want to be detected are the main issues as they cause messy code when used with the Rectangle class.
Im trying to minimize the amount of code....
© Game Development or respective owner