Search code examples
vb62dlinecollision

Math/programming: How to make an object go through a path made from a line


Now I am doing this in VB6 but I don't think it matters what I do it in, does it? I believe it has to do with math.

Here is the problem, have a look at this picture

enter image description here

As you can see in this image, there is a black line and a grey circle. I want the circle to move from the bottom left to the bottom right, but I also want it to stay along the path of the line so it reaches our second picture like this:

enter image description here

Now how can I accomplish this? Again, using VB6.


Solution

  • Ok, I don't know VBA6 but, since you said:

    I don't think it matters what I do it in

    I will give a generic solution that involves you having the center of the circles coordinates, and the lines endpoints.

    This line can be treated as a vector:

     (line.x2-line.x1, line.y2-line.y1)
    

    You don't need to write this in your program or anything just saying it is a vector.

    What you do need to is get the magnitude of the vector and assign it to a variable:

    unitSize = sqrt((line.x2-line.x1)^2 + (line.y2-line.y1)^2)
    

    Now make it into unit vector components and get the separate components:

    unitX = (line.x2-line.x1)/unitSize
    unitY = (line.y2-line.y1)/unitSize
    

    Now how ever you update the circle:

    do {
        circle.x = circle.x + unitX * incrementSize //incrementSize scales how big the movement is assign it to whatever you seem fit.
        circle.y = circle.y + unitY * incrementSize
    until (circle.x >= line.x2) //Or <= line.x2 depends which way you are going.
    

    Hopefully this helps.