navmesh.gd 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. extends Navigation
  2. # Member variables
  3. const SPEED = 4.0
  4. var camrot = 0.0
  5. var begin = Vector3()
  6. var end = Vector3()
  7. var m = SpatialMaterial.new()
  8. var path = []
  9. var draw_path = true
  10. func _process(delta):
  11. if path.size() > 1:
  12. var to_walk = delta * SPEED
  13. var to_watch = Vector3(0, 1, 0)
  14. while to_walk > 0 and path.size() >= 2:
  15. var pfrom = path[path.size() - 1]
  16. var pto = path[path.size() - 2]
  17. to_watch = (pto - pfrom).normalized()
  18. var d = pfrom.distance_to(pto)
  19. if d <= to_walk:
  20. path.remove(path.size() - 1)
  21. to_walk -= d
  22. else:
  23. path[path.size() - 1] = pfrom.linear_interpolate(pto, to_walk/d)
  24. to_walk = 0
  25. var atpos = path[path.size() - 1]
  26. var atdir = to_watch
  27. atdir.y = 0
  28. var t = Transform()
  29. t.origin = atpos
  30. t = t.looking_at(atpos + atdir, Vector3(0, 1, 0))
  31. get_node("robot_base").set_transform(t)
  32. if path.size() < 2:
  33. path = []
  34. set_process(false)
  35. else:
  36. set_process(false)
  37. func _update_path():
  38. var p = get_simple_path(begin, end, true)
  39. path = Array(p) # Vector3array too complex to use, convert to regular array
  40. path.invert()
  41. set_process(true)
  42. if draw_path:
  43. var im = get_node("draw")
  44. im.set_material_override(m)
  45. im.clear()
  46. im.begin(Mesh.PRIMITIVE_POINTS, null)
  47. im.add_vertex(begin)
  48. im.add_vertex(end)
  49. im.end()
  50. im.begin(Mesh.PRIMITIVE_LINE_STRIP, null)
  51. for x in p:
  52. im.add_vertex(x)
  53. im.end()
  54. func _input(event):
  55. # if event extends InputEventMouseButton and event.button_index == BUTTON_LEFT and event.pressed:
  56. if event is InputEventMouseButton and event.button_index == BUTTON_LEFT and event.pressed:
  57. var from = get_node("cambase/Camera").project_ray_origin(event.position)
  58. var to = from + get_node("cambase/Camera").project_ray_normal(event.position)*100
  59. var p = get_closest_point_to_segment(from, to)
  60. begin = get_closest_point(get_node("robot_base").get_translation())
  61. end = p
  62. _update_path()
  63. if event is InputEventMouseMotion:
  64. if event.button_mask&(BUTTON_MASK_MIDDLE+BUTTON_MASK_RIGHT):
  65. camrot += event.relative.x * 0.005
  66. get_node("cambase").set_rotation(Vector3(0, camrot, 0))
  67. print("camrot ", camrot)
  68. func _ready():
  69. set_process_input(true)
  70. m.flags_unshaded = true
  71. m.flags_use_point_size = true
  72. m.albedo_color = Color(1.0, 1.0, 1.0, 1.0)