There is a code of Flashlight with Battery in Godot 3D that turns ON when you press Left Mouse Button, but turns OFF the moment you release the button.
How do I make it turn OFF, ONLY after pressing the Left Mouse Button again?
extends Node3D
func _input(event: InputEvent) -> void:
if Input.is_action_pressed("Toggle") and $Battery.value > 0:
$SpotLight3D.light_energy = 16
else:
$SpotLight3D.light_energy = 0
func _physics_process(delta: float) -> void:
if $SpotLight3D.light_energy == 16:
$Battery.value -= 0.05
A lot easier if you introduce a state variable, eg light_on and toggle that in the input event. (Changed to the newer is_action_just_pressed). Then toggle the light in input handler for the button, using seperate functions so we can reuse them if the battery is empty.
extends Note3D
var light_on = false
func set_light_on() -> void:
$SpotLight3D.light_energy = 16
func set_ligt_off() -> void:
$SpotLight3D.light_energy = 0
func _input(event: InputEvent) -> void:
if Input.is_action_just_pressed("Toggle"):
light_on = !light_on
if light_on:
set_light_on()
else:
set_light_off()
func _physics_process(delta: float) -> void:
if light_on:
$Battery.value -= 0.05
if $Batter.value <= 0:
light_on = false
set_light_off()