Deozaan

Player.gd

Oct 26th, 2020
1,913
329 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. extends Area2D
  2.  
  3. signal hit
  4.  
  5. export var speed = 400
  6.  
  7. var screen_size
  8.  
  9. var target = Vector2()
  10. var useMouse = false
  11.  
  12. func _ready():
  13.     screen_size = get_viewport_rect().size
  14.     hide()
  15.  
  16. func start(pos):
  17.     position = pos
  18.     target = pos
  19.     show()
  20.     $CollisionShape2D.disabled = false
  21.  
  22. func _input(event):
  23.     if event is InputEventScreenTouch and event.pressed:
  24.         target = event.position
  25.         useMouse = true
  26.     elif event is InputEventKey:
  27.         useMouse = false
  28.  
  29. func _process(delta):
  30.     var velocity = Vector2()
  31.    
  32.     if useMouse:
  33.         if position.distance_to(target) > 10:
  34.             velocity = target - position
  35.    
  36.     if Input.is_action_pressed("ui_right"):
  37.         velocity.x += 1
  38.     if Input.is_action_pressed("ui_left"):
  39.         velocity.x -= 1
  40.     if Input.is_action_pressed("ui_down"):
  41.         velocity.y += 1
  42.     if Input.is_action_pressed("ui_up"):
  43.         velocity.y -= 1
  44.    
  45.     if velocity.length() > 0:
  46.         velocity = velocity.normalized() * speed
  47.         $AnimatedSprite.play()
  48.     else:
  49.         $AnimatedSprite.stop()
  50.    
  51.     position += velocity * delta
  52.     position.x = clamp(position.x, 0, screen_size.x)
  53.     position.y = clamp(position.y, 0, screen_size.y)
  54.    
  55.     if velocity.x != 0:
  56.         $AnimatedSprite.animation = "walk"
  57.         $AnimatedSprite.flip_v = false
  58.         $AnimatedSprite.flip_h = velocity.x < 0
  59.     elif velocity.y != 0:
  60.         $AnimatedSprite.animation = "up"
  61.         $AnimatedSprite.flip_v = velocity.y > 0
  62.  
  63. func _on_Player_body_entered(_body):
  64.     hide()
  65.     emit_signal("hit")
  66.     $CollisionShape2D.set_deferred("disabled", true)
  67.  
RAW Paste Data