I am making a 3D top down view game that requires aiming with the mouse. It rotates at wierd angles. After adjusting the transforms, I managed to make the nodes in the $Rotate spatial node centered which made it look slightly better but not like the tutorial I was watching.
From my understanding, I needed to swap out '$Rotate.look_at(Vector3(pos.x, pos.y, pos.z), Vector3(0, 1, 0))' with '$Rotate.look_at(Vector3(pos.x, translation.y, pos.z), Vector3(0, 1, 0))' or '$Rotate.look_at(Vector3(pos.x, $Rotate.translation.y, pos.z), Vector3(0, 1, 0))'
And the code below still didn't work:
# Get current physics state
var space_state = get_world().direct_space_state
# Get current mouse position in the viewport
var mouse_position = get_viewport().get_mouse_position()
rayOrigin = Global.Camera.project_ray_origin(mouse_position) # Set the ray origin
rayEnd = rayOrigin + Global.Camera.project_ray_normal(mouse_position) * 2000 # Set the ray end point
var intersection = space_state.intersect_ray(rayOrigin, rayEnd) # Get the ray hit
if not intersection.empty(): # If there is a proper ray hit get its position and rotate towards it
var pos = intersection.position
$Rotate.look_at(Vector3(pos.x, pos.y, pos.z), Vector3(0, 1, 0))
I also had got this code below to work in the past and I am struggling to see why this doesn't work anymore and neither does the code above. I do not think the code below does anything much different. All it seems to do is rely on another node to get its rotation which now I realize may be over-convoluted compared to the code above which I was hoping would work.
# Create a horizontal plane, and find a point where the ray intersects with it
var player_pos = global_transform.origin
var dropPlane = Plane(Vector3(0, 1, 0), player_pos.y)
# Project a ray from camera, from where the mouse cursor is in 2D viewport
var ray_length = 1000
var mouse_pos = get_viewport().get_mouse_position()
var from = Global.Camera.project_ray_origin(mouse_pos)
var to = from + Global.Camera.project_ray_normal(mouse_pos) * ray_length
var cursor_pos = dropPlane.intersects_ray(from,to)
if cursor_pos != null:
# Rotate mesh to look at cursor
PointFromNode.look_at(cursor_pos, Vector3.DOWN)
var _mesh_pos = MeshInstanceNode.transform.origin
PointFromNode.transform.origin = Vector3(_mesh_pos.x, PointFromNode.transform.origin.y, _mesh_pos.z)
# Signal emitted when custom rotations are needed to be applied
# emit_signal("apply_rotation", self)
# Get mesh node to only rotate by y axis
MeshInstanceNode.rotation.y = PointFromNode.rotation.y
#var rotation = MeshInstanceNode.transform.basis
Best regards,
Oliver