I am currently trying to work on a small project for my programming module and I am still very much a beginner since it's just the first semester. I want to make my character jump when I press the Up-arrow key but only to a certain height and then come back down, I can't figure out how to do this, for now when I press the arrow key, the character keeps going up if I keep holding it down and stops otherwise in mid-air. this is the link for my code in the online editor since I can't post all the code down here GP 3A. The part below is where I am having trouble.
if (isLeft == true)
{
gameChar_x -= 5
}
if (isRight == true)
{
gameChar_x += 5
}
if (isJumping == true)
{
gameChar_y -= 5
}
// if (gameChar_y == gameChar_y - 5)
// {
// gameChar_y += 5
// }
// if (isPlummeting == true)
// {
// gameChar_y += 10
// }
}
function keyPressed()
{
// if statements to control the animation of the character when
// keys are pressed.
//open up the console to see how these work
// console.log("keyPressed: " + key);
// console.log("keyPressed: " + keyCode);
if (keyCode == 37)
{
isLeft = true
}
else if (keyCode == 39)
{
isRight = true
}
else if (keyCode == 38)
{
isJumping = true
}
}
function keyReleased()
{
// if statements to control the animation of the character when
// keys are released.
// console.log("keyReleased: " + key);
// console.log("keyReleased: " + keyCode);
if (keyCode == 37)
{
isLeft = false
}
else if (keyCode == 39)
{
isRight = false
}
else if (keyCode == 38)
{
isJumping = false
}
}
var jumping = false;
var gravity = 1;
var rectangle = {
x: 20,
y: 0,
vx: 10, // X velocity
vy: 5, // Y velocity velocity = acceleration
size: 80
};
var ground = {
x: 0,
y: 600-rectangle.size,
width: 600
};
function setup() {
createCanvas(600, 600);
}
function draw () {
background('#000000');
// The Rectangle
fill('red');
rect(rectangle.x, rectangle.y, rectangle.size);
// Physics
rectangle.y += rectangle.vy; // contantly add y velocity
rectangle.vy += gravity; // constantly add gravity to Y
// Ground check
if (rectangle.y > ground.y - 0 && rectangle.x <= ground.width) {
rectangle.y = ground.y - 0;
rectangle.vy = 0;
jumping = false;
}
// Right
if (keyIsDown(RIGHT_ARROW)) {
rectangle.x += rectangle.vx;
}
// Left
if (keyIsDown(LEFT_ARROW)) {
rectangle.x -= rectangle.vx;
}
}
// THE JUMP
function keyPressed() {
if (jumping === false && keyCode === UP_ARROW) {
rectangle.vy -= 10;
jumping = true;
console.log(jumping);
}
}