0 votes

I have an Area node in which if the player touches it, it would change the speed of the player. But I don't know how to change the player's speed with a script.

extends KinematicBody

var speed = 35

I want to change the speed variable.

Godot version 3.3.2
in Engine by (55 points)

1 Answer

0 votes

Tip

It may be a good idea to have another variable for resetting purposes.

Answer

Connect the body_entered signal of the area to this code of the player node

extends KinematicBody

var speed = 35
var default_speed = 35

func _on_body_entered(body):
    if body == self:
        speed = 50 #set new speed

You can also do by connecting the body_exited signal

func _on_body_exited(body):
    if body == self:
        speed = default_speed #reset speed
by (4,480 points)

My player doesn't stay in the area but touches it and goes on, and I need the effect (speed) to go on for a set amount of time. I made this code:

extends Area

func _on_pickupspeed_body_entered(body):
    if body.name == "player":
        body.speed = 60

It changes the player of the speed but I don't know how to set it back to the default speed after like 20 seconds.

Use a Timer node and connect the timeout signal to

func _on_speed_timer_timeout():
    speed = 35

And in the area code start the timer

extends Area

func _on_pickupspeed_body_entered(body):
    if body.name == "player":
        body.speed = 60
        $speed_timer_node.start()

where to put

func _on_speed_timer_timeout():
    speed = 35

?
because if put into the area node, the code doesn't know where to change that variable. If put into the player script, the timer can't get to the player (the pickup has its own scene).

On the player would be most appropriate and you can set the timer node to a variable for example

var speed_timer = $Timer

Then in the area

extends Area

func _on_pickupspeed_body_entered(body):
    if body.name == "player":
        body.speed = 60
        body.speed_timer.start()
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.