Moving an object perfectly at an angle

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
surtic
Citizen
Posts: 74
Joined: Sat Jul 12, 2008 12:18 am

Re: Moving an object perfectly at an angle

Post 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.)
Post Reply

Who is online

Users browsing this forum: Bing [Bot], zingo and 7 guests