box.gd 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. extends CharacterBody2D
  2. class_name Box
  3. var getting_force: bool = true
  4. var cached_velocity: Vector2
  5. func _physics_process(delta: float) -> void:
  6. # Add the gravity.
  7. if not is_on_floor():
  8. velocity.y += Globals.gravity * delta
  9. #move_and_slide because internally changes velocity
  10. cached_velocity = velocity
  11. move_and_slide()
  12. getting_force = false
  13. for i in get_slide_collision_count():
  14. var collision = get_slide_collision(i)
  15. _process_collision(collision)
  16. #stop any horizontal movement if box isn't controlled/pushed by player
  17. if not getting_force:
  18. velocity.x = 0
  19. func _process_collision(collision: KinematicCollision2D) -> void:
  20. var collider = collision.get_collider()
  21. var normal = collision.get_normal()
  22. if collider is Box:
  23. #Check correct sides
  24. if not (normal == Vector2.LEFT or normal == Vector2.RIGHT):
  25. return
  26. #Not to push if the boxes collide only with corners
  27. if abs(collider.position.y - position.y) > Globals.tile_size/2.0:
  28. return
  29. #Push box only if it has the same direction
  30. #Prevents box sticking to another box
  31. if (collider.velocity.x <= 0 and cached_velocity.x < 0) or \
  32. (collider.velocity.x >= 0 and cached_velocity.x > 0):
  33. var tmp = (collider.velocity.x + cached_velocity.x) / 2.0
  34. collider.velocity.x = tmp
  35. velocity.x = tmp
  36. collider.getting_force=true