Javascript +/+= Operator - javascript

I am having trouble with a basic movement engine I have made, where the Up key triggers a function making a small div go up, and the Down key doing the opposite. I am fairly sure it's to do with the += in the Down() function, and I have tested it with -=, which works fine, just I can't work out what might be clashing with the function.
At the bottom, I have put a comment to indicate where my problem is.
var interval = '';
var key = false;
var interval1 = '';
var key1 = false;
$(document).keydown(function(e) {
if(e.which === 38) {
if(key === false){
interval = setInterval(function(){Up()},20)
key = true;
}
}
if(e.which === 40) {
if(key1 === false){
interval1 = setInterval(function(){Down()},20)
key1 = true;
}
}
});
$(document).keyup(function(e) {
if(e.which === 38) {
clearInterval(interval)
key = false;
}
if(e.which === 40) {
clearInterval(interval1)
key1 = false;
}
});
document.getElementById('Jumper').style.top = '46%';
var Top = parseInt(document.getElementById('Jumper').style.top);
var Topp = parseInt(document.getElementById('Jumper').style.top);
function Up(){
if(Top > 0){
Top = parseInt(document.getElementById('Jumper').style.top);
Top -= 0.2;
document.getElementById('Jumper').style.top = Top+'%';
}
}
function Down(){
if(Topp > 0){
Topp = parseInt(document.getElementById('Jumper').style.top);
Topp += 0.2; //<--PROBLEM
document.getElementById('Jumper').style.top = Topp+'%';
}
}
#Jumper{
position: absolute;
top: 46%;
left: 48%;
height: 8%;
width: 4%;
background-color: red;
opacity: 1;
}
<div id='Jumper'></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Can anyone please tell me how I can fix this?
Here is a fiddle of it: https://jsfiddle.net/Tobsta/2gnoq5hx/

You must use parseFloat(), because parseInt returns integer ::
Topp = parseFloat(document.getElementById('Jumper').style.top);
https://jsfiddle.net/2gnoq5hx/3/

It was this line that stuffed it all up:
Topp = parseInt(document.getElementById('Jumper').style.top);
Thanks Juhana for pointing that out.
Here's the working thing:
var interval = '';
var key = false;
var interval1 = '';
var key1 = false;
var interval2 = '';
var key2 = false;
var interval3 = '';
var key3 = false;
$(document).keydown(function(e) {
if(e.which === 38) {
if(key === false){
interval = setInterval(function(){Up()},20)
key = true;
}
}
if(e.which === 40) {
if(key1 === false){
interval1 = setInterval(function(){Down()},20)
key1 = true;
}
}
if(e.which === 37) {
if(key2 === false){
interval2 = setInterval(function(){Left()},20)
key2 = true;
}
}
if(e.which === 39) {
if(key3 === false){
interval3 = setInterval(function(){Right()},20)
key3 = true;
}
}
});
$(document).keyup(function(e) {
if(e.which === 38) {
clearInterval(interval)
key = false;
}
if(e.which === 40) {
clearInterval(interval1)
key1 = false;
}
if(e.which === 37) {
clearInterval(interval2)
key2 = false;
}
if(e.which === 39) {
clearInterval(interval3)
key3 = false;
}
});
document.getElementById('Jumper').style.top = '46%';
document.getElementById('Jumper').style.left = '48%';
var a = parseInt(document.getElementById('Jumper').style.top);
var b = parseInt(document.getElementById('Jumper').style.left);
function Up(){
if(a > 0){
a -= 1;
document.getElementById('Jumper').style.top = a+'%';
}
}
function Down(){
if(a < 92){
a += 1;
document.getElementById('Jumper').style.top = a+'%';
}
}
function Left(){
if(b > 0){
b -= 0.5;
document.getElementById('Jumper').style.left = b+'%';
}
}
function Right(){
if(b < 96){
b += 0.5;
document.getElementById('Jumper').style.left = b+'%';
}
}
#Jumper{
position: absolute;
top: 46%;
left: 48%;
height: 8%;
width: 4%;
background-color: red;
opacity: 1;
}
<div id='Jumper'></div>
Or the js fiddle
http://www.jsfiddle.net/Tobsta/2gnoq5hx/2

Related

how both player move at the same time (js game)

И have a hockey game in javascript but tво players can not move at the same time. In fact, when one moves, the other remains motionless. It is normal for both players to move at the same time in this game. Do you know a function that can help me? Should a foreign function be added? Thank you for your help.
<html>
<head>
<style>
body {
margin: 0;
}
.P1 {
position: absolute;
font-size: 110px;
background-color: white;
}
.P2 {
position: absolute;
left: 1500px;
font-size: 110px;
background-color: white;
}
</style>
</head>
<body onkeydown="keyD(event)">
<span class="P1">|</span>
<span class="P2">|</span>
</body>
<script>
var P1D = 0;
var P2D = 0;
var spanP1 = document.getElementsByClassName("P1")[0];
var spanP2 = document.getElementsByClassName("P2")[0];
function keyD(e) {
if (e.keyCode == 38 || e.keyCode == 40) {
f1(e);
}
if (e.keyCode == 83 || e.keyCode == 87) {
f2(e);
}
}
function f1(e) {
if (e.keyCode == 40) {
if (P2D >= 620) {
} else {
P2D += 10;
spanP2.style.top = P2D + "px";
}
}
if (e.keyCode == 38) {
if (P2D <= -20) {
} else {
P2D -= 10;
spanP2.style.top = P2D + "px";
}
}
}
function f2(e) {
if (e.keyCode == 83) {
if (P1D >= 620) {
} else {
P1D += 10;
spanP1.style.top = P1D + "px";
}
}
if (e.keyCode == 87) {
if (P1D <= -20) {
} else {
P1D -= 10;
spanP1.style.top = P1D + "px";
}
}
}
</script>
</html>
You would need to remember which keys are pressed down or not. For example by saving their state in an object.
Furthermore, when player 1 has a key pressed and player 2 starts pressing another, the key of player 1 stops repeating for a moment. To prevent this you would need to stop relying on the key repeat of the system of the user. For example by using a setInterval or later implement it into your gameloop. Example:
// Save key states in an object
const keystates = {}
document.addEventListener('keydown', e => {
keystates[e.code] = true
})
document.addEventListener('keyup', e => {
keystates[e.code] = false
})
// Repeat the key action in your gameloop
const repeat_interval = 500
setInterval(() => {
if (keystates['KeyW']) console.log('Player1 up')
if (keystates['KeyS']) console.log('Player1 down')
if (keystates['ArrowUp']) console.log('Player2 up')
if (keystates['ArrowDown']) console.log('Player2 down')
}, repeat_interval)
EDIT:
Also don't use keyCode as it is deprecated

Javascript: Global Variables Aren't Defined In Other Functions

I have three variables that I need to put in the innerHTML of four spans. The variables I use are seconds, accurateclick, and inaccurateclick. The process I use to get these variables is fine. The problem is I can't figure out how to bring them over to another function. I will make a replica of what I have. This will be a simpler version.
var x;
var y;
var z;
function A(){
x = 1;
y = 2;
z = 3;
B();
}
function B(){
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
}
What would happen is, instead of a being equal to 1, b being equal to 2, and c being equal to 3, they would all equal to undefined. I don't know why that is happening when x, y, and z are global variables. I thought they should change when set to a different value.
Here is my actual code:
var seconds;
var accurateclicks;
var inaccurateclicks;
var windowheight = window.innerHeight;
var windowwidth = window.innerWidth;
var colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Purple"];
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
function BeginGameLoad(){
var BottomLabel1 = document.getElementById("bl1");
var BeginGameContainer = document.getElementById("BGC1");
var RightClick = false;
BottomLabel1.addEventListener("mousedown", BL1MD);
BottomLabel1.addEventListener("mouseup", BL1MU);
BottomLabel1.style.cursor = "pointer";
window.addEventListener("resize", BeginGameResize);
window.addEventListener("contextmenu", BeginGameContextMenu);
function BeginGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL1MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel1.style.color = randomcolor;
RightClick = false;
}
}
function BL1MU(){
if(RightClick == false){
window.location.href = "Game.html";
GameLoad();
}
else{
RightClick = false;
}
}
if(windowheight < 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
BeginGameContainer.style.width = "800px";
}
function BeginGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
BeginGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
BeginGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
BeginGameContainer.style.width = "100%";
}
}
}
function GameLoad(){
var LeftPanel2 = document.getElementById("lp2");
var LeftColorPanel2 = document.getElementById("lcp2");
var TopPanel2 = document.getElementById("tp2");
var TopLabel2 = document.getElementById("tl2");
var RightPanel2 = document.getElementById("rp2")
var RightLabel2 = document.getElementById("rl2");
var GameContainer = document.getElementById("GC2");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var clickedRightName = false;
var clickedRightColor = false;
var clickedRightNameColor = false;
var RightClick = false;
var ClickedLeftColorPanel = false;
var ClickedRightLabel = false;
var ClickedTopLabel = false;
var Timer;
TopPanel2.addEventListener("mouseup", TP2MU);
TopLabel2.addEventListener("mousedown", TL2MD);
TopLabel2.addEventListener("mouseup", TL2MU);
TopLabel2.style.cursor = "pointer";
LeftPanel2.addEventListener("mouseup", LP2MU);
LeftColorPanel2.addEventListener("mouseup", LCP2MU);
LeftColorPanel2.addEventListener("mousedown", LCP2MD);
LeftColorPanel2.style.cursor = "pointer";
RightPanel2.addEventListener("mouseup", RP2MU);
RightLabel2.addEventListener("mouseup", RL2MU);
RightLabel2.addEventListener("mousedown", RL2MD);
RightLabel2.style.cursor = "pointer";
window.addEventListener("resize", GameResize);
window.addEventListener("contextmenu", GameContextMenu);
function AddSeconds(){
seconds++;
}
function GameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function TL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true){
TopLabel2.style.color = randomcolor;
RightClick = false;
}
}
function TP2MU(){
if(ClickedTopLabel == false){
inaccurateclicks++;
}
else{
ClickedTopLabel = false;
}
}
function TL2MU(){
ClickedTopLabel = true;
if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
accurateclicks++;
window.location.href = "EndGame.html";
EndGameLoad();
}
else if (!clickedRightName == true && !clickedRightColor == true && !clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
Timer = setInterval(AddSeconds, 1000);
seconds = 0;
accurateclicks = 0;
inaccurateclicks = 0;
TopLabel2.innerHTML = randomcolor;
RightClick = false;
}
else{
inaccurateclicks++;
}
RightClick == false
}
function LCP2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function LCP2MU(){
ClickedLeftColorPanel = true;
if(clickedRightColor == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == LeftColorPanel2.style.backgroundColor){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.color){
LeftColorPanel2.style.backgroundColorr = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.backgroundColor){
LeftColorPanel2.style.backgroundColor = randomcolor2;
accurateclicks++;
}
if (LeftColorPanel2.style.backgroundColor == randomcolor.toLowerCase()){
clickedRightColor = true;
LeftColorPanel2.style.cursor = "auto";
}
randomcolor2 = null;
RightClick = false;
}
else if(clickedRightColor == true && RightClick == false){
inaccurateclicks++;
}
}
function LP2MU(){
if(ClickedLeftColorPanel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
function RL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function RL2MU(){
ClickedRightLabel = true;
if(clickedRightName == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2 == RightLabel2.innerHTML){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2 != RightLabel2.innerHTML){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2 != RightLabel2.color){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
}
if (RightLabel2.innerHTML == randomcolor){
clickedRightName = true;
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == false && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == RightLabel2.style.color){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
}
if (RightLabel2.style.color == randomcolor.toLowerCase()){
clickedRightNameColor = true;
RightLabel2.style.cursor = "auto";
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == true && RightClick == false){
inaccurateclicks++;
}
}
function RP2MU(){
if(ClickedRightLabel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
if(windowheight < 600)
{
GameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
GameContainer.style.width = "800px";
}
function GameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
GameContainer.style.height = "600px";
}
if(windowheight > 600)
{
GameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
GameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
GameContainer.style.width = "100%";
}
}
}
function EndGameLoad(){
var BottomLabel3 = document.getElementById("bl3");
var EndGameContainer = document.getElementById("EGC3");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var RightClick = false;
BottomLabel3.addEventListener("mousedown", BL3MD);
BottomLabel3.addEventListener("mouseup", BL3MU);
BottomLabel3.style.cursor = "pointer";
window.addEventListener("resize", EndGameResize);
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
window.addEventListener("contextmenu", EndGameContextMenu);
function EndGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL3MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true
}
else{
randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel3.style.color = randomcolor;
RightClick = false;
}
}
function BL3MU(){
if(RightClick == false){
MiddleLabelTwo.innerHTML = "Time (Seconds): "
MiddleLabelThree.innerHTML = "Accurate Clicks: "
MiddleLabelFour.innerHTML = "Inaccurate Clicks: "
MiddleLabelFive.innerHTML = "Score: "
window.location.href = "Game.html";
}
}
if(windowheight < 600)
{
EndGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
EndGameContainer.style.width = "800px";
}
function EndGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
EndGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
EndGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
EndGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
EndGameContainer.style.width = "100%";
}
}
}
Whenever I run it, it works up to this point
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
It says seconds, accurateclicks, and inaccurateclicks are all undefined. I don't know why this would happen given that they were defined in the previous function [Game()].
try writing,
x = 1;
y = 2;
z = 3;
function A() {
B();
}
function B() {
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
console.log(a, b, c, d);
}
A();
Reason: 'var' defines variables locally!
You did make two html files and this caused the js file to reload. This is why the global variables are declared again and are renewed to undefined.The solution is to work with one html file and to only reload the body.
My syntax was right, but as #Julie mentioned, the variables were being reloaded. How to get JS variable to retain value after page refresh? this helped me solve my problem.

Javascript function for moving div with arrow keys not working?

I've been trying to move a div around a page just using the arrows keys on my keyboard. It seems not to be working. I had it working before but for some reason it is no longer working. Could you let me know what you think the issue is? I have a feeling it has something to do with window.onkeydown and onkeyup.
Thank you for any help in advance.
CSS --
#log {
position:absolute;
width: 50px;
height: 50px;
border: 2px solid black;
background-color: white;
color: black;
font-size: 20px;
left: 20px;
}
HTML---
<div id="log"></div>
JavaScript --
var Keys = {
up: false,
down: false,
left: false,
right: false
};
var hero = {
x: 0,
y: 0
};
var log = document.getElementById("log");
window.onkeydown = function(e){
var kc = e.keyCode;
e.preventDefault();
if(kc === 37) Keys.left = true;
if(kc === 38) Keys.up = true;
if(kc === 39) Keys.right = true;
if(kc === 40) Keys.down = true;
};
window.onkeyup = function(e){
var kc = e.keyCode;
e.preventDefault();
if(kc === 37) Keys.left = false;
if(kc === 38) Keys.up = false;
if(kc === 39) Keys.right = false;
if(kc === 40) Keys.down = false;
};
function main() {
move();
};
function move(){
if(Keys.up){
hero.y -= 10;
var p = hero.y;
var t = p + 10;
log.style.top = p + "px";
log.style.bottom = t + "px";
//color();
}
if(Keys.down){
hero.y += 10;
var g = hero.y;
var q = g - 10;
log.style.bottom = g + "px";
log.style.top = q + "px";
//color();
}
if(Keys.left) {
hero.x -= 10;
var z = hero.x;
var q = z + 10;
log.style.left = z + "px";
log.style.right = q + "px";
//color();
}
if(Keys.right){
hero.x += 10;
var z = hero.x;
var q = z - 10;
log.style.right = z + "px";
log.style.left = q + "px";
// color();
}
}
setInterval(main, 50);
If you're open to using jQuery this might help you out.
$(document).ready(function() {
var hero = $("#log");
var speed = 1;
var direction = {
left: false,
up: false,
right: false,
down: false
};
$(document).on('keydown', function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) direction.left = true;
if (kc === 38) direction.up = true;
if (kc === 39) direction.right = true;
if (kc === 40) direction.down = true;
});
$(document).on('keyup', function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) direction.left = false;
if (kc === 38) direction.up = false;
if (kc === 39) direction.right = false;
if (kc === 40) direction.down = false;
});
function move() {
if (direction.left) hero.css("left", (hero.position().left - speed) + "px");
if (direction.up) hero.css("top", (hero.position().top - speed) + "px");
if (direction.right) hero.css("left", (hero.position().left + speed) + "px");
if (direction.down) hero.css("top", (hero.position().top + speed) + "px");
}
setInterval(move, 1);
});
Here's a Fiddle to demonstrate the result. Feel free to customize it to your needs.
UPDATE
And here's another Fiddle to accept multiple buttons pressed at the same time.

issue when trying to move two div's onkeydown

The code seems right to me but when i try to move the div with class ai using the key 'A' and 'Q' it doesn't work , it work only with the div which have the class player when hitting up and down arrow :
LIVE DEMO
JavaScript :
var playerPosition = 0,
playerPosition2 = 0;
window.onkeydown = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if(key == 40) { // up arrow
playerPosition += 5;
} if(key == 38) { // down arrow
playerPosition -= 5;
}
if(key == 113) { // q buttton
playerPosition2 += 5;
} if(key == 97) {
playerPosition2 -= 5; // a button
}
var players1 = document.getElementsByClassName('player');
for(var i = 0; i < players1.length; i++) {
if (playerPosition < 0) {
playerPosition = 0;
}
else if (playerPosition > 330) {
playerPosition = 330;
}
players1[i].style.top = playerPosition + "px";
}
var players2 = document.getElementsByClassName('ai');
for(var i = 0; i < players2.length; i++) {
if (playerPosition2 < 0) {
playerPosition2 = 0;
}
else if (playerPosition > 330) {
playerPosition2 = 330;
}
players2[i].style.top = playerPosition2 + "px";
}
}
Not sure where you got those keyCode values
a = 65
q = 81
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

How to move an element in javascript automatically with while loop?

I am making a Snake game so I'm trying to move my snake. It is moving with keys but it should move automatically on the screen. I tried doing that with while loops like in the code below but because of break; I have to press a key every time I want it to move. How can I make it move automatically? I tried removing break; an using an if statement but I didn't succeed.
Any other solutions or something else?
I'm new to programming so any advices would be helpful.
var main = function() {
var i = 0;
var j = 0;
$(document).keyup(function(event) {
var e = event.which;
while(i == 1) {
$('.snake').animate({left: '+=10px'}, 10);
break;
}
while(i == 2) {
$('.snake').animate({left: '-=10px'}, 10);
break;
}
while(i == 3) {
$('.snake').animate({top: '-=10px'}, 10);
break;
}
while(i == 4) {
$('.snake').animate({top: '+=10px'}, 10);
break;
}
//Which key is preesed
//D
if(e == 68) {
i = 1;
}
//A
else if(e == 65) {
i = 2;
}
//W
else if(e == 87) {
i = 3;
}
//S
else if(e == 83) {
i = 4;
}
//Any other key
else {
i = 0;
}
});
};
$(document).ready(main);
I think you just have to organize a little bit your code.
First. You must put your code inside a function. You really don't need a while. You can use a simple if.
function move(i) {
if(i == 1) {
$('.snake').animate({left: '+=10px'}, 10);
break;
}
if(i == 2) {
$('.snake').animate({left: '-=10px'}, 10);
break;
}
if(i == 3) {
$('.snake').animate({top: '-=10px'}, 10);
break;
}
if(i == 4) {
$('.snake').animate({top: '+=10px'}, 10);
break;
}
}
Now you have to change the event, using keydown instead of keyup
function main() {
var interval;
$(document).keydown(function(event) {
if(interval) clearInterval(interval); // Clear the previous interval
var e = event.which;
var i;
//Which key is pressed
//D
if(e == 68) {
i = 1;
}
//A
else if(e == 65) {
i = 2;
}
//W
else if(e == 87) {
i = 3;
}
//S
else if(e == 83) {
i = 4;
}
//Any other key
else {
i = 0;
}
interval = setInterval(function() {
move(i)
},1000); // repeat every 1 second
});
}
$(document).ready(main);

Categories

Resources