# input Direction confusion in snake game javascript

Go to solution Solved by polaryeti,

## Recommended Posts

Here's the full code:

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?

##### Share on other sites

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;
});```

##### Share on other sites

```let snakeArr = [
{
x: 13,
y: 15
}
]```

But in this code, we mean x and y are grid co-ordinates. How can we now tell in this question case that x and y represents a vector? I am not getting it. Please help.

##### Share on other sites

• Solution

My confusion is cleared.

arrSnake=[{x:0,y:1}]

inputDir={x:0,y:1}

are 2 different object names. It doesn't matter if we use same key name for both of them.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account. ×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.