Get objects X axis positon

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


I’m trying to get and store a nodes X axis position so that another game object can use it to set itself to that X axis.

i.e. centre the Player to a ladder.

Currently I can only get both the X and Y, but I just wish to use the X.

I get the Ladders position with:

var ladder_position

func _ready() -> void:
    ladder_position = self.position

Then in the Player script I use:

func _on_Ladder_on_ladder() -> void:

Incidentally, the Ladder scene is autoloaded allowing me the reference :wink:

But obviously I don’t wish to set the Player to both axis’s, just the X.

What should I do instead?

:bust_in_silhouette: Reply From: Gluon

you just append with .x but I would suggest using global_position not position.

with your code it would be

func _ready() -> void:
    ladder_position.x = self.position.x

but as I say I would recommend

func _ready() -> void:
    ladder_position.x = self.global_position.x

global position is its position in absolute gamespace whereas position is a relative position to the sprite.

Bear in mind though if you only store the x position and you want to set the position later on you will need to give it a y axis as well.


Thanks for the info, however I get an error:

Invalid set index ‘x’ (on base: ‘Nil’) with type of ‘float’

I didn’t give my ladder_position variable a type:

var ladder_position

I tried it with:

var ladder_position = Vector2()

The error is gone, however I don’t know if this is correct.

I also don’t know how to write the Player’s script to match the position collected:

Currently I have:

func _on_Ladder_on_ladder() -> void:

I tried:

self.set_global_position.x = (Ladder.ladder_position.x)

But I get an error:
Invalid get index ‘set_global_position’ (on base: ‘KinematicBody2D (’). Did you mean ‘.set_global_position()’ or funcref(obj, “set_global_position”) ?

JayH | 2022-07-10 14:18

Oh sorry yes your var needs to be a vector.

With regards to the second error you would want something like this;

ladder_postion.x = Ladder.global_position.x
self.global_position.x = ladder_position.x

or you could bypass the variable altogether with

self.global_position.x = Ladder.global_position.x

Gluon | 2022-07-10 14:37

I used the last option:

self.global_position.x = Ladder.global_position.x

Which does what’s required, thanks.

However I now have another issue, but it’s more related to instancing the ladder I think. The ladder’s original position is only returned. After I move the ladder to another location in the Scene Tree, the position isn’t updated for the Player, the original position is all that’s available - I’ll post a new question related to this, as I think I have other issues regarding it unless you have an idea why?

JayH | 2022-07-10 14:56