Skip to content

Commit 4936165

Browse files
authored
Merge pull request #12 from Wincha/main
fix ball collision under paddle & fix game speed + added fps counter
2 parents 42971c5 + 1c65266 commit 4936165

File tree

1 file changed

+37
-5
lines changed

1 file changed

+37
-5
lines changed

02-arkanoid-game/index.html

+37-5
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@
4343
let dy = -3
4444

4545
/* VARIABLES DE LA PALETA */
46+
const PADDLE_SENSITIVITY = 8
47+
4648
const paddleHeight = 10;
4749
const paddleWidth = 50;
4850

@@ -86,8 +88,6 @@
8688
}
8789

8890

89-
const PADDLE_SENSITIVITY = 8
90-
9191
function drawBall() {
9292
ctx.beginPath() // iniciar el trazado
9393
ctx.arc(x, y, ballRadius, 0, Math.PI * 2)
@@ -133,6 +133,10 @@
133133
}
134134
}
135135

136+
function drawUI() {
137+
ctx.fillText(`FPS: ${framesPerSec}`, 5, 10)
138+
}
139+
136140
function collisionDetection() {
137141
for (let c = 0; c < brickColumnCount; c++) {
138142
for (let r = 0; r < brickRowCount; r++) {
@@ -180,7 +184,7 @@
180184
if (isBallSameXAsPaddle && isBallTouchingPaddle) {
181185
dy = -dy // cambiamos la dirección de la pelota
182186
} else if ( // la pelota toca el suelo
183-
y + dy > canvas.height - ballRadius
187+
y + dy > canvas.height - ballRadius || y + dy > paddleY + paddleHeight
184188
) {
185189
console.log('Game Over')
186190
document.location.reload()
@@ -226,20 +230,48 @@
226230
}
227231
}
228232

233+
// a que velocidad de fps queremos que renderice nuestro juego
234+
const fps = 60
235+
236+
let msPrev = window.performance.now()
237+
let msFPSPrev = window.performance.now() + 1000;
238+
const msPerFrame = 1000 / fps
239+
let frames = 0
240+
let framesPerSec = fps;
241+
229242
function draw() {
243+
window.requestAnimationFrame(draw)
244+
245+
const msNow = window.performance.now()
246+
const msPassed = msNow - msPrev
247+
248+
if (msPassed < msPerFrame) return
249+
250+
const excessTime = msPassed % msPerFrame
251+
msPrev = msNow - excessTime
252+
253+
frames++
254+
255+
if (msFPSPrev < msNow)
256+
{
257+
msFPSPrev = window.performance.now() + 1000
258+
framesPerSec = frames;
259+
frames = 0;
260+
}
261+
262+
// ... render code
230263
cleanCanvas()
231264
// hay que dibujar los elementos
232265
drawBall()
233266
drawPaddle()
234267
drawBricks()
235-
// drawScore()
268+
drawUI()
236269

237270
// colisiones y movimientos
238271
collisionDetection()
239272
ballMovement()
240273
paddleMovement()
241274

242-
window.requestAnimationFrame(draw)
243275
}
244276

245277
draw()

0 commit comments

Comments
 (0)