简体   繁体   English

用鼠标平稳地移动对象

[英]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 . 例如,我要将对象从A点移动到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 . 我可以以45°角移动它,直到它具有与单击鼠标相同的轴之一,然后像这样使它笔直移向另一个轴。 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 . 每一步移动的总距离取决于浮动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. 其中update根据给定的速度更新位置。 Each click, mvtEnabled is set to true and the final coordinates are recalculated. 每次单击时,将mvtEnabled设置为true,并重新计算最终坐标。

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. 并在更新对象的位置时使用此角度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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