Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <title>JavaScript Key Press Move Div</title>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <style>
- #sprite{
- background:blue;
- width:50px;
- height:50px;
- position: relative;
- left: 10px;
- }
- </style>
- <script>
- //wait for document to load
- document.addEventListener("DOMContentLoaded", function(){
- let sprite = document.querySelector("#sprite");
- sprite.pos = 0;
- sprite.speed = 10;
- sprite.mleft = false;
- sprite.mright = false;
- });
- document.addEventListener('keydown', function( ev ) {
- if(ev.key == "ArrowRight"){ sprite.mright = true; }
- if(ev.key == "ArrowLeft"){ sprite.mleft = true; }
- });
- document.addEventListener('keyup', function( ev ) {
- if(ev.key == "ArrowRight"){ sprite.mright = false; }
- if(ev.key == "ArrowLeft"){ sprite.mleft = false; }
- });
- //Main Game Loop
- setInterval(function(){
- if ( sprite.mleft ){ sprite.pos -= sprite.speed; }
- if ( sprite.mright ){ sprite.pos += sprite.speed; }
- sprite.style.left = sprite.pos + "px";
- },10);
- </script>
- </head>
- <body>
- <div id="sprite"></div>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement