How do I get the objects coordinates (needed for movement)?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Federe76
:warning: Old Version Published before Godot 3 was released.

Hi, I’m trying to get an object to do a patrol movement.

The idea is: It goes up until it reaches “this y value”, then turns around, goes down until “this other y value” and so on.

My idea is somthenig like this, setting this code into the object’s own script.

var topy = 0 # i.e.
var lowy = 200
var dir = 1

if dir == 1:

move_local_y(-10)

if dir == 0:

move_local_y(10)

if (my own Y value) == topy:

dir = 0

if (my own Y value) == lowy:

dir = 1

My problem is that I’m not being able to find an action to get “my own Y value”. I need the object to detect its own coordinates so it can turn around when needed.

Hope to have been clear enough, thanks in advance.

Not an answer for the get_pos/get_global_pos but for what I think you want to do:


You can use a tween for that and loop up-down for the eternity.

Another thing, add the node to a “patroller” group, use 2 areas and on body enter, change the dir value ( dir *= -1)of the body if it is in the “patroller” group.
This way the limits will be easier to move and can be duplicated and added everywhere, all with the same script.

eons | 2017-01-18 20:29

:bust_in_silhouette: Reply From: Zylann

Having a look at the docs and examples around, you can find the position of a 2D node with get_pos(). It returns a position with x and y components.

For patrolling, you can also have a search at how the PathFollow2D node works.

Thanks, but I had a problem with get_pos(). My object (node) is a kinematicbody2d, and I get an error saying get_pos is an invalid call for kinematicbody2d, same thing for rigidbody.

Federe76 | 2017-01-18 19:03

KinematicBody2D inherits Node2D, so you certainly have access to get_pos() on it. If you don’t, you probably made an error earlier in your code (like, maybe the variable was not containing what you expected). You are working in 2D, right? (because in 3D the function is get_translation()).

Note: RigidBody2D also inherits Node2D and it has get_pos, but that one updates itself according to the laws of physics, so you would not be able to set its position but only apply forces to it.

Zylann | 2017-01-18 19:24

Got it, re-wrote the script from scratch, didn’t have much yet. Don’t know exactly what was wrong, but we are up and running.

Thanks a lot.

Federe76 | 2017-01-18 19:59

:bust_in_silhouette: Reply From: Godot_Hacker

If you are using Godot 3.0, use get_position(). This returns a Vector2() (in 2D scenes) of the x and y position of the thing which has the script in relation to itself or another object depending of the code surrounding it and how you use it.

You also no longer need to use the getter method; you can just use the position member.

H3katonkheir | 2020-11-10 02:01