简体   繁体   中英

Moving object with mouse smoothly

I want my object to follow where my mouse is, like a point and click game. Problem is, while I can make my object move to where my mouse clicked, I can't make it do so smoothly. For example, I want to move my object from point A to point B . I can move it in a 45° angle until it has one of the same axis's as my mouse click, and then have it move straight towards the other axis like this . But I can't figure out how to make it move smooth, like this .

I move my object with this:

private void Game_MouseMove(object sender, MouseEventArgs e)
{
    if (IsMouseDown == true)
    {
        _xClick = e.Location.X;
        _yClick = e.Location.Y;
        timerClickMovement.Enabled = true;
    }
}
private void Game_MouseDown(object sender, MouseEventArgs e)
{
    IsMouseDown = true;
}
private void Game_MouseUp(object sender, MouseEventArgs e)
{
    IsMouseDown = false;
}
private void timerClickMovement_Tick(object sender, EventArgs e)
{
    if (_x != _xClick || _y != _yClick)
    {
        //_x and _y is the location of the object I want to move.
        if (_x > _xClick)
        { _x--; }
        else if (_x < _xClick)
        { _x++; }
        if (_y > _yClick)
        { _y--; }
        else if (_y < _yClick)
        { _y++; }
        Invalidate();
    }
    else
    { timerClickMovement.Enabled = false; }
}

What can I do to make the movement more direct?

To move an object in a game toward a specific direction, you can use the following pseudocode:

x_delta = cos(direction)*speed;
y_delta = sin(direction)*speed;

x_position+=x_delta;
y_position+=y_delta;

Where the total distance moved each step is determined by the float speed .

To travel toward a specific location, you can create a condition that prevents your object from moving faster than the final distance with something like:

if(mvtEnabled){
   float tempDst = object.dst(x_final, y_final);
   if(speed>tempDst){
      update(tempDst);
      mvtEnabled = false;
   }else{
      update(speed);
   }
}

Where update updates the positions based on the given speed. Each click, mvtEnabled is set to true and the final coordinates are recalculated.

You can get the angle between the starting location and the final location through something like this:

float direction = atan2(y_final - y_start, x_final - x_start);

and use this angle when you update your object's position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM