javascript - Why and (&) in if statement is not working? -
this question has answer here:
- javascript multiple keys pressed @ once 8 answers
so making html5 game working in movement. player can move w, a, s ,d in key. working wanted add power ..like if player press + space-bar or d + space-bar ability trigger.
i used , operator , should have worked in theory it's not working. new in html5 , appreciated. in advance.
here code... copy paste on html note.
<canvas id="canvas" width="800" height="500" style="border:1px solid #000000;"></canvas> <script> var c = document.getelementbyid("canvas").getcontext("2d"); var width = 800; var height = 500; var player = { x: math.random() * width, y: math.random() * height, width: 30, height: 30, color: 'black', pressingdown: false, pressingup: false, pressingleft: false, pressingright: false, pressinpowerright: false, pressinpowerleft: false, }; drawentity = function(e) { c.fillstyle = e.color; c.fillrect(e.x - e.width / 2, e.y - e.height / 2, e.width, e.height); } document.onkeydown = function(event) { if (event.keycode === 68) //d player.pressingright = true; else if (event.keycode === 83) //s player.pressingdown = true; else if (event.keycode === 65) //a player.pressingleft = true; else if (event.keycode === 87) // w player.pressingup = true; else if (event.keycode === 68 && event.keycode === 32) // statement not working player.pressinpowerright = true; else if (event.keycode === 65 && event.keycode === 32) // statement not working player.pressinpowerleft = true; } document.onkeyup = function(event) { if (event.keycode === 68) //d player.pressingright = false; else if (event.keycode === 83) //s player.pressingdown = false; else if (event.keycode === 65) //a player.pressingleft = false; else if (event.keycode === 87) // w player.pressingup = false; else if (event.keycode === 68 && event.keycode === 32) // not working player.pressinpowerright = false; else if (event.keycode === 65 && event.keycode === 32) // not working player.pressinpowerleft = false; } updateplayerposition = function() { if (player.pressingright) player.x += 5; if (player.pressingleft) player.x -= 5; if (player.pressingdown) player.y += 5; if (player.pressingup) player.y -= 5; if (player.pressingpowerright) player.x += 50; if (player.pressingpowerleft) player.x -= 50; } update = function() { c.clearrect(0, 0, width, height); updateplayerposition(); drawentity(player); } setinterval(update, 40); </script>
by making if , else if tree making condition satisfied not further button presses. need check both button presses (space bar , a) before checking single button presses not short circuit logic
Comments
Post a Comment