Can't get movement math right

I wish you guys had a discord or something, hate to take up space with what’s probably such a simple question

New to Defold, so I’m sure there’s some rule that I’m not aware of causing this (or my math is just wrong). I’m trying to move the player towards wherever I click.

In main.script I have this:

	if(action_id == hash("touch")) then
		msg.post("/player#player", "move", {vmath.vector3(action.x, action.y, 0)})
	end

and in the player.script I have this

function on_message(self, message_id, message, sender)
if message_id == hash(“move”) then
print(“move received”)
pos = go.get_position()
moveto = vmath.normalize(message[1] - pos)
go.set_position(pos + moveto)
end
end

But when I click on the screen, the player only moves up and to the right- if I click different places he’ll move more to the right than up but always only northeast. What am I doing wrong?

Defold community has Discord, Slack and Telegram.

I would guess is that your player is sitting inside some other game object, centered on the screen.
go.get_position() returns local position, for global position you need to call go.get_world_position().

Alternatively you can convert mouse coordinates into your player coordinate system, e.g. subtract half width and half height of the screen.

3 Likes

go.get_world_position() is the function you need.

4 Likes

There is a Discord, though it’s not official: https://discord.gg/cHBde7J

Sweet, thanks for the discord, for some reason I did not find it when I searched, I must have searched poorly

go.get_world-position() didn’t seem to change anything, I suppose I need to figure out the position of the click relative to the game object itself? Still figuring out how cameras work but I intend to go that direction.

action.x and action.y are in GUI coordinates, they often won’t match up with world coordinates. You’ll need to convert them by offsetting them by the camera position and half the screen if it is centered, and scaling by the camera zoom. You can try printing action.x and action.y to see what you get.

Actually, it may be easier to work with action.screen_x, action.screen_y since they do not stretch and squash when the window changes.

4 Likes

And there is https://defold.com/slack/

1 Like