Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public void update(float delta) {
- // apply gravity
- velocity.y -= gravity * delta;
- // clamp velocity
- if(velocity.y > speed)
- velocity.y = speed;
- else if(velocity.y < -speed)
- velocity.y = -speed;
- // save old position
- float oldX = getX(), oldY = getY();
- boolean collisionX = false, collisionY = false;
- // move on x
- setX(getX() + velocity.x * delta);
- // calculate the increment for step in #collidesLeft() and #collidesRight()
- increment = collisionLayer.getTileWidth();
- increment = getWidth() < increment ? getWidth() / 2 : increment / 2;
- if(velocity.x < 0) // going left
- collisionX = collidesLeft();
- else if(velocity.x > 0) // going right
- collisionX = collidesRight();
- // react to x collision
- if(collisionX) {
- setX(oldX);
- velocity.x = 0;
- }
- // move on y
- setY(getY() + velocity.y * delta * 5f);
- // calculate the increment for step in #collidesBottom() and #collidesTop()
- increment = collisionLayer.getTileHeight();
- increment = getHeight() < increment ? getHeight() / 2 : increment / 2;
- if(velocity.y < 0) // going down
- canJump = collisionY = collidesBottom();
- else if(velocity.y > 0) // going up
- collisionY = collidesTop();
- // react to y collision
- if(collisionY) {
- setY(oldY);
- velocity.y = 0;
- }
- // update animation
- animationTime += delta;
- setRegion(velocity.x < 0 ? left.getKeyFrame(animationTime) : velocity.x > 0 ? right.getKeyFrame(animationTime) : still.getKeyFrame(animationTime));
- }
- private boolean isCellBlocked(float x, float y) {
- Cell cell = collisionLayer.getCell((int) (x / collisionLayer.getTileWidth()), (int) (y / collisionLayer.getTileHeight()));
- return cell != null && cell.getTile() != null && cell.getTile().getProperties().containsKey(blockedKey);
- }
- public boolean collidesRight() {
- for(float step = 0; step <= getHeight(); step += increment)
- if(isCellBlocked(getX() + getWidth(), getY() + step))
- return true;
- return false;
- }
- public boolean collidesLeft() {
- for(float step = 0; step <= getHeight(); step += increment)
- if(isCellBlocked(getX(), getY() + step))
- return true;
- return false;
- }
- public boolean collidesTop() {
- for(float step = 0; step <= getWidth(); step += increment)
- if(isCellBlocked(getX() + step, getY() + getHeight()))
- return true;
- return false;
- }
- public boolean collidesBottom() {
- for(float step = 0; step <= getWidth(); step += increment)
- if(isCellBlocked(getX() + step, getY()))
- return true;
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement