1

I am trying to make me character moving left and up and I think jump() and slideLeft() functions are working properly and the problem is in the controller(e) function (else if (e.KeyCode===37)) . The first function is avaible but it isn't able to acces the second conditon function. Also, I would want to make the grid solid after I will make an slideRight() similar function ,so if my character is jumping on it, the platform would sustain the square . Has anyone any ideea for either of my questions ?

Code snippet:

var square = document.querySelector('.square');
var grid = document.querySelector('.grid');
var bottom = 0;
let isJumping = false;
let isGoingLeft = false;
var newBottom;
let left = 0;
let leftTimerId;


function jump() {
  if (isJumping) return
  let timerUpId = setInterval(function() {
    if (bottom > 250) {
      clearInterval(timerUpId);

      let timerDownId = setInterval(function() {
        if (bottom < 0) {
          clearInterval(timerDownId);
          isJumping = false;
        }
        bottom -= 5;
        square.style.bottom = bottom + 'px';
      }, 20)
    }
    isJumping = true;
    bottom += 30;
    square.style.bottom = bottom + 'px';
  }, 20)
}

function slideLeft() {
  console.log('da');
  isGoingLeft = true;
  leftTimerId = setInterval(function() {
    left -= 5;
    square.style.left = left + 'px';
  }, 20)
}

function controller(e) {
  if (e.keyCode === 32)
    jump();
  else if (e.KeyCode === 37)
    slideLeft();
}

document.addEventListener('keydown', controller);
.grid {
  position: absolute;
  background-color: chartreuse;
  height: 20px;
  width: 500px;
  bottom: 100px;
  left: 100px;
}

.square {
  position: absolute;
  background-color: darkblue;
  height: 100px;
  width: 100px;
  bottom: 0px;
  left: 150px;
}

`
<div class="grid"></div>
<div class="square"></div>
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
fast539
  • 27
  • 6

1 Answers1

1

EDIT: There is a typo: The second time you've written KeyCode

function controller(e) {
    if(e.keyCode===32) {
        jump();
    }
    else if(e.keyCode===37) {
        slideLeft();
    }
}

I don't really understand what you mean by the second part of your question. If you want a character to have the ability to jump on a square, you'll have to implement a collision detection. Something like this:

if ( isNotOnGround() ) { 
    fall() 
}
Sven
  • 66
  • 4
  • 4
    Nope, the brackets are optional when only a single statement is executed when the condition passes. – Teemu Feb 09 '22 at 14:18
  • Thank you for pointing out, I didn't know that.. However there's a typo in your code, see my edit. – Sven Feb 09 '22 at 14:24
  • Curly brace optional but then no semi-colon which terminates the statement Not having braces to me makes the code less readable https://stackoverflow.com/q/4797286/125981 – Mark Schultheiss Feb 09 '22 at 14:26