Move point to another in c#

前端 未结 1 1716
暖寄归人
暖寄归人 2021-01-03 11:15

I would like to move some point a in two dimensional search space to another point b with some stepsize (_config.StepSize = 0.03).

Point a = agent.Location;         


        
相关标签:
1条回答
  • 2021-01-03 12:11

    Assuming you mean you want to move one point towards another point and assuming your step size has distance units, then no, your calculation is not correct.

    The correct formula is:

    • nextLocation = a + UnitVector(a, b) * stepSize

    In C#, using just a simple Point class and the Math library, this looks like:

    public Point MovePointTowards(Point a, Point b, double distance)
    {
        var vector = new Point(b.X - a.X, b.Y - a.Y);
        var length = Math.Sqrt(vector.X * vector.X + vector.Y * vector.Y);
        var unitVector = new Point(vector.X / length, vector.Y / length);
        return new Point(a.X + unitVector.X * distance, a.Y + unitVector.Y * distance);
    }
    

    Edit: Updated code as per TrevorSeniors suggestion in comments

    0 讨论(0)
提交回复
热议问题