下記のscriptでバイク走行をする画面を作成しましたが、一定時間過ぎると下記のように画面の左上に
行ってしまいます。原因がわかる方ご教授ください。
html
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>Document</title> 8</head> 9<body> 10 <script src="app.js"></script> 11</body> 12</html>
app.js
javascript
1let c = document.createElement("canvas"); 2let ctx = c.getContext("2d"); 3 4c.width = 1000; 5c.height = 400; 6 7document.body.appendChild(c); 8 9let perm = []; 10 11while (perm.length < 255) { 12 while (perm.includes(val = Math.floor(Math.random() * 255))); 13 perm.push(val); 14} 15 16let lerp = (a, b, t) => a + (b - a) * (1 - Math.cos(t * Math.PI)) / 2; 17 18let noise = x => { 19 x = x * 0.01 % 255; 20 return lerp(perm[Math.floor(x)], perm[Math.ceil(x)], x - Math.floor(x)); 21} 22 23let player = new function () { 24 this.x = c.width / 2; 25 this.y = 0; 26 this.ySpeed = 0; 27 this.rot = 0; 28 29 this.img = new Image(); 30 this.img.src = 'moto.png'; 31 32 this.draw = function () { 33 let p1 = c.height - noise(t + this.x) * 0.25; 34 35 36 if (p1 - 30 > this.y) { 37 this.ySpeed += 0.1; 38 } else { 39 this.ySpeed -= this.y - (p1 - 30); 40 this.y = p1 - 30; 41 } 42 this.y += this.ySpeed; 43 44 ctx.save(); 45 ctx.translate(this.x, this.y) 46 ctx.drawImage(this.img, 0, 0, 30, 30); 47 48 ctx.restore(); 49 50 } 51} 52 53let t = 0; 54function loop() { 55 56 t += 7; 57 ctx.fillStyle = "pink"; 58 ctx.fillRect(0, 0, c.width, c.height); 59 60 ctx.fillStyle = "black"; 61 62 ctx.beginPath(); 63 ctx.moveTo(0, c.height); 64 65 for (let i = 0; i < c.width; i++) { 66 ctx.lineTo(i, c.height - noise(t + i) * 0.25); 67 } 68 69 ctx.lineTo(c.width, c.height); 70 71 ctx.fill(); 72 73 player.draw(); 74 75 requestAnimationFrame(loop); 76} 77loop();
回答1件
あなたの回答
tips
プレビュー