-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch.js
138 lines (114 loc) · 2.71 KB
/
sketch.js
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
let player;
let obstacles = [];
let gameOver = false;
let gameStarted = false;
function setup() {
createCanvas(800, 600); // Increase the height
setupMenu();
}
function draw() {
if (gameStarted) {
if (gameOver) {
// Reset game state and show the menu
gameStarted = false;
gameOver = false;
setupMenu();
} else {
drawGame();
}
} else {
drawMenu();
}
}
function drawGame() {
background(220);
// Draw floor
fill(200);
rect(0, height - 10, width, 10);
if (!gameOver) {
player.show();
player.update();
if (frameCount % 60 === 0) {
obstacles.push(new Obstacle());
}
for (let i = obstacles.length - 1; i >= 0; i--) {
obstacles[i].show();
obstacles[i].update();
if (player.hits(obstacles[i])) {
gameOver = true;
}
if (obstacles[i].offscreen()) {
obstacles.splice(i, 1);
}
}
} else {
fill(255, 0, 0);
textSize(32);
textAlign(CENTER, CENTER);
text("Game Over!", width / 2, height / 2);
}
}
function startGame() {
gameStarted = true;
player = new Player();
}
class Player {
constructor() {
this.width = 20;
this.height = 20;
this.x = width / 4;
this.y = height - this.height - 10; // Adjust the initial y position
this.gravity = 0.5;
this.lift = -10;
this.velocity = 0;
}
show() {
fill(0, 0, 255);
rect(this.x, this.y, this.width, this.height);
}
update() {
this.velocity += this.gravity;
this.y += this.velocity;
// Ensure the player stays above the floor
if (this.y > height - this.height - 10) {
this.y = height - this.height - 10;
this.velocity = 0;
}
if (keyIsDown(32)) {
this.jump();
}
}
jump() {
if (this.y === height - this.height - 10) {
this.velocity += this.lift;
}
}
// Updated collision detection
hits(obstacle) {
return (
this.x < obstacle.x + obstacle.width &&
this.x + this.width > obstacle.x &&
this.y < obstacle.y + obstacle.height &&
this.y + this.height > obstacle.y
);
}
}
class Obstacle {
constructor() {
this.width = 20;
this.height = random(20, 60); // Adjust the maximum height
this.x = width;
this.y = height - this.height;
this.speed = 5;
}
show() {
fill(255, 0, 0);
rect(this.x, this.y, this.width, this.height);
}
update() {
this.x -= this.speed;
}
offscreen() {
return this.x < 0;
}
}