Wednesday, November 2, 2011

Mouse Movement by Dragging

So I forgot to post this one type of movement piece. It's pretty simple if you know how to do the math which I will show you. Like the other snippets it's not entirely polished so there is definitely improvements that can be made to the movement style. This snippet will do a simple move towards the cursor when the mouse is dragged.

Other ways to do mouse movement is point-and-click movement. Point-and-click movement usually works along side a good pathfinding algorithm using either tiles or nodes. So here's the meat of this snippet.
  // only move if the user is dragging the mouse and we aren't already
  // at the mouse position
  if (dragging && !isMouseOverBlock()) {
   // the amount to move the character in x and y directions
   double dx = 0.0d;
   double dy = 0.0d;

   // relative mouse position from the character
   double relativeMouseX = mouseX - basicBlock.x;
   double relativeMouseY = mouseY - basicBlock.y;

   // determine the angle the mouse is from the current position
   double angle = Math.atan2(relativeMouseY, relativeMouseX);

   // now determine based on the angle what direction to move in
   dx = Math.cos(angle);
   dy = Math.sin(angle);

    * move the block by multiplying the amount of time in seconds that
    * has passed since the last update by the speed constant and by the
    * change in x or y directions which will either will result in += 0
    * or dt * speed negative or positive.
   basicBlock.x += dt * speed * dx;
   basicBlock.y += dt * speed * dy;   
So one of the tricks here is knowing how to use the atan2 method. It gives you the angle for the Cartesian points x,y passed to the function using the arctan trig function. Once we have the angle it's a simple matter to move in that direction based on speed and time. You can think of the dx and dy as percentages of the speed to apply and the dt as the amount of time applied.

Some ehancements that could be made to this snippet are things like using acceleration instead of pure speed. You could use this snippet to experiment with different styles of mouse movement such as the point and click and other variations as per your gameplay.

There is also a little bug I noticed in this example, sometimes when moving the block if it is over the mouse cursor it will sometimes jump quickly back and forth around the cursor. I tried to fix it by using the isMouseOverBlock but it wasn't 100% successful. If you figure it out please let me know.
Here's the full snippet:

No comments:

Post a Comment