107 lines
2.2 KiB
Java
107 lines
2.2 KiB
Java
package de.samdev.colorrunner.game.world.entities;
|
|
|
|
import com.badlogic.gdx.math.Vector2;
|
|
|
|
import de.samdev.colorrunner.game.world.CRGameWorld;
|
|
|
|
public abstract class MovingEntity extends CRGameEntity {
|
|
protected Vector2 velocity = new Vector2();
|
|
|
|
protected boolean isOnFloor = false;
|
|
|
|
public MovingEntity(CRGameWorld _owner, float width, float height) {
|
|
this(_owner, 0, 0, width, height);
|
|
}
|
|
|
|
public MovingEntity(CRGameWorld _owner, float x, float y, float width, float height) {
|
|
super(_owner, x, y, width, height);
|
|
}
|
|
|
|
protected boolean moveByX(float bx) {
|
|
if (bx == 0) return false;
|
|
|
|
boolean collided = false;
|
|
|
|
bounds.x += bx;
|
|
|
|
for (CRGameEntity ent : world.entities) {
|
|
if (ent == this) continue;
|
|
|
|
if (ent.bounds.overlaps(bounds)) {
|
|
if (bx < 0) { // LEFT
|
|
float correction = (ent.bounds.x + ent.bounds.width) - bounds.x;
|
|
|
|
bounds.x += correction;
|
|
bx += correction;
|
|
|
|
collided = true;
|
|
} else { // RIGHT
|
|
float correction = ent.bounds.x - (bounds.x + bounds.width);
|
|
|
|
bounds.x += correction;
|
|
bx += correction;
|
|
}
|
|
}
|
|
}
|
|
|
|
return collided;
|
|
}
|
|
|
|
protected boolean moveByY(float by) {
|
|
if (by == 0) return false;
|
|
|
|
boolean collided = false;
|
|
|
|
bounds.y += by;
|
|
|
|
for (CRGameEntity ent : world.entities) {
|
|
if (ent == this) continue;
|
|
|
|
if (ent.bounds.overlaps(bounds)) {
|
|
if (by < 0) { // DOWN
|
|
float correction = (ent.bounds.y + ent.bounds.height) - bounds.y;
|
|
|
|
bounds.y += correction;
|
|
by += correction;
|
|
|
|
collided = true;
|
|
} else { // UP
|
|
float correction = ent.bounds.y - (bounds.y + bounds.height);
|
|
|
|
bounds.y += correction;
|
|
by += correction;
|
|
}
|
|
}
|
|
}
|
|
|
|
return collided;
|
|
}
|
|
|
|
private void updateOnFloor() {
|
|
for (CRGameEntity ent : world.entities) {
|
|
if (ent == this) continue;
|
|
|
|
if (Math.abs((ent.bounds.y + ent.bounds.height) - bounds.y) < 0.00004f && ent.bounds.x < (bounds.x + bounds.width) && (ent.bounds.x + ent.bounds.width) > bounds.x) {
|
|
isOnFloor = true;
|
|
return;
|
|
}
|
|
}
|
|
|
|
isOnFloor = false;
|
|
}
|
|
|
|
@Override
|
|
public void update(float delta) {
|
|
if (velocity.x != 0) {
|
|
moveByX(velocity.x * delta);
|
|
}
|
|
|
|
if (velocity.y != 0) {
|
|
moveByY(velocity.y * delta);
|
|
}
|
|
|
|
updateOnFloor();
|
|
}
|
|
|
|
}
|