I am trying my hand at creating a simple game using libGDX.
The idea is: We have a hero who jumps and world consist of dynamically created moving platforms in an auto side-scrolling manner. In order to progress our hero need to jump on these platforms and avoid falling. I have figured out how to do this using the built-in libGDX collision detection mechanism.
Code is:
public boolean collides(Hero hero){
if (position.y < hero.getY() + hero.getHeight()) {
return Intersector.overlaps(hero.getBoundingRect(),boundingRect);
}
return false;
}
But, our hero need to die when hits side of a platform. Following code should do the trick but even though bounding rectangle of hero surely overlaps(see below image) the bounding rectangle of platform Intersector.overlaps
returns false no matter what.
My code for this task:
public boolean collidesSide(Hero hero){
float heroYH = hero.getY() + hero.getHeight();
float heroXW = hero.getX() + hero.getWidth();
if (heroYH > position.y && heroXW>position.x){ // Platforms position
Gdx.app.log("Platform","hero.bound:" + hero.getBoundingRect().toString() + " plat.bound:" +boundingRect.toString());
Gdx.app.log("Platform","Intersect: " + Intersector.overlaps(hero.getBoundingRect(),boundingRect));
if (Intersector.overlaps(hero.getBoundingRect(),boundingRect)){
Gdx.app.log("Platform","CollidesSide: True");
return true;
}
return false;
}
return false;
}
It seems that I have missed some logic or doing something wrong.
How should I handle this issue?
Also this is the output log
Platform: Intersect: false
Platform: hero.bound:20.0,64.65544,25.0,32.0 plat.bound:-3.0893557,96.0,19.0,5.0
Platform: Intersect: false
Platform: hero.bound:20.0,65.13417,25.0,32.0 plat.bound:-4.4350085,96.0,19.0,5.0
Platform: Intersect: false
Platform: hero.bound:20.0,65.74593,25.0,32.0 plat.bound:-5.779882,96.0,19.0,5.0
Platform: Intersect: false
Platform: hero.bound:20.0,66.43762,25.0,32.0 plat.bound:-7.042242,96.0,19.0,5.0
Platform: Intersect: false
Platform: hero.bound:20.0,67.29663,25.0,32.0 plat.bound:-8.372085,96.0,19.0,5.0
Platform: Intersect: false
UPDATE:
The Red and Cyan rectangles seen in images are rendered output of Bounding Rectangle(hit boxes) of each object, not actual sprite.
plat.bound.x
is negative, whereashero.bound.x
is 20. So yourboundingRect
which is supposed to be theplat.bound
is wrong. \$\endgroup\$boundingRect.set(position.x,position.y, width,height)
\$\endgroup\$