Calculated on the click of the mouse -
if math.abs(ship[0].target_x - ship[0].start_x) > math.abs(ship[0].target_y - ship[0].start_y) then ship[0].factor_x = (math.abs(ship[0].target_x - ship[0].start_x) / math.abs(ship[0].target_y - ship[0].start_y))end if math.abs(ship[0].target_x - ship[0].start_x) < math.abs(ship[0].target_y - ship[0].start_y) then ship[0].factor_y = (math.abs(ship[0].target_y - ship[0].start_y) / math.abs(ship[0].target_x - ship[0].start_x))end
Within characterUpdate (dt) -
if ship[0].x ~= ship[0].target_x then if (ship[0].start_x > ship[0].target_x) and (ship[0].x > ship[0].target_x) then ship[0].x = ship[0].x - (dt / ship[0].speed) * ship[0].factor_x elseif (ship[0].start_x < ship[0].target_x) and (ship[0].x < ship[0].target_x) then ship[0].x = ship[0].x + (dt / ship[0].speed) * ship[0].factor_x endend if ship[0].y ~= ship[0].target_y then if (ship[0].start_y > ship[0].target_y) and (ship[0].y > ship[0].target_y) then ship[0].y = ship[0].y - (dt / ship[0].speed) * ship[0].factor_y elseif (ship[0].start_y < ship[0].target_y) and (ship[0].y < ship[0].target_y) then ship[0].y = ship[0].y + (dt / ship[0].speed) * ship[0].factor_y endend
Point Start
Point Target
Number Speed
Find:
Vector Velocity
Number Distance
Velocity.x = Target.x - Start.x
Velocity.y = Target.y - Start.y
Distance = Velocity.Length() //cache distance before normalizing
Velocity.Normalize()
Velocity *= Speed //Scalar multiply
In your update:
Pos.x += Velocity.x * deltaTime
Pos.y += Velocity.y * deltaTime
TrackDistance += Velocity.Length() * deltaTime
//Check if we reached or passed our target
if( TrackDistance >= Distance )
{
Pos = Target
Velocity.Zero()
TrackDistance = 0
}
The deltaTime is needed if you aren't running on a frame based or fixed time step system. (Edit: I see you are already using a dt system, so this note is just repeating the obvious :)