Advertisement
Guest User

Untitled

a guest
Oct 4th, 2019
586
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. extends Sprite
  2.  
  3. var last_position = Vector2()
  4. var target_position = Vector2()
  5. var direction = Vector2()
  6.  
  7. export(float) var speed = 5
  8.  
  9. # References const TILE_SIZE from the Game Node2D
  10. onready var TILE_SIZE = get_parent().get_parent().TILE_SIZE
  11.  
  12. onready var ray = $RayCast2D
  13. onready var tween = $Tween
  14.  
  15. func _ready():
  16. speed = 1 / speed
  17.  
  18. position = position.snapped(Vector2(TILE_SIZE / 2, TILE_SIZE / 2))
  19.  
  20. target_position = position
  21.  
  22. func _process(delta):
  23. _get_direction()
  24.  
  25. # COLLISION == MOVE PLAYER BACK TO LAST POSITION
  26. if(ray.is_colliding()):
  27. target_position = last_position
  28.  
  29. _move_player()
  30. # NO COLLISION AND PLAYER IS NOT MOVING == MOVE PLAYER TO WHERE THEY WANT
  31. elif(target_position == position):
  32. target_position = position + direction * TILE_SIZE
  33. last_position = position
  34.  
  35. _move_player()
  36.  
  37. func _move_player():
  38. tween.interpolate_property(self, "position", position, target_position, speed, Tween.TRANS_LINEAR, Tween.EASE_IN)
  39. tween.start()
  40.  
  41. func _get_direction():
  42. var right = Input.is_action_pressed("ui_right")
  43. var left = Input.is_action_pressed("ui_left")
  44. var up = Input.is_action_pressed("ui_up")
  45. var down = Input.is_action_pressed("ui_down")
  46.  
  47. direction.x = int(right) - int(left)
  48. direction.y = int(down) - int(up)
  49.  
  50. # PLAYER TRIES TO MOVE DIAGONALLY
  51. if(direction.x != 0 && direction.y != 0):
  52. direction = Vector2.ZERO
  53.  
  54. # PLAYER TRIES TO MOVE AT ALL
  55. if(direction != Vector2.ZERO):
  56. ray.cast_to = direction * TILE_SIZE / 2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement