You can use ai like Gemini , Claude , ChatGPT for problems like this it can help u learn and find the mistakes u did easily
BUT DONE USE IT TO DO EVERYTIHNG FOR U K?
The error is happening because the type of sprite changes during your code.
At the beginning:
var sprite = 0
So sprite is an int.
Later you do:
sprite = load("res://assets/playerright.png")
Now sprite is a Texture2D object.
Then on the next frame you compare:
sprite == 0
You’re comparing a Texture2D with an int, which gives:
Invalid operands ‘int’ and ‘Object’ in operator ‘==’
Another problem
Even if the error didn’t happen, this logic wouldn’t work.
When you first move right:
sprite = load("playerright.png")
Now sprite is no longer 0.
So these conditions will never be true again:
if velocity.x > 1 and sprite == 0:
if velocity.x < -1 and sprite == 0:
if velocity.y > 1 and sprite == 0:
if velocity.y < -1 and sprite == 0:
because sprite is now a texture, not 0.
What you probably wanted
You don’t actually need sprite == 0.
Just change the texture whenever the player moves in a direction.
func turn():
if velocity.x > 1:
$Sprite2D.texture = load("res://assets/playerright.png")
elif velocity.x < -1:
$Sprite2D.texture = load("res://assets/playerleft.png")
elif velocity.y > 1:
$Sprite2D.texture = load("res://assets/playerdown.png")
elif velocity.y < -1:
$Sprite2D.texture = load("res://assets/playerup.png")
Notice the elifs. Only one direction is chosen each frame.
If the player stops moving, nothing happens, so the last direction stays visible automatically.
If your goal is diagonal movement
You said:
keep the last sprite if the player walks diagonally
For example:
- Move right → face right.
- Hold Up while still holding Right → continue facing right.
- Release Right and keep holding Up → now face up.
You can do that by giving horizontal movement priority:
func turn():
if velocity.x > 1:
$Sprite2D.texture = right_texture
elif velocity.x < -1:
$Sprite2D.texture = left_texture
elif velocity.y > 1:
$Sprite2D.texture = down_texture
elif velocity.y < -1:
$Sprite2D.texture = up_texture
Or give vertical movement priority by checking velocity.y first.
One more improvement
You’re calling load() every frame, which is inefficient. Load the textures once:
@onready var right_texture = preload("res://assets/playerright.png")
@onready var left_texture = preload("res://assets/playerleft.png")
@onready var up_texture = preload("res://assets/playerup.png")
@onready var down_texture = preload("res://assets/playerdown.png")
Then just assign them:
$Sprite2D.texture = right_texture
This is much faster because the images are loaded only once.