-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlatformer.java
More file actions
102 lines (87 loc) · 2.6 KB
/
Platformer.java
File metadata and controls
102 lines (87 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Platformer extends JPanel implements ActionListener, KeyListener {
private Timer timer;
private int playerX, playerY;
private int playerWidth, playerHeight;
private int velocityX, velocityY;
private boolean onGround;
private final int gravity = 1;
private final int moveSpeed = 5;
private final int jumpStrength = 15;
public Platformer() {
timer = new Timer(20, this);
timer.start();
playerX = 50;
playerY = 300;
playerWidth = 50;
playerHeight = 50;
velocityX = 0;
velocityY = 0;
onGround = true;
setFocusable(true);
addKeyListener(this);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.CYAN);
g.fillRect(0, 0, getWidth(), getHeight()); // Background
g.setColor(Color.GREEN);
g.fillRect(0, 350, getWidth(), 50); // Ground
g.setColor(Color.RED);
g.fillRect(playerX, playerY, playerWidth, playerHeight); // Player
}
@Override
public void actionPerformed(ActionEvent e) {
update();
repaint();
}
private void update() {
playerX += velocityX;
playerY += velocityY;
if (playerY + playerHeight >= 350) { // Ground collision
playerY = 350 - playerHeight;
velocityY = 0;
onGround = true;
} else {
velocityY += gravity;
onGround = false;
}
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
velocityX = -moveSpeed;
}
if (key == KeyEvent.VK_RIGHT) {
velocityX = moveSpeed;
}
if (key == KeyEvent.VK_SPACE && onGround) {
velocityY = -jumpStrength;
onGround = false;
}
}
@Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT) {
velocityX = 0;
}
}
@Override
public void keyTyped(KeyEvent e) {}
public static void main() {
JFrame frame = new JFrame("Simple Platformer");
Platformer game = new Platformer();
frame.add(game);
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}