Topic was automatically imported from the old Question2Answer platform.
Asked By
Movit
I use two spawn positions for the appearance of enemies (left and right) when the enemy appears on the right, everything is fine, but when the enemy spawns on the left, it goes backwards, so you need to flip it on the x axis. how do I do this?
Spawner:
extends Node2D
var Skelet = preload("res://Skelet.tscn")
func _on_SpawnTimer_timeout():
var enemy = Skelet.instance()
add_child(enemy)
enemy.position = $Spawn.position
var nodes = get_tree().get_nodes_in_group("spawn")
var node = nodes[randi() % nodes.size()]
var position = node.position
$Spawn.position = position
var velocity = Vector2()
var dead = false
var health = 5
onready var player = get_node("/root/Main/Player")
func _physics_process(delta):
if dead == true:
$CollisionShape2D.disabled = true
return
if player:
var direction = (player.position - position).normalized()
move_and_slide(direction * SPEED)
$AnimatedSprite.play("walk")
Hello,
I’m assuming from your code that your problem is that the monsters always go in the right direction (towards the player) but some appear to be moonwalking. AnimatedSprite has a flag you can toggle to flip horizontally the sprite: AnimatedSprite.flip_h.
Yes, that’s my problem, but I don’t understand how I can use AnimatedSprite.flip_h when spawning an enemy on the left, could you help me with the code?
Movit | 2021-07-21 18:58
Well you can deduce wether your creatures are moving to the left or to the right by looking at the sign of their horizontal movement: velocity.x < 0 means that they are moving to the left, velocity.x > 0 is when they move to the right.
You can therefore do:
var moving_to_right := (velocity.x < 0)
$AnimatedSprite.flip_h = moving_to_right
This will litterally flip the sprite when the enemy comes from the left (and moves to the right).
Lola | 2021-07-21 20:53
When I adding var moving_to_right := (velocity.x < 0) an error appears in the console:
“The assigned value doesnt have a set type; the variable type cant be inferred”
I’m sorry for such stupid questions
Movit | 2021-07-22 06:48
There are no stupid questions!
You can remove the : in :=.
This is a GDScript feature that allows you to “lock” the type of a variable to help avoid errors. You can for example do var my_int: int to disallow setting something else than an int to a variable.
The := is a shorthand meaning “assign a value and lock the type to the type of the value”. But since velocity has no locked type, godot can’t deduce a type for moving_to_right: its type can’t be inferred.
Lola | 2021-07-22 07:10
I managed to turn them over! there is no more moonwalk XD