Page 2 of 2

Re: Moving an object perfectly at an angle

Posted: Sun Nov 23, 2008 11:47 pm
by surtic
This code seems to work:

Code: Select all

function load()
   angle = 67
   x = 100
   y = 500
   speed = 20
end

function update(dt)
   x = x + math.cos(math.rad(angle)) * dt * speed
   y = y - math.sin(math.rad(angle)) * dt * speed
end

function draw()
   love.graphics.rectangle(love.draw_fill, x, y, 10, 10)
end
If you use atan2(dy,dx) then you are measuring the angle anti-clockwise from the right (3 o'clock). In that case you need cosine to calculate the x direction, but -sin to calculate the y direction (because the y of the cartesian coordinate system and y of the display are inverted).

Of course, if you fiddle with cos and sin long enough, you get what you need (because cos(x) = sin(x+pi/2), cos(x)=cos(-x), sin(x)=-sin(-x) etc.)