Error when trying to get player position for camera to follow

Godot Version

4.2.2

Question

Hello,
i want the camera to follow the player in a top-down-view style without being a child of the player node, because i don’t want the camera to inherit the player-rotation - only the x/y/z position of the player with an added offset. So i added a script to my camera:

extends Camera3D

@onready var player = %Player

@export var posY: float = 10.0
@export var posZ: float = 10.0
@export var rotX: float = -45.0

var playerPos: Vector3 = player.position
var camPos: Vector3 = playerPos + Vector3(0,posY,posZ)

func _ready():
	pass

func _process(_delta):
	position = camPos
	rotation.x = rotX

but i get the error: “Invalid get index ‘position’ (on base: ‘Nil’)”.

here a screenshot:

I’m new to Godot and GameDev. It would be awesome if someone could help me, or suggest a better solution to this , thank you :slight_smile:

change to

@onready var player = $"../Player"

if above changes still can’t
then do this:

extends Camera3D

@onready var player =  $"../Player"

@export var posY: float = 10.0
@export var posZ: float = 10.0
@export var rotX: float = -45.0

var playerPos: Vector3
var camPos: Vector3 

func _ready():
	await get_tree().physics_frame
	playerPos = player.position
	camPos = playerPos + Vector3(0,posY,posZ)

func _process(_delta):
	position = camPos
	rotation.x = rotX

also by the way, since you put the camera node in the scene directly on editor, you can use

@export var player:CharacterBody3D

instead of
@onready var player = %Player
then after you save the script, go to inspector dock of camera3d and assign it either from drag and drop from scene tree to player property in inspector dock, or assign it from player property in inspector dock

1 Like

Hey,
thank you very much for your reply.

With a few changes to your suggestion it’s finally working now :slight_smile:

extends Camera3D

@onready var player = %Player

@export var posY: float = 10.0
@export var posZ: float = 10.0
@export var rotX: float = -45.0

var playerPos: Vector3
var camPos: Vector3

func _ready():
	pass

func _process(_delta):
	playerPos = player.position
	camPos = playerPos + Vector3(0,posY,posZ)
	position = camPos
	rotation.x = rotX

Seems like the splitting of the variable declaration and the adding of the variable values (moving the latter into the ‘’_process()‘’ function) has been the key to success.

:+1:

I would change it to a @export var player: CharacterBody3D instead. Unique names aren’t supposed to be used by siblings. You will run into more errors down the line with your current setup.

1 Like

Allright,

thank you (and zdrmlpzdrmlp) for pointing that out. I’m gonna change it to @export var player: CharacterBody3D

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.