import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class Jumper implements KeyListener { double x, y, vx ,vy; private boolean onTheGround; public static final double GRAVITY = 20; public static final double FRICTION = 0.75; public Jumper() { x = y = vx = vy = 0; } public void setNotOnGround() { this.onTheGround = false; } public void tick(double dt) { if (this.onGround()) { vx *= FRICTION; } else { vy += GRAVITY * dt; } x += vx; y += vy; if (vy < 0) { this.onTheGround = false; } } private boolean onGround() { return this.onTheGround; } @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_LEFT) { vx = -3; } if(e.getKeyCode() == KeyEvent.VK_RIGHT) { vx = 3; } if(e.getKeyCode() == KeyEvent.VK_UP && this.onGround()) { vy = -10; } } @Override public void keyReleased(KeyEvent e) {} @Override public void keyTyped(KeyEvent e) {} public Rectangle bounds() { return new Rectangle((int)(x-10), (int)(y-30), 20, 60); } public void draw(Graphics2D g) { g.setColor(Color.DARK_GRAY); g.fillOval((int)(x-10), (int)(y-30), 20, 60); } public void bumpInto(Rectangle r) { if(this.bounds().intersects(r)) { Rectangle overlap = this.bounds().intersection(r); if (overlap.width < overlap.height) { this.vx = 0; if(this.x > r.getCenterX()) { this.x = 10 + r.getMaxX(); } else { this.x = r.getMinX() - 10; } } else { this.vy = 0; if(this.y > r.getCenterY()) { // TODO: break blocks this.y = r.getMaxY() + 30; } else { // hit the top this.onTheGround = true; this.y = (int)r.getMinY() - 29; } } } } }