Dropping RigidBody3D Pickups Around Player

Godot Version

4.7.2 Stable

Question

I am spawning Pickup instances when the player selects the item in an inventory. The Pickup instance is a RigidBody3D which has a child scene representing the object visually, and a CollisionShape3D which has a shape assigned when its spawned. The player will be able to drop multiple items at once. I am currently just spawning the pickups in a random circle around the player. I think some of the collision shapes are intersecting each other or the player when the item is spawned, but the physics engine so far has been resolving these pretty gracefully. The issue is if I stand near a wall, sometimes the pickups just disappear and I’m not sure what the best way to handle this is. Either to just test each spawn position and iterate a number of times until a position is found, or maybe I am going about this the wrong way?

class_name Game
extends Node3D

const PICKUP: PackedScene = preload("res://pickup/pickup.tscn")

@export var player: Player

@onready var level: Node3D = $TestLevel


func _ready() -> void:
	assert(player, "Player must be assigned.")
	player.inventory_component.item_dropped.connect(_on_item_dropped)


func get_random_drop_position(center: Vector3, radius: float) -> Vector3:
	var angle: float = randf_range(0.0, TAU)
	return center + Vector3(cos(angle) * radius, 0.5, sin(angle) * radius)


func _on_item_dropped(item_data: ItemData, quantity: int) -> void:
	for i: int in quantity:
		var pickup: Pickup = PICKUP.instantiate()
		level.add_child(pickup)
		pickup.item_data = item_data
		pickup.global_position = get_random_drop_position(player.global_position, 1.0)

Instead of generating random positions, generate random directions. Ray or shape cast in each direction and limit the spawn distance along the direction to the point of hit or to the end of max range if nothing was hit.

I think I am going to research into this method more, it sounds like exactly what I need.

Its my first time working on a 3D game, I am a little unsure how best to handle situations where the system can’t determine a free position - Would you just spawn the item and let physics hash it out or prompt the player that they can’t drop the item in the location? I guess those are more design questions…

Player should always be able to drop an item. The thing you want to avoid is spawning on positions that are partially or fully “inside walls”. Especially if your wall colliders are concave shapes. You can always raycast a whole 360 deg fan of directions, eliminate the ones that hit something that’s very close and randomly pick a needed number of them from the remaining candidates.