How to point an image toward the cursor?

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
Ethan-Taylor
Prole
Posts: 34
Joined: Mon Nov 24, 2014 9:15 pm

How to point an image toward the cursor?

Post by Ethan-Taylor »

So do I measure the angle based on x and y of my sprite (image) and the x and y of the cursor?
Also I would like it so when you press the up key the character goes toward the mouse cursor.

Also with all the keys too, so if you're pointing 90d the "A" key would make you go down.

Thanks.
User avatar
micha
Inner party member
Posts: 1083
Joined: Wed Sep 26, 2012 5:13 pm

Re: How to point an image toward the cursor?

Post by micha »

You can calculate the angle like this:

Code: Select all

local dx = mouseX-playerX
local dy = mouseY-playerY
local angle = math.atan2(dy,dx)
This angle can then be used in the draw-call to rotate the image.

To make the movement towards the mouse, you need some trigonometry (put the calculation of the angle before this code):

Code: Select all

if love.keyboard.isDown('w') then
  playerX = playerX + velocity * dt * math.cos(angle)
  playerY = playerY + velocity * dt * math.sin(angle)
end
Post Reply

Who is online

Users browsing this forum: No registered users and 75 guests