bullets.gd 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. extends Node2D
  2. # This demo is an example of controling a high number of 2D objects with logic and collision without using scene nodes.
  3. # This technique is a lot more efficient than using instancing and nodes, but requires more programming and is less visual
  4. # Member variables
  5. const BULLET_COUNT = 500
  6. const SPEED_MIN = 20
  7. const SPEED_MAX = 50
  8. var bullets = []
  9. var shape
  10. # Inner classes
  11. class Bullet:
  12. var pos = Vector2()
  13. var speed = 1.0
  14. var body = RID()
  15. func _draw():
  16. var t = preload("res://bullet.png")
  17. var tofs = -t.get_size()*0.5
  18. for b in bullets:
  19. draw_texture(t, b.pos + tofs)
  20. func _process(delta):
  21. var width = get_viewport_rect().size.x*2.0
  22. var mat = Matrix32()
  23. for b in bullets:
  24. b.pos.x -= b.speed*delta
  25. if (b.pos.x < -30):
  26. b.pos.x += width
  27. mat.o = b.pos
  28. Physics2DServer.body_set_state(b.body, Physics2DServer.BODY_STATE_TRANSFORM, mat)
  29. update()
  30. func _ready():
  31. shape = Physics2DServer.shape_create(Physics2DServer.SHAPE_CIRCLE)
  32. Physics2DServer.shape_set_data(shape, 8) # Radius
  33. for i in range(BULLET_COUNT):
  34. var b = Bullet.new()
  35. b.speed = rand_range(SPEED_MIN, SPEED_MAX)
  36. b.body = Physics2DServer.body_create(Physics2DServer.BODY_MODE_KINEMATIC)
  37. Physics2DServer.body_set_space(b.body, get_world_2d().get_space())
  38. Physics2DServer.body_add_shape(b.body, shape)
  39. b.pos = Vector2(get_viewport_rect().size * Vector2(randf()*2.0, randf())) # Twice as long
  40. b.pos.x += get_viewport_rect().size.x # Start outside
  41. var mat = Matrix32()
  42. mat.o = b.pos
  43. Physics2DServer.body_set_state(b.body, Physics2DServer.BODY_STATE_TRANSFORM, mat)
  44. bullets.append(b)
  45. set_process(true)
  46. func _exit_tree():
  47. for b in bullets:
  48. Physics2DServer.free_rid(b.body)
  49. Physics2DServer.free_rid(shape)
  50. bullets.clear()