I am having a little trouble here, I can easily fix it but the code is messy and horrible.
Basically I need to invert the X or Y velocity if I touch the edge of the screen, I can do this by doing:
if (ball.getX() + ball.getWidth() > Engine.graphics.getBox2DCam().viewportWidth) {
ball.velocity.set(-3, ball.velocity.y);
}
if (ball.getX() < 0) {
ball.velocity.set(3, ball.velocity.y);
}
if (ball.getY() < 0) {
ball.velocity.set(ball.velocity.x, 3);
}
if (ball.getY() + ball.getHeight() > Engine.graphics.getBox2DCam().viewportHeight) {
ball.velocity.set(ball.velocity.x, -3);
}
This however frustrates the crap out of me, I don’t want to manipulate the ball in the collision code, I simply want to check for collisions then report back to the entities that “hey, you just collided, do something”.
I want something like this, the problem being that because I am checking for collisions when they happen, the ball collides and remains colliding; resulting in a constantly flip of the velcocity:
if (ball.getX() > Engine.graphics.getBox2DCam().viewportWidth
|| ball.getX() < 0) {
event = Event.BOUNDARY_VIOLATION;
event.setProjection(CollisionProjection.X);
notify(ball, event);
}
if (ball.getY() < 0
|| ball.getY() > Engine.graphics.getBox2DCam().viewportHeight) {
event = Event.BOUNDARY_VIOLATION;
event.setProjection(CollisionProjection.Y);
notify(ball, event);
}
This basically checks what axis we are colliding on and sends an notification to the Ball itself to let it know it just hit something, then in the ball code:
@Override
public void onNotify(Entity entity, Event event) {
switch (event) {
case BOUNDARY_VIOLATION:
if(event.getProjection() == CollisionProjection.X){
velocity.set(-velocity.x, velocity.y);
}else if(event.getProjection() == CollisionProjection.Y){
velocity.set(velocity.x, -velocity.y);
}
break;
default:
break;
}
}
As you can see this is just going to constantly flip the velocity vector because I check for collision as they happen, is there a simple algorithm I can implement to check for collisions just before they happen? No idea what to google, came up results that mostly just check for collisions when they overlap.