|
43 | 43 | let dy = -3
|
44 | 44 |
|
45 | 45 | /* VARIABLES DE LA PALETA */
|
| 46 | + const PADDLE_SENSITIVITY = 8 |
| 47 | + |
46 | 48 | const paddleHeight = 10;
|
47 | 49 | const paddleWidth = 50;
|
48 | 50 |
|
|
86 | 88 | }
|
87 | 89 |
|
88 | 90 |
|
89 |
| - const PADDLE_SENSITIVITY = 8 |
90 |
| - |
91 | 91 | function drawBall() {
|
92 | 92 | ctx.beginPath() // iniciar el trazado
|
93 | 93 | ctx.arc(x, y, ballRadius, 0, Math.PI * 2)
|
|
133 | 133 | }
|
134 | 134 | }
|
135 | 135 |
|
| 136 | + function drawUI() { |
| 137 | + ctx.fillText(`FPS: ${framesPerSec}`, 5, 10) |
| 138 | + } |
| 139 | + |
136 | 140 | function collisionDetection() {
|
137 | 141 | for (let c = 0; c < brickColumnCount; c++) {
|
138 | 142 | for (let r = 0; r < brickRowCount; r++) {
|
|
180 | 184 | if (isBallSameXAsPaddle && isBallTouchingPaddle) {
|
181 | 185 | dy = -dy // cambiamos la dirección de la pelota
|
182 | 186 | } else if ( // la pelota toca el suelo
|
183 |
| - y + dy > canvas.height - ballRadius |
| 187 | + y + dy > canvas.height - ballRadius || y + dy > paddleY + paddleHeight |
184 | 188 | ) {
|
185 | 189 | console.log('Game Over')
|
186 | 190 | document.location.reload()
|
|
226 | 230 | }
|
227 | 231 | }
|
228 | 232 |
|
| 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 | + |
229 | 242 | 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 |
230 | 263 | cleanCanvas()
|
231 | 264 | // hay que dibujar los elementos
|
232 | 265 | drawBall()
|
233 | 266 | drawPaddle()
|
234 | 267 | drawBricks()
|
235 |
| - // drawScore() |
| 268 | + drawUI() |
236 | 269 |
|
237 | 270 | // colisiones y movimientos
|
238 | 271 | collisionDetection()
|
239 | 272 | ballMovement()
|
240 | 273 | paddleMovement()
|
241 | 274 |
|
242 |
| - window.requestAnimationFrame(draw) |
243 | 275 | }
|
244 | 276 |
|
245 | 277 | draw()
|
|
0 commit comments