I haven't done a 3rd person shooter myself, not directly at any rate, but looking at the Unreal blueprint and using what I have learned from other projects, I think I have a rough idea on how to go about it. I have no idea if it will work, nor have I tested any of the code, but here is how I would program it:
When you need to fire, send a raycast from the camera to the cursor location. This is needed so you can get the position in 3D space to aim the bullet at. Something like this should be able to get bullet location:
const RAY_LENGTH = 100
var raycast_position = null
func _physics_process(delta):
# Note: this assumes you are using a action for the mouse.
# you might need to replace this with a different method to detect
# whether the mouse has been clicked.
if (Input.is_action_just_pressed("mouse_click")):
var mouse_position = get_tree.root.get_mouse_position()
var raycast_from = level_camera.project_ray_origin(mouse_position)
var raycast_to = level_camera.project_ray_normal(mouse_position)
# You might need a collision mask to avoid objects like the player...
var space_state = get_world().direct_space_state
var raycast_result = space_state.intersect_ray(raycast_from, raycast_to)
if (result):
# store the location.
raycast_position = result["position"]
Using the raycast position, the next step is to rotate the bullet so that it is pointed towards the raycast position. There are several ways to do this, but the easiest is probably to use the looking_at
function in Transfom. For example:
if (raycast_position != null):
# Assuming the bullet has been instanced already
# and is stored in a variable called 'clone'
# Note: for this to work, the bullet's position has to
# already have been set, otherwise the rotation
# will not be pointing to the correct spot.
clone.global_transform = clone.global_transform.looking_at(raycast_position, Vector3.UP)
This will rotate the bullet so it's negative Z axis is pointing at the target, which means the bullet scene will need to be facing the negative Z axis for the visuals to look correct.
Then in the bullet script, all that is left is to move the scene along the negative Z axis. I think the translate_object_local
function will move the object relative to it's rotation, though it has been awhile since I've used it:
func _physics_process(delta):
var bullet_speed = int(100)
translate_object_local(Vector3(0, 0, -bullet_speed))
Then the bullet should move towards whatever object is under the cursor.
I have not tested any of the code, but I think that should work, assuming I understand the situation and the code I wrote works correctly.
Hopefully this helps!
(Side note: I edited your post a bit so the code is formatted within your post)