参考

YouTube:https://youtu.be/HmnwNadwHWI
kidscancode:基于网格的运动
image.png

  1. extends KinematicBody2D
  2. var grid_size = 16
  3. var inputs ={
  4. 'ui_up':Vector2.UP,
  5. 'ui down'Vector2.DOWN,
  6. 'ui left':Vector2.LEFT,
  7. 'ui_right':Vector2.RIGHT
  8. }
  9. func _unhandled_input(event):
  10. for dir in inputs.keys():
  11. if event.is_action_pressed(dir):
  12. move(dir)
  13. func move(dir):
  14. position += inputs[dir] * grid_size

image.png

  1. extends KinematicBody2D
  2. onready var ray = $RayCast2D
  3. var grid_size = 16
  4. var inputs ={
  5. 'ui_up':Vector2.UP,
  6. 'ui down'Vector2.DOWN,
  7. 'ui left':Vector2.LEFT,
  8. 'ui_right':Vector2.RIGHT
  9. }
  10. func _unhandled_input(event):
  11. for dir in inputs.keys():
  12. if event.is_action_pressed(dir):
  13. move(dir)
  14. func move(dir):
  15. var vector_pos = inputs[dir] * grid_size
  16. ray.cast_to = vector_pos
  17. ray.force_raycast_update()
  18. if !ray.is_colliding():
  19. position += vector_pos

image.png

image.png

image.png
image.png
为盒子也添加一个RayCast2D。
image.png

  1. extends KinematicBody2D
  2. onready var ray = $RayCast2D
  3. var grid_size = 16
  4. var inputs ={
  5. 'ui_up':Vector2.UP,
  6. 'ui down'Vector2.DOWN,
  7. 'ui left':Vector2.LEFT,
  8. 'ui_right':Vector2.RIGHT
  9. }
  10. func move(dir):
  11. var vector_pos = inputs[dir] * grid_size
  12. ray.cast_to = vector_pos
  13. ray.force_raycast_update()
  14. if !ray.is_colliding():
  15. position += vector_pos
  16. return true
  17. return false

将box添加到“box”组。
继续修改Player的代码如下:

  1. extends KinematicBody2D
  2. onready var ray = $RayCast2D
  3. var grid_size = 16
  4. var inputs ={
  5. 'ui_up':Vector2.UP,
  6. 'ui down'Vector2.DOWN,
  7. 'ui left':Vector2.LEFT,
  8. 'ui_right':Vector2.RIGHT
  9. }
  10. func _unhandled_input(event):
  11. for dir in inputs.keys():
  12. if event.is_action_pressed(dir):
  13. move(dir)
  14. func move(dir):
  15. var vector_pos = inputs[dir] * grid_size
  16. ray.cast_to = vector_pos
  17. ray.force_raycast_update()
  18. if !ray.is_colliding():
  19. position += vector_pos
  20. else
  21. var collider = ray.get_collider()
  22. if collider.is_in_group("box")
  23. if collider.move(dir):
  24. position += vector_pos

此时,玩家已经可以推动箱子了。
剩下的就是实现spot的Area2D在body_entered之后,进入下一关或弹出获胜对话框。
这样一个简单的推箱子游戏的核心就有了,就看你如何做出有趣的关卡了。