Hello,
I am trying to figure out how to stop a sprite from being able to rotate (I’m using the _input(event) method to rotate it) once it reaches a certain rotation_degree value.
The thing is, I can’t even get it to print something once it reaches that rotation_degree, but there’s no error code so I don’t know what’s wrong…
my code:
extends StaticBody2D
# When pressing the following buttons: Q / E / , / . --> Rotate self - Works!
# if the rotation matches a certain value, stop being able to rotate - doesn't work
var correctRot : float = 180.0
@onready var spriteNode = get_node("Sprite2D")
func checkIfCorrectRot():
if spriteNode.rotation_degrees == correctRot:
#stop being able to rotate
print("Stop being able to rotate somehow...") #doesn't work either...
func _input(event: InputEvent) -> void: #*
if Input.is_action_just_pressed("Rotate_Left"):
self.rotation_degrees -= 90
checkIfCorrectRot()
elif Input.is_action_just_pressed("Rotate_Right"):
self.rotation_degrees += 90
checkIfCorrectRot()
First, you’re using == to compare two float values (the node rotation degrees and you desired value) that’s not recommended due to the floating point issue.
Second, rotation_degrees in a node will not loop into 0 ~ 360, the value can go in to more than 360 or can be less than 0, so if you start the rotation to the left, the value will go to below than zero (-90, -180, etc).
Third and more important, you rotate the node that contains the script but in your checkIfCorrectRot you look for the other node rotation, so will never reach the desired result.
To solve these issues you can do:
extends StaticBody2D
# When pressing the following buttons: Q / E / , / . --> Rotate self - Works!
# if the rotation matches a certain value, stop being able to rotate - doesn't work
# Don't use floats unless you need the decimal
# value, use ints instead.
var correctRot := 180
# Create a variable to tell if the node can be or not rotated
var can_rotate := true
@onready var spriteNode = get_node("Sprite2D")
func checkIfCorrectRot() -> void:
# Convert the node rotation degrees to a int value to
# avoid float point issues
if int(spriteNode.rotation_degrees) == correctRot:
# Lock rotation
can_rotate = false
func _input(event: InputEvent) -> void:
# Check if can rotate, otherwise you don't need to
# check the input
if can_rotate:
if Input.is_action_just_pressed("Rotate_Left"):
# Use wrapi to keep the values between 0 ~ 360
# no matter the side you rotate, also
# rotate the correct node (very important)
spriteNode.rotation_degrees = wrapi(spriteNode.rotation_degrees - 90, 0, 360)
checkIfCorrectRot()
elif Input.is_action_just_pressed("Rotate_Right"):
spriteNode.rotation_degrees = wrapi(spriteNode.rotation_degrees + 90, 0, 360)
checkIfCorrectRot()