Home > OS >  else if not working in KeyCode events javascript
else if not working in KeyCode events javascript

Time:02-11

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 ></div>
<div ></div>

CodePudding user response:

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() 
}
  • Related