Search code examples
javascriptjquerykeyboardgame-physics

jQuery - how to move figure in coordinationsystem


Lets say that I have this code:

<div id="gameFrame">
   <div id="figure"></div>
</div>

Where the figure div is lets say a picture of a figure. How can i use jQuery in order to move the figure inside the gameFrame with the keyboard keys up down left and right?


Solution

  • With the exception of keyboard use, what you are trying to do has already been done in the jQuery Draggable module: http://jqueryui.com/demos/draggable/#default. You might be able to use what they have done their as a start point. The actual code is here: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.draggable.js.

    The downside is that you might have to put considerable effort into extending/modifying the code, and it will still likely depend on other jQuery code.

    Then again, you could probably whip something up in a fraction of the size of the jQuery code. But, I thought I'd post this in case no one else turned anything up.

    If you want to do it yourself, the general process would be:

    1. Wrap the item you want to move in a container (like another div) and set the position to be relative using CSS.
    2. Bind keyboard events for the arrow keys
    3. When a key is pressed, modify the positioning of the element to move it (CSS attributes like left and top)