As a beginner in the world of coding, I am currently working on creating a game. However, one major challenge I am facing is simulating gravity to make my character jump effectively. Despite trying various methods, I have encountered disappointing results. Below is a snippet of my code:
#canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
<body>
<canvas id='canvas' width='512px' height='300px'></canvas>
<script>
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let charX = 20;
let charY = 130;
let charSide = 20;
let velocity = 0;
let resistance = 0;
let rightPressed = false;
let leftPressed = false;
let upPressed = false;
let aPressed = false;
let dPressed = false;
function drawRect(x, y, width, height, color) {
ctx.beginPath();
ctx.rect(x, y, width, height);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
function drawGround(x, y, count) {
if (count === undefined) {
count = 1;
}
drawRect(x, y, 32 * count, canvas.height - y, '#684027');
drawRect(x, y, 32 * count, 10, 'green');
}
function draw() {
//Updates Game
ctx.clearRect(0, 0, canvas.width, canvas.height);
//Draws Character
drawRect(charX, charY, charSide, charSide, 'lime');
//Draws Ground
drawGround(0, 150, 16);
//Moves Character
if (charY = 130) {
speed = 0;
accelerate = 0;
}
if (rightPressed && charX < canvas.width - charSide) {
charX += 2;
} else if (leftPressed && charX > 0) {
charX -= 2;
} else if (upPressed && charY > 0 && charY < 131) {
velocity = 0;
velocity += 50;
resistance++;
velocity -= resistance;
charY -= velocity;
} else if (upPressed === false && charY > 129) {
resistance = 0;
velocity = 0;
}
}
//Character Movement Logic
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 37) {
leftPressed = true;
} else if (e.keyCode == 38) {
upPressed = true;
} else if (e.keyCode == 65) {
aPressed = true;
} else if (e.keyCode == 68) {
dPressed = true;
}
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
} else if (e.keyCode == 37) {
leftPressed = false;
} else if (e.keyCode == 38) {
upPressed = false;
} else if (e.keyCode == 65) {
aPressed = false;
} else if (e.keyCode == 68) {
dPressed = false;
}
}
//Animates Game
setInterval(draw, 10);
</script>
</body>
In an attempt to implement gravity for character jumping, I experimented with variables like velocity and resistance but unfortunately, it did not yield the desired outcome.