Make Bullets fly in Mouse direction

im still learning to code lua, thats why im doing the war battles tutorial.

But i want to modify the war battles mechanics, so that the bullets would face the mouse and fly in its direction.

So i want to know, is it possible to get the angle the mouse is in as a variable, to replace this part:

if self.firing then
	local angle = math.atan2(self.dir.y, self.dir.x)
	local rot = vmath.quat_rotation_z(angle)
	local props = { dir = self.dir }
	factory.create("#rocketfactory", nil, rot, props)

and if it is possible to do that, please reply

thank you :slight_smile:

1 Like

Hi. Yes, it’s possible, but it’s not a one line solution.

First you need to setup input listening with 'acquire_input_focus' if not already. Usually you need hash('touch') as the action_id.
Then you can get screen coordinates with action.screen_x and action.screen_y (or scaled values action.x and action.y).
These value you have to convert from screen space (0 to screen width/height) to game space (your game object coordinates).
Once that’s done you can get mouse direction with something like

local rocket_launcher_position = go.get_position('/rocket_launcher')
rocket_launcher_position.z = 0
local dir = vmath.normalize(rocket_launcher_position - vmath.vector3(mouse_x, mouse_y, 0))

I am not familiar with the war battle tutorial, so you have adopt these steps to your project.

This was also discussed here as well: Make a bullet move in faced direction