Advertisement
Cruddier

Godot Movement with Grid

Aug 21st, 2021
2,523
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. extends Node2D
  2.  
  3. var speed = 256
  4. var tile_size = 32
  5.  
  6. var last_position = Vector2()
  7. var target_position = Vector2()
  8. var movedir = Vector2()
  9.  
  10. onready var ray = $Sprite/RayCast2D
  11.  
  12. func _ready():
  13.     position = position.snapped(Vector2(tile_size, tile_size))
  14.     last_position = position
  15.     target_position = position
  16.  
  17. func _process(delta):
  18.     #MOVEMENT
  19.     #collision
  20.     if ray.is_colliding():
  21.         position = last_position
  22.         target_position = last_position
  23.    
  24.     else:
  25.         #Movement
  26.         position += speed * movedir * delta
  27.        
  28.         if position.distance_to(last_position) >= tile_size - speed * delta:
  29.             position = target_position
  30.  
  31.     #IDLE
  32.     if position == target_position:
  33.         get_movedir()
  34.         last_position = position
  35.         target_position += movedir * tile_size
  36.  
  37.  
  38. func get_movedir():
  39.     var Left = Input.is_action_just_pressed("left")
  40.     var Right = Input.is_action_just_pressed("right")
  41.     var Down = Input.is_action_just_pressed("down")
  42.     var Up = Input.is_action_just_pressed("up")
  43.    
  44.     movedir.x = -int(Left) + int(Right)
  45.     movedir.y = - int(Up) + int(Down)
  46.    
  47.     if movedir.x != 0 && movedir.y != 0:
  48.         movedir = Vector2.ZERO
  49.     #collsion
  50.     if movedir != Vector2.ZERO:
  51.         ray.cast_to = movedir * tile_size
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement