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