Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | Serenade | |
Old Version | Published before Godot 3 was released. |
Hi!
I made a object(kinematic 2d) that creates objects when you press button (like a gun, it shoots those objects in one direction)
But the thing is,i dont know how to limit the amount that can exist in the sceene or/and make a limit that you can shoot…
Also i cant make them dissapear when they hit JUST the player or leave screen…
Btw, the “bullet” is a seperate sceene.
Code… anyone? : D
Hi! Serenade,
I hope I can help you
var bulletLimit = 10 # Firing range
var bulletCount = 0 # Counter of shot bullets
func _process(delta):
if Input.is_key_pressed(81): # 81, Q index code
if bulletCount <= bulletLimit:
spawn Object # Your spawn object code here
bulletCount += 1
Aquiles | 2017-01-17 16:58
Unrelated, but you should use KEY_Q
instead of 81
Zylann | 2017-01-17 18:15
Ill try this ;D
Serenade | 2017-01-17 22:12
But… how do you delete previous bullets when the limit is reached? (like, 10 bullets, when 11th is created, the very first one is deleted…)
Serenade | 2017-01-17 22:14
You can do it this way:
const MAX_BULLETS = 10
var bullets = []
func create_bullet():
# Create your bullet (just an example)
var bullet = bullet_resource.instance()
world.add_child(bullet)
# Then decide what to do
if bullets.size() < MAX_BULLETS:
bullets.append(bullet)
else:
var oldest_bullet = bullets.remove(0)
oldest_bullet.queue_free()
bullets[0] = bullet
At some point the second case in the last if
will be always executed, unless bullets get destroyed afterwards (in which case you might want to remove them from the list). The implementation of this can change depending on what you plan to do with those bullets.
Zylann | 2017-01-17 22:29
Thanks! Ill try this out!
havent used “size(), .remove(0), .append(var)” before though
Serenade | 2017-01-17 22:37
I just found that my code is slightly wrong, because it won’t always destroy the oldest bullet. The container you need is a queue, so you can push recent bullets and pop older ones. However I don’t see queues in GDScript containers so you would have to find a way with an array and an increasing index variable that wraps when it reaches the end (if you need it, otherwise you can sort by lifetime if it’s better for you :p)
Zylann | 2017-01-18 02:55
Assign an ID (a kind of counter) to the bullets, no array, add them to a group (or create the bullet scene as part of a group).
If group size is on limit, search for the lower ID and remove it.
That way covers hits and limits, but only bullets on the scene tree will count (I don’t know if will be a problem or not for your game).
eons | 2017-01-18 04:30