Make an object move towards another objects position

前端 未结 2 774
情深已故
情深已故 2021-01-22 01:23

What I have currently is two objects that can be played though nav keys and the other one with wasd. The point is to get the 3rd object and score a point, and it randoms a new p

2条回答
  •  忘掉有多难
    2021-01-22 02:16

    Try something like this

        public void FlyttaMot(int x, int y, float speed)
        {
            float tx = x - pt.X;
            float ty = y - pt.Y;
            float length = Math.Sqrt(tx*tx + ty*ty);
            if (length > speed)
            {
                // move towards the goal
                pt.X = (int)(pt.X + speed* tx/length);
                pt.Y = (int)(pt.Y + speed* ty/length);
            }
            else
            {
                // already there
                pt.X = x;
                pt.Y = y;
            }
        }
    

    Call it from your timer tick code in Form.cs like this for example.

    npc2.FlyttaMot(200, 200, 0.5f);
    

    I based this on linear algebra. Take a look at this video for example. The (tx,ty) is the vector in which direction the npc should go. Dividing with the length of the vector gives us a vector of length 1. I multiply this with a speed parameter so you can adjust the speed of the npc.

提交回复
热议问题