How to make a detection radius around a spatial with gdscript.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Masaoto

Greetings everyone !

I’m new to this forum, so if there is anything that I’m doing wrong on that thread, please let me know, I will try to correct myself.

So first, I’ll explain what I am trying to make in order to not confuse anyone and then I will ask my question. Feel free to jump to the question if you already know of what I’m talking about with just the title ! :slight_smile:

1. What I am trying to do

I created two entities in my “world”, where one is a moveable player (a KinematicBody) and another one which is an interractable object (which is a spatial with a StaticBody)

Now, what I’m trying to do is to allow the player to “pick up” the object when he is near it by pressing a key on the keyboard.

To do so, I thought of a way which was to get the position of the two entities and to check if the position of the KinematicBody was around the position of the Spatial.

2. The question

How can I get the position of a spatial and of a KinematicBody in order to know it they are close to one another ?

Thank you for reading these few lines !

:bust_in_silhouette: Reply From: gmaps

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

Thank you so much for this answer, you must be god sent ! ToT

Masaoto | 2019-09-04 11:57