Calculate a point along the line A-B at a given distance from A

前端 未结 6 1384
情歌与酒
情歌与酒 2020-11-29 08:54

I\'m going quite mad trying to calculate the point along the given line A-B, at a given distance from A, so that I can "draw" the line between two given points. It

6条回答
  •  臣服心动
    2020-11-29 09:29

    Better approach (you can rename the struct if you need):

    struct Vector2
    {
        public readonly float X;
        public readonly float Y;
    
        public Vector2(float x, float y)
        {
            this.X = x;
            this.Y = y;
        }
    
        public static Vector2 operator -(Vector2 a, Vector2 b)
        {
            return new Vector2(b.X - a.X, b.Y - a.Y);
        }
        public static Vector2 operator +(Vector2 a, Vector2 b)
        {
            return new Vector2(a.X + b.X, a.Y + b.Y);
        }
        public static Vector2 operator *(Vector2 a, float d)
        {
            return new Vector2(a.X * d, a.Y * d);
        }
    
        public override string ToString()
        {
            return string.Format("[{0}, {1}]", X, Y);
        }
    }
    

    For getting the midpoint you just need to do the (a - b) * d + a action:

    class Program
    {
        static void Main(string[] args)
        {
            Vector2 a = new Vector2(1, 1);
            Vector2 b = new Vector2(3, 1);
            float distance = 0.5f; // From 0.0 to 1.0.
            Vector2 c = (a - b) * distance + a;
            Console.WriteLine(c);
        }
    }
    

    This will give you the point:

    50%

    output:\> [2, 1]

    All you need after that is to for(the distance; up toone; d += step) from 0.0 to 1.0 and draw your pixels.

提交回复
热议问题