Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | serveira |
I’m trying to move a simple animated sprite through the screen. It should play the “idle” animation whenever it has reached its target; and play the “run” animation when it’s moving.
The sprite should flip horizontally whenever the target’s x position is > or < than the current position of the idle sprite.
So far, I’ve written the following code, which moves the sprite to the mouse target, but doesn’t stop or flip the animation, it just plays endlessly.
extends KinematicBody2D
export (int) var speed = 100
var target = Vector2()
var vel = Vector2()
onready var sprite = get_node("AnimatedSprite")
var anim = "idle"
func _input(event):
#gets mouse position
if event.is_action_pressed('click'):
target = get_global_mouse_position()
func _fixed_process(delta):
#tries to flip the sprite to the direction clicked
if target.x == vel.x:
anim = "idle"
else:
anim = "run"
if target.x > vel.x:
sprite.set_flip_h(false)
elif target.x < vel.x:
sprite.set_flip_h(true)
sprite.play(anim)
func _physics_process(delta):
#this moves the sprite
vel = (target - position).normalized() * speed
if (target - position).length() > 5:
vel = move_and_slide(vel)
What if you use self.position
instead of vel.x
…
like
if target.x < self.position.x:
sprite.flip_h = true
elif target.x > self.position.x:
sprite.flip_h = false
Yoseph | 2019-08-21 12:22