I’m currently working on a side-scrolling platforming game using 3D models, somewhat similar to Little Big Planet.
Right now, I’m trying to make it so the player is able to hold a weapon and aim it by pointing the mouse cursor in the general direction he wishes to shoot in.
(Similar to what is shown in this 2D tutorial here: https://youtu.be/chIFtkuFnVw)
Since the player will only be able to move up/down and left/right, the idea is that the weapon should only be able to independently rotate around one axis, and not move in any other way.
And while this was simple enough in 2D using the look_at() function, I haven’t found any instructions online as to how I could implement this in 3D that worked for me.
(And LLMs appear to not have much information on how Godot works.)
Following the guides I found, which generally involved raycasting, the weapon would point in all sorts of directions, but I couldn’t get it to follow the mouse in any way (even without locking any axis).
I would be grateful if anyone could suggest a solution, which a 3D newbie like me can understand
How to properly calculate this is exactly my problem.
For example, this code…
var mouse_position: Vector2 = (get_viewport().get_mouse_position())
var target_position = camera.project_position(mouse_position, 10)
var target_position_vector = Vector3(target_position.x,target_position.y,target_position.y)
if target_position != null:
blaster.look_at(target_position_vector)
…does this…
…while this code…
var mouse_position: Vector2 = (get_viewport().get_mouse_position())
var ray_start: Vector3 = camera.project_ray_origin(mouse_position)
var ray_direction: Vector3 = camera.project_ray_normal(mouse_position)
var plane = Plane(Vector3(0,1,0))
var ray_intersect = plane.intersects_ray(ray_start, ray_direction)
if ray_intersect:
blaster.look_at(Vector3(ray_intersect.x, ray_intersect.y, ray_intersect.z))
Your second code should work. You just need to construct the proper plane. The plane normal should be the global axis you want gun to rotate around, and plane origin should be at global position of gun’s rotation pivot. Currently the plane you’re constructing is the ground plane.