I have asked questions for this project before, but the jumping physics are a bit messed up. I cannot jump unless I hold down the W key, and then it just teleports me upwards. Does anybody know how to fix this glitch? Here's the code:
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
var x = 1
var y = 0
var xPos = 0
var yPos = 0
function updateVariables() {
x = x * 0.9
y = y * -0.9
y = y + 0.5
xPos += x
yPos += y
}
function clear() {
ctx.clearRect(0,0,600,600)
}
function Draw() {
collisionCheck();
clear();
ctx.fillRect(xPos,yPos,10,10)
ctx.fillRect(0,canvas.offsetHeight * 0.7,600,200)
window.requestAnimationFrame(Draw)
}
function collisionCheck() {
if (yPos > canvas.offsetHeight * 0.7 - 10) {
yPos = canvas.offsetHeight * 0.7 - 10
}
}
function right() {
x = 2
}
function left() {
x = -2
}
function jump() {
y =+ 20
}
function detectKeys() {
document.onkeypress = function (e) {
e = e || window.event;
console.log(e.key)
if (e.key == "d") {
right()
}
if (e.key == "a") {
left()
}
if (e.key == "w") {
jump()
}
}
}
window.requestAnimationFrame(Draw)
setInterval(updateVariables, 1)
setInterval(detectKeys, 1)
<canvas id="canvas" width="500" height="140"></canvas>