Rotating an image to face another point?

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.
Post Reply
f4ux
Prole
Posts: 2
Joined: Mon Jan 11, 2016 10:53 pm

Rotating an image to face another point?

Post 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
User avatar
pgimeno
Party member
Posts: 3593
Joined: Sun Oct 18, 2015 2:58 pm

Re: Rotating an image to face another point?

Post 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.
f4ux
Prole
Posts: 2
Joined: Mon Jan 11, 2016 10:53 pm

Re: Rotating an image to face another point?

Post by f4ux »

awesome, thanks. i'm glad you could explain how it works, this will be useful for other things aswell.
Post Reply

Who is online

Users browsing this forum: No registered users and 3 guests