How to go about saving a reference to an object as a variable?

On Godot 4.2.1

I need to save a reference to the last object a raycast collided with as variable so that I may call a function from it even after the raycast is no longer colliding.

-Player

var collider = ray.get_collider()
	
	if ray.is_colliding() and collider.is_in_group("block"):
		ray.force_raycast_update()
		collider._move(direction)
	
	#print("player_direction:", direction)
	move_and_slide()

-Block

func _move(direction):
	if direction != 0:
		velocity.x = direction * 100
	else:
		velocity.x = move_toward(velocity.x, 0, 100)
	print("block_direction:", direction)

Without a reference I cannot update the blocks velocity after player raycast has stopped colliding, and so the block maintains its last applied velocity and simply continues to slide along the ground even after the player has stopped touching it.

I am still very much a novice and am unsure exactly how to approach this. Any and all help is appreciated.

class_name Block
extends CharactorBody2D

func _physics_process(delta: float) -> void:
    move_and_slide()
    velocity = Vector2.ZERO

func _move(direction):
    if direction != 0:
	velocity.x = direction * 100
    else:
	velocity.x = move_toward(velocity.x, 0, 100)
1 Like

I may be missing some context (it would be useful if you could post your complete script code), but it seems like you could do something like this:

# player script

var block = null

func _physics_process(delta):
	var collider = ray.get_collider()
	
	if ray.is_colliding() and collider.is_in_group("block"):
		# currently colliding
		block = collider
		block._move(direction)
	else:
		# no longer colliding
		if block:
			block._move(0)
	
	move_and_slide()

As an aside, if you’re going to be calling _move from other scripts, you typically wouldn’t put the leading _ since that typically means “don’t call this from other scripts”. Also, I would avoid using move_toward anywhere except in a _physics_process function, since if you ever stop calling _move, the velocity could get stuck.

1 Like

Thank you so much, your fix worked like a charm. I was never aware of _ being used as a prefix to indicate that a function should’t be called from another script, thank you for filling me in!

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