how to change the speed of the player via script?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By 20xxdd20

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.

:bust_in_silhouette: Reply From: Wakatta

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

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.

20xxdd20 | 2021-08-03 15:11

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()

Wakatta | 2021-08-03 15:23

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).

20xxdd20 | 2021-08-03 16:35

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()

Wakatta | 2021-08-07 07:33