|Topic was automatically imported from the old Question2Answer platform.
I’m making an inventory system and it’s my turn to make items drop out depending on the player’s position, but how best to do it? I have a couple of guesses and didn’t even want to apply, but maybe I’ll understand if I’m doing the right thing or not. If necessary, I can throw off a piece of code on this topic. Thank you!
From the guides I found only how to make this thing in 3d from the position of the player’s camera
You could define a bounding box that defines where the objects could spawn around a player. Assuming the items obey physics properties and fall to the ground after dropping them, make sure the bounding box is above the player’s feet to make sure items don’t spawn in the floor. You otherwise probably want to center the bounding box around the player. Then, randomly generate two numbers that are bound within the bounding box. Use that pair as the position of the item being dropped. The generated position should be relative to something like the center of your player. Then create an instance of the item and add it to the scene (I imagine as a child of your player node’s parent would suffice). You may even want to consider adding a raycast2D or Area2D to the item to make sure it isn’t spawning inside a wall or floor, and if you detect that it is, randomly generate a new item position until it isn’t colliding with geometry.
The RandomNumberGenerator class and this tutorial should help guide you with RNG.
Oh, thank you! I’m already using raycast2d
The fact is that I saw an additional guide, but for 3d and there were these lines in two scripts:
func get_drop_position() → Vector3:
var direction = -camera.global_transform.basis.z
return camera.global_position + direction
func _on_inventory_menu_drop_slot_data(slot_data) → void:
war pick_up = PickUp.instantiate()
pick_up.slot_data = slot_data
pick_up.position = player.get_drop_position()
And no matter how I try to try to change it for 2d, I just get an error when throwing an item out of the inventory
I think what this code does is makes sure the dropped items are visible in the camera so that they don’t spawn by the player but behind the camera’s field of view if the camera is really close to the player. Otherwise, this code is similar to my suggesting but is meant for 3D.
My solution doesn’t actually account for the camera. If the camera zooms in a lot, the item may spawn outside the camera’s view, so you may want to account for that too. You may want to look at this post that has some code regarding camera/screen-border bounding box computation
godot_dev_ | 2023-05-24 17:30
Yes, maybe that’s what I meant But in general, the essence is clear and similar. Thank you again! I will try to study and do