<!DOCTYPE html> <html lang="cs"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Auticko 2019-11-13</title> <style> #hra { width:80%; margin:0 auto; height:80vh; background-color:#f0f0f0; border:2px solid black; position:relative; overflow:hidden; } .auticko { width:100px; height:200px; background-color:green; position:absolute; } </style> </head> <body> <div id="hra"> <div id="auticko" class="auticko"> </div> <script> /* <![CDATA[ */ document.body.onload = function(){ //Jsou zmacknute klavesy? var ovladaniNahoru = false; var ovladaniDolu = false; var ovladaniDoleva = false; var ovladaniDoprava = false; /* Atributy auticka */ var x=200; var y=200; var rychlost=0; var uhel=0; /* html element auticka */ var autickoElement = document.getElementById('auticko') var nactiKlavesy = function(){ if (ovladaniNahoru){ rychlost += 0.5 } //TODO: ostatni } //Herni loop - vykreslovací funkce var vykresliVse = function(){ var rychlostX = getXDiff (uhel, rychlost); var rychlostY = getYDiff (uhel, rychlost); x += rychlostX; y += rychlostY; //Zapis nove souradnice autickoElement.style.top=y+"px"; autickoElement.style.left=x+"px"; autickoElement.style.transform="rotate("+uhel+"deg)"; } /* Pomocne funkce */ function getXDiff(angle,velocity){ var angleRad=((angle+90)/180)*Math.PI; return Math.cos(angleRad)*velocity; } function getYDiff(angle,velocity){ var angleRad=((angle+90)/180)*Math.PI; return Math.sin(angleRad)*velocity; } //Herni loop setInterval(vykresliVse, 16.6); setInterval(nactiKlavesy, 16.6); /* Ovladani klavesnici */ document.addEventListener('keydown', function(event){ //Klavesa byla zmacknuta (jde dolu) const keyName = event.key; if(keyName === 'a' || keyName === 'A'){ ovladaniDoleva=true; } if(keyName === 'd' || keyName === 'D'){ ovladaniDoprava=true; } if(keyName === 's' || keyName === 'S'){ ovladaniDolu=true; } if(keyName === 'w' || keyName === 'W'){ ovladaniNahoru=true; } }); document.addEventListener('keyup', function(event){ //Klavesa byla odmacknuta (jde nahoru) const keyName = event.key; if(keyName === 'a' || keyName === 'A'){ ovladaniDoleva=false; } if(keyName === 'd' || keyName === 'D'){ ovladaniDoprava=false; } if(keyName === 's' || keyName === 'S'){ ovladaniDolu=false; } if(keyName === 'w' || keyName === 'W'){ ovladaniNahoru=false; } }); } /* ]]> */ </script> </body> </html>