Search code examples
positionnodesscenegodotgdscript

How to get the position of a different object in gdscript?


I have a player, and I want to be able to detect when they are near a ball so they can press 'E' to kick it.

I'm new to godot and I'm probably just dumb but I can't figure out how to get the position of another object.

I have 3 separate scenes: MainScene(Node2D), Player(KinematicBody2D), and Ball(RigidBody2D). I want to attach a script to one of the scenes that detects how close the Player is to the Ball so they can kick it.

I'm not sure if I should attach the script to the MainScene, the Player scene, or the Ball scene and to be honest, I'm not entirely sure how the code should look. I'm not very familiar with the functions and the node/scene hierarchy is a little confusing.

I am familiar with Python, I just think I'm overwhelmed with this engine (its my first time using a game engine) and I'm having a bit of a tough time grasping it.

Any help would be greatly appreciated!

Side-quest: If you are feeling extra helpful I also need to figure out how to stop a RigidBody2D object from moving until the player hits 'E' on it to kick it!


Solution

  • For this you want an Area2D, which is purpose-built for "detecting nearby objects" without interacting with them physics-wise. Have an Area2D as a child of the Player node and connect the Player node to that Area2D's body_entered signal. Here's a tutorial on using Area2D for further info; this tutorial also links to various other tutorials that could be helpful.