How do I make a toggle button to move my player?

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

I want to have a toggle button that when toggled on, the player starts to move right, and when toggled off, the player stops moving. I put a signal on a check button node and connected it to my player kinematicbody2D. This is the code inside it:

var velocity = Vector2()
var speed = 300
const FLOOR = Vector2(0, -1)

func _on_CheckButton_toggled(button_pressed):
velocity.x = speed
velocity.x = 0
velocity = move_and_slide(velocity, FLOOR)

When I go into the game and toggle the button to on, the player moves once and stops moving. I don’t know what’s causing this to happen. I’m a beginner and I’m probably not noticing something I should.

:bust_in_silhouette: Reply From: exuin

The reason the player only moves once is because the on_CheckButton_toggled function only executes once when the the button is toggled. Instead, what you should do is store whether the player is moving in a variable, like is_moving. Assign false to it on initialization (unless you want the character to start off moving), and when the the CheckButton is pressed, change the variable’s value button_pressed. Then, in the _physics_process function, put your movement code.

Okay, that makes sense. Thanks for the info!

BoiTrek | 2020-10-03 01:48