Advertisement
Guest User

Untitled

a guest
Jan 18th, 2020
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. var selection = []
  2. var selection_shape
  3. var selection_shape_query
  4. var selection_origin
  5. var selection_rect = Rect2()
  6.  
  7. var space_state
  8.  
  9. func _ready():
  10. space_state = get_world_2d().direct_space_state
  11.  
  12. selection_shape = RectangleShape2D.new()
  13. selection_shape_query = Physics2DShapeQueryParameters.new()
  14. selection_shape_query.set_shape(selection_shape)
  15. selection_shape_query.collide_with_bodies = false
  16. selection_shape_query.collide_with_areas = true
  17. selection_shape_query.collision_layer = 4
  18.  
  19. func _unhandled_input(event):
  20. if event is InputEventMouseMotion:
  21. if Input.is_action_pressed("mouse_left"):
  22. update_select_area()
  23.  
  24. if event.is_action_pressed("mouse_left"):
  25. update_selection([])
  26.  
  27. $SelectVisual.visible = true
  28. selection_origin = get_global_mouse_position()
  29. update_select_area()
  30.  
  31. if event.is_action_released("mouse_left"):
  32. $SelectVisual.visible = false
  33.  
  34. func update_select_area():
  35. var mouse_pos = get_global_mouse_position()
  36. # set our selection_rect, the human readable selection area
  37. selection_rect.position = Vector2(min(mouse_pos.x, selection_origin.x), min(mouse_pos.y, selection_origin.y))
  38. selection_rect.end = Vector2(max(mouse_pos.x, selection_origin.x), max(mouse_pos.y, selection_origin.y))
  39.  
  40. # set visuals
  41. $SelectVisual.rect_position = selection_rect.position
  42. $SelectVisual.rect_size = selection_rect.size
  43.  
  44. # set our shape
  45. selection_shape.extents = selection_rect.size / 2
  46. selection_shape_query.transform.origin = selection_rect.position + selection_rect.size / 2
  47.  
  48. # query the space_state about what our shape is overlapping. it's set to only detect unit hitboxes in the ready function
  49. var new_selection = space_state.intersect_shape(selection_shape_query)
  50.  
  51. # trims the query return to what info we need
  52. for i in range(len(new_selection)):
  53. new_selection[i] = new_selection[i]["collider"].owner
  54.  
  55. update_selection(new_selection)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement