• Advertisement
Sign in to follow this  

Help with movement in javascript [noob]

This topic is 1835 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

ok, I am very new to programming so it may sound like a stupid question but I can't work it out.

 

So, with the help of a book, I made an animation in javascript with html5, basically there is and animation loop that constantly increases the variables that store the data of shapes positions. I understand it all, but I want to make it so the shapes only move when I am pressing buttons on my keyboard, so I can move a shape around the screen. 

 

I think I just need to put an if loop around the bit where I increase the x and y positions with the condition that a certain button is pressed. I don't know how to detect if a button if pressed and was hoping for an easy solution that is only a few lines of code.

 

Also, if you can't answer the question directly, are there any good websites/tutorials that do, I googled it but didn't find anything useful.

Share this post


Link to post
Share on other sites
Advertisement

Handling keyboard events in JavaScript is fairly straightforward. 

 

Not sure if your using any libraries or what your code looks like, but I suspect the information in this blog post should help get an understanding of how to do what you're after, specifically this portion:

 

window.addEventListener('keydown', function(event) {
  switch (event.keyCode) {
    case 37: // Left
      Game.player.moveLeft();
    break;

    case 38: // Up
      Game.player.moveUp();
    break;

    case 39: // Right
      Game.player.moveRight();
    break;

    case 40: // Down
      Game.player.moveDown();
    break;
  }
}, false);

 

Hope that helps. :)

Share this post


Link to post
Share on other sites
Handling keyboard events in JavaScript is fairly straightforward. 

 

Not sure if your using any libraries or what your code looks like, but I suspect the information in this blog post should help get an understanding of how to do what you're after, specifically this portion:

 

window.addEventListener('keydown', function(event) {
  switch (event.keyCode) {
    case 37: // Left
      Game.player.moveLeft();
    break;

    case 38: // Up
      Game.player.moveUp();
    break;

    case 39: // Right
      Game.player.moveRight();
    break;

    case 40: // Down
      Game.player.moveDown();
    break;
  }
}, false);

 

Hope that helps. smile.png

Yh thats was extremely helpful, I got it working, thanks!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement