I want to find the mouse coordinates during every frame of my game

So I’m trying to make a game where the player will face different directions (with different relevant sprites, not just pointing the same sprite at the mouse), and in order to do so I want to find my mouse coordinates. I checked out the mouse and touch imput example that defold has, and I have figured out how to read the mouse position, but its in a mouse script. I assume its connected to an object of some kind, what type of object would that be though.

Mouse position is passed to your on_input() function every time the mouse is moved. The engine passes this information through a nil action_id and a populated action table.

For example:

function on_input(self, action_id, action)
    if not action_id then // action_id == nil, so this is a mouse movement event
        print("Mouse x position = " .. action.x)
        print("Mouse y position = " .. action.y)
    end
end

Also see here: https://defold.com/manuals/input-mouse-and-touch/#mouse-movement

7 Likes

To expand on what was already said and answer the original question; you need to pass the mouse coordinates to the update function to have access to it every frame. You can either make it part of the “self” script or a local variable/table to the script, the former probably being the best practice.

example:


function init(self)  
    self.mouse = nil -- Declare it so you know it is part of the script, It will work without this though
end

function update(self, dt)
    if self.mouse then
        print("Mouse x position = " .. self.mouse.x)
        print("Mouse y position = " .. self.mouse.y)
    end
end

function on_input(self, action_id, action)
    if not action_id then -- action_id == nil, so this is a mouse movement event
        self.mouse = action
    end
end
2 Likes

Do you need access to it every frame? You only need access to it when it changes, which it does in on_input(). Why not rotate the player character there and possibly avoid code running every frame.

yeah that makes sense since you put it that way.

While I agree with your logic here, there are still reasons to pass the coords to the update function, such as using lerp on an animation or something along those lines. Depending on how the OP is animating his translations it could still be reasonable. But if they are a linearly changing sprites with no animation there is no need to bother the update function.

Absolutely. I’m just saying that one should be mindful of when you need an update function and when you don’t. You want to avoid code running every frame if you can.