How can you get an object to point to the mouse pointer?

I’m new to defold and I’m trying to make an object point towards the mouse pointer.

Getting just the mouse coordinates would be very helpful too.

Hi @stainedmentor, and welcome!

I think the first step is to read our manual about input.
Pay special attention to the parts about Acquiring Input Focus, the on_input message handler and Mouse Triggers.

Those should be a good first step to your first input handling.

As for making an object rotate towards the mouse pointer, here is a good solution and demo by @britzl.

2 Likes

Another demo and some code for the same thing:


http://britzl.github.io/publicexamples/rotate_and_move/index.html

1 Like

Ehmm, i saw this topic just and i dont really understand, i also need this code to my “plattformer” to get a go called gun to point towards the mouse

What exactly do you not understand?

I may just not have understand the answers by @Mathias_Westerdahl and @britzl or i am just bad at this. But, i dont understand Git-Hub

Hi man, I started a game recently and first thing I implemented is something like this. It’s still raw, but I guess it can be of help.

First in on_input function, create a vector from your character to the mouse. If you have a camera, you need to convert the characters position to screen first.

function on_input(self, action_id, action)

local pos = go.get_position()

pos = camera.world_to_screen(hash("/camera"), pos) -- convert position to screen
local mouse_vec = vmath.vector3(action.x - pos.x, action.y - pos.y, 0)

self.mouse_vec = mouse_vec

If you don’t have a camera, just use the position as go.get_position.
Once you have the vector from the player to the mouse, lets say your weapon object is child of your player. Update its position/rotation in your player’s update method like so:

    -- update weapon position & rotation depending on mouse
if self.mouse_vec.y > 0 then
	pos.z = 0.01 -- behind player
else 
	pos.z = 1 -- in front of player
end
local angle = math.atan2(self.mouse_vec.y, self.mouse_vec.x)
local rot = vmath.quat_rotation_z(angle)

if self.weapon then
	sprite.set_vflip(self.weapon, rot.z > 0.65 or (rot.z < -0.5 and rot.z > -1)) -- flip if rotation reaches limit
	go.set_position(pos, self.weapon)	
	go.set_rotation(rot, self.weapon)
end
-- end weapon pos & rot

Those vals are for a gun sprite pointing right. You should tweak the amounts, but I guess you can get a hang of what is going on by looking at the code.

The “pos” var has the players position. The vflip is for when the gun reaches a certain point that it has to be turned over for it to look natural. Hope it helps

1 Like

The relevant snippet of code:

local look_at = vmath.vector3(123, 456, 0) -- the position to look at
local my_position = go.get_position()
local angle = math.atan2(look_at.x - my_position.x, look_at.y - my_position.y)
go.set_rotation(vmath.quat_rotation_z(angle))
4 Likes