Character movement with Mouse

Hello,
Sorry for newbie question but How to movement Game Character with Mouse?
Something like I am have: mouseX, mouseY, playerX = 0, playerY = 0.
If I am click mouse get cordinates in mouseX and mouseY(Something like now mouseX = 5 and mouseY = 10) and move Character to x 1 and y 3(playerX = 1 and playerY = 3 now)
How to move Game character(wihout Teleport) to mouseX and mouseY cordinates?

Simple code snippets very useful.

Thanks and sorry for my English language.

movement over time: http://en.wikipedia.org/wiki/Linear_interpolation

The simplest case, two known points. A good exercise to code yourself, though a googlefu may find it readyrolled.

first you need to find the angle


double angle = Math.atan2(mouseY-playerY,mouseX-playerX);

then you need to build a vector to calculate the movement threshold


double movex = Math.cos(angle);
double movey = Math.sin(angle);

and now to move towards the point


x += movex;
y += movey;
if (x == mouseX && y == mouseY) { // you can use epsilon here
 stop();
}

hth

That is NOT going to work. In 99.999999999999% of all cases it will just overshoot and continue forever. You would need to change the if-statement to detect overshooting and then set the position to (mouseX, mouseY) to actually land on the mouse position.

thats why I also write use an epsilon here in the comment, its up to OP to implement an epsilon though.

  • David

just quick question, is epsilon sort of like margin of error? so it can be off slightly of the exact point, and doesnt skip it?

I think theagentd’s point is that there’s no guarantee that N steps, for any integer N, will land the player on the target position, either exactly or within the epsilon margin-of-error. You’d need to choose the step length (as well as the step direction) carefully to achieve that. Or (as Karmington said) interpolate between the original position and the target position. Or do something like the following, which moves the player towards the target at a fixed speed.


static final double stepSize = 5.0;  // the player's speed (how far to move each update)

double playerX, playerY; // current position
double targetX, targetY; // where the mouse click happened

// move the player one step closer to the target position
void updatePosition() {
  double dx = targetX - playerX,
         dy = targetY - playerY;
  double distance = Math.hypot(dx,dy);
  if ( distance > stepSize ) {
    // still got a way to go, so take a full step
    playerX += stepSize*dx/distance;
    playerY += stepSize*dy/distance;
  } else {
    // we're either at the target already, or within one step of it
    playerX = targetX;
    playerY = targetY;
  }
}

Simon