1

Hi I am new to coding and I am using Lua and solar2d, trying to transition object1 via another object2's co-ordinates and for object1 to continue along the same path with the same velocity if it doesn't hit object2.

I can easily transition to the obeject but I don't know how to then go beyond that. transition.to( object1, { x=object2.x, y=object2.y, time=3000, })

I feel I will have to add an oncomplete but not sure what.

any help would be greatly appreciated.

LeapingJag
  • 11
  • 1

1 Answers1

1

You have to calculate the equation of the line (y = m * x + b) that you are traveling.

Formulas:

m = (y2 - y1) / (x2 - x1)

b = y1 - m * x1

So in your case:

m = (object2.y - object1.y) / (object2.x - object1.x)
b = object1.y - m * object1.x

Now you have the equation of the path (line) to keep if object1 doesn't hit object2.

When the transition ends, you want to check if the object2 is still there (object1 hit it) or not (object1 keeps moving), so you need to include an onComplete listener to check for that.

As for the speed, you have to decide if you want a constant speed and then you have to calculate the time for each transition or if you are using always 3 seconds no matter if the object2 is close or far away from the object1. I guess you probably want the first option, so it doesn't go pretty slow if objects are close and too fast if the object are far away. In that case you have to set a constant speed s, that you want.

Formulas:

Speed = Distance / Time

Time = Distance / Speed

Distance between 2 points:

d = squareRoot( (x2 - x1)^2 + (y2 - y1)^2 )

In summary, it would be something like that:

s = 10 --Constant speed
m = (object2.y - object1.y) / (object2.x - object1.x)
b = object1.y - m * object1.x

direction = 1 --assume it's traveling to the right
if(object2.x < object1.x)then
  direction = -1 --it's traveling to the left    
end

local function checkCollision( obj )
    if(obj.x == object2.x and obj.y == object2.y)then
        -- Object1 hit Object2
    else
        -- Object2 is not here anymore, continue until it goes offscreen
        -- following the line equation 

        x3 = -10 -- if it's traveling to the left
        if(direction == 1)then 
            --it's traveling to the right
            x3 = display.contentWidth + 10
        end
        y3 = m * x3 + b
        d2 = math.sqrt( (x3 - obj.x)^2 + (y3 - obj.y)^2 )
        t2 = d2 / s
        transition.to( obj, {x=x3, y=y3, time=t2} )
    end
end

d1 = math.sqrt( (object2.x - object1.x)^2 + (object2.y - object1.y)^2 )
t1 = d1 / s
transition.to( object1, { x=object2.x, y=object2.y, time=t1, onComplete=checkCollision} )

You should try different values for the speed s until you get the desired movement.

ednincer
  • 931
  • 8
  • 15