Salve a tutti, spero che questa sia la sezione giusta. Sto attualmente studiando un libro per realizzare giochi in html5/css3/JavaScript/JQuery.
Devo gestire l'input da tastiera senza che eventi diversi (premere più tasti contemporaneamente) si annullino l'un l'altro.
Il codice del libro NON funziona.
JQuery
HTMLcodice:var pingpong = {}; pingpong.pressedKeys = []; $(function() { // set interval to call gameloop every 30 milliseconds pingpong.timer = setInterval(gameloop, 30); // mark down what key is down and up into an array called // "pressedKeys" $(document).keydown(function(e) { pingpong.pressedKeys[e.which] = true; }); $(document).keyup(function(e) { pingpong.pressedKeys[e.which] = false; }); }); function gameloop() { movePaddles(); } function movePaddles() { // use our custom timer to continuously check if a key is // pressed. if (pingpong.pressedKeys[KEY.UP]) {// arrow-up // move the paddle B up 5 pixels var top = parseInt($("#paddleB").css("top")); $("#paddleB").css("top", top - 5); } if (pingpong.pressedKeys[KEY.DOWN]) {// arrow-down // move the paddle B down 5 pixels var top = parseInt($("#paddleB").css("top")); $("#paddleB").css("top", top + 5); } if (pingpong.pressedKeys[KEY.W]) {// w // move the paddle A up 5 pixels var top = parseInt($("#paddleA").css("top")); $("#paddleA").css("top", top - 5); } if (pingpong.pressedKeys[KEY.S]) {// s // move the paddle A down 5 pixels var top = parseInt($("#paddleA").css("top")); $("#paddleA").css("top", top + 5); } }
Ho provato a fare dei tentativi, cambiamenti, ma niente, l'input non viene captato.codice:<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>MyGame</title> <style> #playground { background: #e0ffe0; width: 400px; height: 200px; position: relative; overflow: hidden; } #ball { background: #fbb; position: absolute; width: 20px; height: 20px; left: 150px; top: 100px; border-radius: 10px; } .paddle { background: #bbf; left: 50px; top: 70px; position: absolute; width: 30px; height: 70px; } #paddleB { left: 320px; } </style> </head> <body> <header> <h1>Test</h1> </header> <div id="game"> <div id="playground"> <div id="paddleA" class="paddle"></div> <div id="paddleB" class="paddle"></div> <div id="ball"></div> </div> </div> <footer> This is an example of creating a Ping Pong Game. </footer> <script src="js/jquery-1.11.3.js"></script> <script src="js/html5games.pingpong.js"></script> </body> </html>

Rispondi quotando
