How do I call a function that runs continuously if the player enters an Area?

Godot Version

4.3 stable

Question

Hello everyone, I am new to programming and Godot but I understand some of the basics. My goal is for the player (I’m using the included Godot icon) to start spinning continuously as it touches the Goal, which is an Area2D.

The following is what I came up with but is not working:
NOTE: This script is attached to the player.

class_name Player
extends CharacterBody2D

@onready var player: Player = %Player
@onready var goal: Area2D = $"../Goal"

var max_speed := 600.00


func _physics_process(_delta: float) -> void:
	var direction := Input.get_vector("move_left", "move_right", "move_up", "move_down")
	velocity = direction * max_speed
	move_and_slide()
	
	goal.body_entered.connect(func (body: Node) -> void:
		if body is not Player:
			return
		var player := body as Player
		player.rotate(.1)

The condition is running inside the _physics_process ( ) function, I don’t understand why the player doesn’t start rotating.

If you decide to reply, I will really appreciate if you could explain in details and perhaps give a simple example writing some GD Script lines, since I’m a visual learner.

Here’s a screenshot of my code:

Btw, the player in the scene tree has no collision shape, I added the collision shape but it’s still not working. Once the player touches the goal (Area2D) it will instantly rotate to a random angle but it won’t rotate continuously which is my goal.

You are connecting a new function every frame, but body_entered only fires once per entry. You could set a variable on the the player to enable rotation. The player will need a collision shape to trigger the area2d

var spinning: bool = false

func _ready() -> void:
	# or connect through the editor, or better yet connect on the Area2D
	goal.body_entered.connect(func(body: Node2D) -> void:
		if body is Player:
			body.spinning = true

func _physics_process(_delta: float) -> void:
	var direction := Input.get_vector("move_left", "move_right", "move_up", "move_down")
	velocity = direction * max_speed
	move_and_slide()

	if spinning:
		self.rotate(.1)
1 Like

@gertkeno I did not expected such a fast reply so thank you very much. Your solution works, I then added a signal for when the player exits the area so that it would stop spinning.

I’m still working on understanding the logic in GD Script so thanks again for your help! :slightly_smiling_face: