test_raycasting.gd 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. extends Test
  2. var _do_raycasts = false
  3. func _ready():
  4. yield(start_timer(0.5), "timeout")
  5. if is_timer_canceled():
  6. return
  7. _do_raycasts = true
  8. func _physics_process(_delta):
  9. if not _do_raycasts:
  10. return
  11. _do_raycasts = false
  12. Log.print_log("* Start Raycasting...")
  13. clear_drawn_nodes()
  14. for node in $Shapes.get_children():
  15. var body = node as PhysicsBody2D
  16. var space_state = body.get_world_2d().direct_space_state
  17. var body_name = String(body.name).substr("RigidBody".length())
  18. Log.print_log("* Testing: %s" % body_name)
  19. var center = body.position
  20. # Raycast entering from the top.
  21. var res = _add_raycast(space_state, center - Vector2(0, 100), center)
  22. Log.print_log("Raycast in: %s" % ("HIT" if res else "NO HIT"))
  23. # Raycast exiting from inside.
  24. center.x -= 20
  25. res = _add_raycast(space_state, center, center + Vector2(0, 200))
  26. Log.print_log("Raycast out: %s" % ("HIT" if res else "NO HIT"))
  27. # Raycast all inside.
  28. center.x += 40
  29. res = _add_raycast(space_state, center, center + Vector2(0, 40))
  30. Log.print_log("Raycast inside: %s" % ("HIT" if res else "NO HIT"))
  31. if String(body.name).ends_with("ConcavePolygon"):
  32. # Raycast inside an internal face.
  33. center.x += 20
  34. res = _add_raycast(space_state, center, center + Vector2(0, 40))
  35. Log.print_log("Raycast inside face: %s" % ("HIT" if res else "NO HIT"))
  36. func _add_raycast(space_state, pos_start, pos_end):
  37. var result = space_state.intersect_ray(pos_start, pos_end)
  38. var color
  39. if result:
  40. color = Color.green
  41. else:
  42. color = Color.red.darkened(0.5)
  43. # Draw raycast line.
  44. add_line(pos_start, pos_end, color)
  45. # Draw raycast arrow.
  46. add_line(pos_end, pos_end + Vector2(-5, -10), color)
  47. add_line(pos_end, pos_end + Vector2(5, -10), color)
  48. return result