12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- extends Area2D
- signal hit
- export var speed = 400 # pixel / sec
- var screen
- var target = Vector2()
- var target_reached = true
- func spawn(atPos):
- position = atPos
- show()
- $CollisionShape2D.disabled = false
- func die():
- hide()
- func _ready():
- hide()
- screen = get_viewport_rect()
- func _process(delta):
- var velocity = get_velocity_from_action()
- if velocity == Vector2.ZERO :
- velocity = get_velocity_from_target(delta)
- if velocity.length() > 0:
- velocity = velocity.normalized() * speed
- $AnimatedSprite.play()
- else:
- $AnimatedSprite.stop()
-
- position += velocity * delta
-
- position.x = clamp(position.x, 0, screen.size.x)
- position.y = clamp(position.y, 0, screen.size.y)
-
- if velocity.x != 0:
- $AnimatedSprite.animation = "right"
- $AnimatedSprite.flip_v = false
- $AnimatedSprite.flip_h = velocity.x < 0
- elif velocity.y != 0:
- $AnimatedSprite.animation = "up"
- $AnimatedSprite.flip_v = velocity.y > 0
- func _input(event):
- if event is InputEventMouseButton or event is InputEventMouseMotion :
- target = event.position
- target_reached = false
- func _on_Player_body_entered(_body):
- die()
- emit_signal("hit")
- $CollisionShape2D.set_deferred("disabled", true)
- func get_velocity_from_action() -> Vector2:
- var velocity = Vector2()
- if Input.is_action_pressed("ui_right"):
- velocity.x += 1
- if Input.is_action_pressed("ui_left"):
- velocity.x -= 1
- if Input.is_action_pressed("ui_down"):
- velocity.y += 1
- if Input.is_action_pressed("ui_up"):
- velocity.y -= 1
- return velocity;
- func get_velocity_from_target(delta):
- if target_reached :
- return Vector2.ZERO
- var path = target - position
- if path.length_squared() < speed * speed * delta * delta :
- target_reached = true
- return Vector2.ZERO
- return path
|