Hello,
I'm following this tutorial :
I am stuck near the 8:45 mark where the guy tests his left and right arrow keys on the moto.....because when the guy added the line "this.rvel += (k.ArrowLeft - k.ArrowRight) * 0.05" on the 8:20 mark, and I did the same, my code isn't working in the sense that when I press the right or left arrow keys, the moto doesn't rotate accordingly. And there aren't any errors. (see the commented line):
my code:
Can someone pls help? Thanks.
I'm following this tutorial :
I am stuck near the 8:45 mark where the guy tests his left and right arrow keys on the moto.....because when the guy added the line "this.rvel += (k.ArrowLeft - k.ArrowRight) * 0.05" on the 8:20 mark, and I did the same, my code isn't working in the sense that when I press the right or left arrow keys, the moto doesn't rotate accordingly. And there aren't any errors. (see the commented line):
my code:
Code:
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
c.width = 500;
c.height = 350;
document.body.appendChild(c);
var perm = [];
while(perm.length < 255){
while(perm.includes(val = Math.floor(Math.random() * 255)));
perm.push(val);
}
var lerp = (a, b, t) => a + (b-a) * (1 - Math.cos(t * Math.PI))/2;
var noise = x=>{
x = x * 0.01 % 255;
return lerp(perm[Math.floor(x)], perm[Math.ceil(x)], x - Math.floor(x));
}
var player = new function(){
this.x = c.width/2;
this.y = 0;
this.dy = 0;
this.rot = 0;
this.rvel = 0;
this.img = new Image();
this.img.src = "https://image.flaticon.com/icons/png/512/10/10027.png"
this.draw = function(){
var pl = c.height - noise(t + this.x) * 0.25;
var p2 = c.height - noise(t + 5 + this.x) * 0.25;
var grounded = 0;
if (pl - 15 > this.y){
this.dy += 0.1;
} else {
this.dy -= this.y - (pl - 15);
this.y = pl - 15;
grounded = 1;
}
var angle = Math.atan2((p2 - 15) - this.y, (this.x + 5) - this.x);
this.y += this.dy;
if (grounded){
this.rot -= (this.rot - angle) * 0.5;
this.rvel = this.rvel - (angle - this.rot);
}
// this.rvel += (k.ArrowLeft - k.ArrowRight) * 0.05; --> the line I'm referring to
this.rot -= this.rvel * 0.1;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.rot);
ctx.drawImage(this.img, -15, -15, 30, 30);
ctx.restore();
}
}
var t = 0;
var speed = 8;
var k = {ArrowUp: 0, ArrowDown: 0, ArrowLeft: 0, ArrowRight: 0};
function loop(){
t += speed;
ctx.fillStyle = "#19f";
ctx.fillRect(0, 0, c.width, c.height);
ctx.fillStyle = "black";
ctx.beginPath();
ctx.moveTo(0, c.height);
for (let i = 0; i < c.width; i++){
ctx.lineTo(i, c.height - noise(t + i) * 0.25);
}
ctx.lineTo(c.width, c.height);
ctx.fill();
player.draw();
requestAnimationFrame(loop);
}
onkeydown = d => k[d.key] = 1;
onkeyup = d => k[d.key] = 0;
loop();
Can someone pls help? Thanks.