How can I access a Camera3D node as a variable in my code

4.2.2 Godot Version

Question

I am not sure how to access the Camera3D node as a variable so that I can use rays to get the mouse position while I have the game running. In the debug menu I can see all of the variables that rely on the node are null instances. I am not sure where my mistake is.

Here is the code I am using.

extends Node3D

#Player Variables
@onready var player = preload(“res://Scenes/player.tscn”)

var money := 100.00
@onready var camera3d := $Camera3D

#Building Variables
var building
var in_construct_mode : bool = false

#Building Objects
const FLOOR_TILE = preload(“res://Scenes/Building Items/floor_tile.tscn”)
const FloorTilePlacement = preload(“res://Scripts/floorTilePlacement.gd”)

func ScreenPointToRay():

var mousePos = get_viewport().get_mouse_position()
var camera = camera3d
var raylength = 2000
var rayOrigin = camera.project_ray_orgin(mousePos) 
var rayEnd = rayOrigin + camera.project_ray_normal(mousePos) * raylength
var space = get_world_3d().direct_space_state
var rayQuery = PhysicsRayQueryParameters3D.create(rayOrigin, rayEnd)
rayQuery.collide_with_areas = true
rayQuery.to=rayEnd

var result = space.intersect_ray(rayQuery)

return result.position

func _unhandled_input(event):
if event.is_action_pressed(“buildmode”):
print(“building 1 selected”)
building = FLOOR_TILE.instantiate()
get_tree().root.add_child(building)
in_construct_mode = true

func _process(delta):
if in_construct_mode:
var mouse_position : Vector3 = ScreenPointToRay()
building.transform.origin = mouse_position
if Input.is_action_just_pressed(“buildmode”):
in_construct_mode = false

You can reference the current Camera3D by simply calling get_viewport().get_camera_3d().

1 Like
  • What’s the scene tree like?
    • The $Camera3D maybe couldn’t be found. It means find a node named Camera3D as the child of current node.
  • Is the Camera3D node changed by code?
    • When it is not exists in _ready calling, it will be assigned to null.
1 Like

Thank you both so much! You both helped solve the problem. I have been trying to fix this issue for 2 weeks. I needed to clean up my scene tree and I switched to using get_viewport().get_camera_3d() and it worked perfectly any place I needed to access my camera.

1 Like