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