This destroys my logic

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

I have only one print() function in my game

It prints

4

This is the code where the print function is:

var d = direction
if !d == 4:
    print(d)

The local variable var d is only used in this lines of code

The variable direction is a variable that changes sometimes, but it is always between 0 and 7.

HOW IS IT POSSIBLE THAT IT PRINTS 4 SOMETIMES IF IT ONLY PRINTS WHEN
IT ISNT 4

My head will explod soon ;). Please help me!

Here is the whole script, also when I am not thinking that you will need it. It is the only script:

extends KinematicBody2D

export (int) var speed = 300

var direction = 4
var velocity = Vector2()
var spritedirection = "U"

func get_input():
	velocity = Vector2(0,0)
	var right = Input.is_key_pressed(KEY_D)
	var left = Input.is_key_pressed(KEY_A)
	var up = Input.is_key_pressed(KEY_W)
	var down = Input.is_key_pressed(KEY_S)

	if left:
		velocity.x -= speed
	if right:
		velocity.x += speed
	if up:
		velocity.y -= speed
	if down:
		velocity.y += speed

func get_direction():
	if !velocity == Vector2(0,0):
		direction = rad2deg(velocity.angle()) / 45 + 3


func set_sprite():
	if velocity == Vector2(0,0):
		if $Animation.current_animation == "Laufen1":
			$Animation.play("Stehen1")
		if $Animation.current_animation == "Laufen3":
			$Animation.play("Stehen3")
		if $Animation.current_animation == "Laufen5":
			$Animation.play("Stehen5")
		if $Animation.current_animation == "Laufen7":
			$Animation.play("Stehen7")
	else:
		var d = direction
		if !d == 4:
			print(d)
			$Animation.play("Laufen"+str(d))

func _process(delta):
	get_input()
	get_direction()
	set_sprite()
	velocity = move_and_slide(velocity)

Crazy idea, but have you tried writing d != 4, instead of !d == 4?

alsvel | 2020-10-22 19:33

:bust_in_silhouette: Reply From: p7f

The problem is that direction is a float (as you didnt specify type), and the operation to calculate it may not result in an exact integer, because of rounding errors. So, as direction is always an int, you could either do this when declaring it:

var direction : int = 4

or when comparing:

var d = int(direction)
    if !d == 4:
    print(d)

You see 4 being printed in the console, because numbers like 4.000000001 or 3.999999999 will be printed as 4 because of rounding, but they are not equal. For example, you can test this:

var a = 4.000000001
var b = 3.999999999
var c = 4
print(a)
print(b)
print(a==c)
print(b==c)