Update paddle.update() to handle edge collision more nicely + cleaner code

Calculates an adjust variable which locates the paddle at exactly the
screen edge if a regular speed * dt move would put it past. Applies
the same adjust to stuck balls so they don't drift.
This commit is contained in:
Matt Low 2018-11-15 12:24:33 +04:00
parent e4000998cc
commit b44b48097c

View File

@ -5,6 +5,7 @@ import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
@ -48,29 +49,27 @@ public class Paddle extends Entity implements PhysicsBody {
@Override
public void update(float dt) {
float displacement = PADDLE_SPEED * dt;
float adjust = 0;
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
if (pos.x - width/2 - PADDLE_SPEED * dt < 0) {
setX(width/2);
return;
}
setX(pos.x - PADDLE_SPEED * dt);
for (Ball ball : state.balls) {
if (ball.isStuck()) {
ball.setX(ball.getX() - PADDLE_SPEED * dt);
}
if (pos.x - width / 2 - displacement < PlayState.EDGE_PADDING) {
adjust = -(pos.x - width/2 - PlayState.EDGE_PADDING);
} else {
adjust = -displacement;
}
}
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
if (pos.x + width/2 + PADDLE_SPEED * dt > PlayState.BOARD_WIDTH) {
setX(PlayState.BOARD_WIDTH - width/2);
return;
if (pos.x + width / 2 + displacement > PlayState.BOARD_WIDTH-PlayState.EDGE_PADDING) {
adjust = PlayState.BOARD_WIDTH - PlayState.EDGE_PADDING - width/2 - pos.x;
} else {
adjust = displacement;
}
setX(pos.x + PADDLE_SPEED * dt);
}
if (!MathUtils.isZero(adjust)) {
setX(pos.x + adjust);
for (Ball ball : state.balls) {
if (ball.isStuck()) {
ball.setX(ball.getX() + PADDLE_SPEED * dt);
ball.setX(ball.getX() + adjust);
}
}
}