Jump to content

input Direction confusion in snake game javascript


Go to solution Solved by polaryeti,

Recommended Posts

 

 

Here's the full code:

https://codepen.io/pelko/pen/jOpBmPN

This is the code that I'm interested in:

window.addEventListener("keydown", e => {
  inputDir = { x: 0, y: 1 };
  moveSound.play();
  switch (e.key) {
    case "ArrowUp":
      inputDir.x = 0;
      inputDir.y = -1;
      break;
    case "ArrowDown":
      inputDir.x = 0;
      inputDir.y = 1;
      break;
    case "ArrowLeft":
      inputDir.x = -1;
      inputDir.y = 0;
      break;
    case "ArrowRight":
      inputDir.x = 1;
      inputDir.y = 0;
      break;


  }
})


What is inputDir variable? (I didn't write this code, I'm learning it from a tutorial, you know tutorials don't cover stuffs well).
What I'm not understanding is why are we setting inputDir at 0th row, 1st column? What does that mean? Can you provide some explanations with figures(if possible) about this issue?
 

inputDir holds the direction of movement in the x and y direction based on the key you pressed.

  • -1 = move left or move up
  • 0 = no movement in that direction
  • 1 = move right or move down.

In the rest of the code you would apply that movement with code like this:

  snakeArr.forEach((e,idx)=>{
    e.x+=inputDir.x;
    e.y+=inputDir.y;
  });

 

  • 2 months later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.