Help with movement in javascript [noob]

Started by
2 comments, last by FalconDragoon 11 years, 4 months ago

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.

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. :)

My Games -- My Music 

Come join us for some friendly game dev discussions over in XNA Chat!

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!

Happy to help!

My Games -- My Music 

Come join us for some friendly game dev discussions over in XNA Chat!

This topic is closed to new replies.

Advertisement