bullets.gd 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. const BULLET_COUNT = 500
  5. const SPEED_MIN = 20
  6. const SPEED_MAX = 50
  7. var bullets=[]
  8. var shape
  9. class Bullet:
  10. var pos = Vector2()
  11. var speed = 1.0
  12. var body = RID()
  13. func _draw():
  14. var t = preload("res://bullet.png")
  15. var tofs = -t.get_size()*0.5
  16. for b in bullets:
  17. draw_texture(t,b.pos+tofs)
  18. func _process(delta):
  19. var width = get_viewport_rect().size.x*2.0
  20. var mat = Matrix32()
  21. for b in bullets:
  22. b.pos.x-=b.speed*delta
  23. if (b.pos.x < -30):
  24. b.pos.x+=width
  25. mat.o=b.pos
  26. Physics2DServer.body_set_state(b.body,Physics2DServer.BODY_STATE_TRANSFORM,mat)
  27. update()
  28. func _ready():
  29. shape = Physics2DServer.shape_create(Physics2DServer.SHAPE_CIRCLE)
  30. Physics2DServer.shape_set_data(shape,8) #radius
  31. for i in range(BULLET_COUNT):
  32. var b = Bullet.new()
  33. b.speed=rand_range(SPEED_MIN,SPEED_MAX)
  34. b.body = Physics2DServer.body_create(Physics2DServer.BODY_MODE_KINEMATIC)
  35. Physics2DServer.body_set_space(b.body,get_world_2d().get_space())
  36. Physics2DServer.body_add_shape(b.body,shape)
  37. b.pos = Vector2( get_viewport_rect().size * Vector2(randf()*2.0,randf()) ) #twice as long
  38. b.pos.x += get_viewport_rect().size.x # start outside
  39. var mat = Matrix32()
  40. mat.o=b.pos
  41. Physics2DServer.body_set_state(b.body,Physics2DServer.BODY_STATE_TRANSFORM,mat)
  42. bullets.append(b)
  43. set_process(true)
  44. func _exit_tree():
  45. for b in bullets:
  46. Physics2DServer.free_rid(b.body)
  47. Physics2DServer.free_rid(shape)
  48. # Initalization here
  49. bullets.clear()
  50. pass