You have multiple ways, and it depends what you want to achieve.
a.) If you want the user to have to look (aim) at the object before picking it up, use a raycast, check this docs. Basically you project a ray from your object towards the direction it's facing and check if anything is on the way. Code is something like this (I wrote it by heart so, maybe it has some typo's):
var space_state = get_world().direct_space_state
# If your vector is looking at -z by default
var looking_direction = -get_transform().basis.z
var range_of_pickup = 2;
var result = space_state.intersect_ray(get_global_transform().origin, get_global_transform().origin + looking_direction * range_of_pickup, [self])
b.) If you want user to pick up an object that is anywhere in range r of him, add Area to kinematic body, and use it's body_entered
and body_exited
, to make the list of nearby objects. You have to connect the body_entered
and body_exited
signals in ready function of the Area (add Area, and add script to it), and then you can use the bound functions to add the entered bodies to a list, from which you can then access nearby bodies.
extends Area
var nearby_bodies = []
func _ready():
connect("body_entered", self, "body_entered")
connect("body_exited", self, "body_exited")
func body_entered(body):
nearby_bodies.append(body)
func body_exited(body):
nearby_bodies.erase(body)
2D example, just rename Area2D to Area.
Documentation for Area