I am currently creating my first godot project, a snake clone and just don't understand why this isn't working as it is supposed to. I try to change the texture of my snake sprite in code with sprite.set_texture(). Changing the texture with sprite.set_texture(sprite.texture2) does work while sprite.set_texture(sprite.texture) doesn't work. I don't get any error, the texture just doesn't change. texture is the default texture of the sprite and texture2 is also a Texture2D and added with @export. This is my code:
extends CharacterBody2D
@onready var sprite = $Sprite
const MOVESPEED = 200
func _ready():
sprite.global_position = Vector2(get_viewport().size / 2)
velocity = MOVESPEED * Vector2.RIGHT
func _process(_delta):
var current_direction = Vector2(velocity.x, velocity.y).normalized()
current_direction = get_movement_direction(current_direction)
if current_direction != Vector2.ZERO:
velocity = current_direction * MOVESPEED
move_and_slide()
func get_movement_direction(current_direction):
var x_movement = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
var y_movement = Input.get_action_strength("move_down") - Input.get_action_strength("move_up")
if x_movement != 0:
if x_movement == 1:
current_direction = Vector2.RIGHT
sprite.set_texture(sprite.texture)
sprite.flip_h = false
else:
current_direction = Vector2.LEFT
sprite.set_texture(sprite.texture)
sprite.flip_h = true
elif y_movement != 0:
if y_movement == 1:
current_direction = Vector2.DOWN
sprite.set_texture(sprite.texture2)
sprite.flip_v = true
else:
current_direction = Vector2.UP
sprite.set_texture(sprite.texture2)
sprite.flip_v = false
return current_direction
I already verified that both textures do exist. I really have no clue what else I can check.
Here is the mistake:
texture is the default texture
No, it isn't.
The texture
property is not the default texture. The texture
property is the current texture.
In fact, when you do:
sprite.set_texture(sprite.texture)
It is the same as doing:
sprite.texture = sprite.texture
Which I hope is clear enough to understand why it does nothing.