Page 1 of 1

Rotating an image to face another point?

Posted: Mon Jan 11, 2016 10:59 pm
by f4ux
Hi, I'm kind of new to love, and I was curious to see how I can rotate an image to make it point to a certain point. (The mouse cursor position.)


function love.draw(dt)
love.graphics.draw(player.img, player.x, player.y, player.r) --player is a table value storing the information of the player
end

all i'd like to do is set player.r to make it face towards love.mouse:getX() and love.mouse:getY()

I may not sound like I know when I'm saying since i just started love.

Thanks

Re: Rotating an image to face another point?

Posted: Tue Jan 12, 2016 12:18 am
by pgimeno
Generic images don't point anywhere. You probably want to point the top, the bottom, the left, or the right of the image towards a point.

The function to obtain the angle of a 2D vector is math.atan2. It requires two arguments and (for historical reasons) they are required in reverse order: y and x of the vector. To obtain a vector from an origin and a destination point, you subtract their coordinates.

So, assuming you want to rotate your image around its origin (top left), you would use something like:

Code: Select all

local mouseX, mouseY = love.mouse.getPosition()
player.r = math.atan2(mouseY - player.y, mouseX - player.x) + offset
where offset is 0 if you want to point the right side of the image, math.pi/2 if the top, math.pi if the left side, and math.pi/-2 if the bottom.

Re: Rotating an image to face another point?

Posted: Tue Jan 12, 2016 1:24 am
by f4ux
awesome, thanks. i'm glad you could explain how it works, this will be useful for other things aswell.