Trying to fire projectile in mouse direction

Hi, sorry for yet another post. I am new to defold and I don’t have a lot of time to complete my project haha.

I have done some tinkering, and have made a projectile system, and am currently trying to make it fire towards the player’s mouse position. It fires the projectile, but it doesn’t fire it to the mouse position, and it does this weird thing where the direction of motion changes when the player walks around.

Here is the code

function init(self)
	-- make sure the script will receive user input
	msg.post(".", "acquire_input_focus")
end

function on_input(self, action_id, action)
	if action_id == hash("attack") and action.pressed then
		local pos = go.get_position()
		local mouse_pos = vmath.vector3(action.x, action.y, 0)

		local direction = vmath.normalize(mouse_pos - pos)
		local distance = 350
		local to = pos + direction * distance

		local bullet_id = factory.create("#pizzafactory", pos)
		go.set(bullet_id, "position", pos)
		go.animate(bullet_id, "position", go.PLAYBACK_ONCE_FORWARD, to, go.EASING_LINEAR, distance / 350, 0, function()
			go.delete(bullet_id)
		end)
	end
end

Could it be something to do with the (mouse_pos-pos) line?? Or is it an external error, with gameobject placements etc?

I do not immediately see the problem. I suggest that you print these values and check that they make sense. I suppose the script you shared is added to the player that is moving around?

image

When standing in the top right of my map, and having my mouse in the top right corner of my screen, this is what the output shows.

I managed to tinker with the code (though, I do not have access to it right now, it is on a separate computer) and utilise rendercam, and rendercam.screen_to_world_2d.

It works, it fires the projectile to the mouse position! However, I am going to take a look at the references and documentation of rendercam and see if I can manage to make it fire in the direction of the mouse, and not the position.

Thank you for helping me!!

1 Like