Wednesday, October 11, 2023

3D objects position

 So... Another Godot for the PS Vita entry here.

There are a few ways to check if the puck enters the net, and for the NPC to follow the puck, I need to know its position. Therefor I had to see how to manage it in Godot 3.5, and that's what I want to write here for the people who want to do the same.

WARNING: This is the way I came up with. There could be more, and it may be different in other Godot versions, but for me, it works. Besides, this can be reused in any other project easily. Last but not least, the code and Idea below shows values in screen to give you an idea of how to use it, the numbers are by no means used in practice yet (I save that for another entry, maybe).

Without further ado, Code to see the positions of 3d objects in Godot 3.5

First, I took the "3D Squash the Creeps starter project" from https://github.com/gdquest-demos/godot-3-getting-started-2021/releases/tag/1.0.0 to have a test base (this way I don't have to create a new scene, and anyone can follow along without much problem). I cleaned a bit tho, no need of the mobs group or the scoring system for my test.






Then, I created and used signals to send the numbers from the Player and the creeper(Mob) to a UserInterface/Label node(ScoreLabel), so they can be printed in screen.  My added code is below:

```
# Creeper Code

signal creep
func _process(delta):
    var cPosition = get_global_transform()
    emit_signal("creep", str(cPosition))
```

```
# Player Code

signal player
func _process(delta):
    var pPosition = get_global_transform()
    emit_signal("player", str(pPosition))
```

Once I had the numbers, I just created two local variables on the label and printed them on screen.
```
# textPositions label code

extends Label

var player_position = 0
var creep_position = 0


func _on_Mob_creep(cPosition):
    creep_position =  cPosition

func _on_Player_player(pPosition):
    player_position =  pPosition

func _process(delta):
#    text = "PlayerPos: %s " % player_position
#    text = "CreeperPos: %s " % creep_position
    text = "PlayerPos: %s \n" %player_position + "CreeperPos: %s" %creep_position
```
 
Here you can see images of the result with the player in various positions




More on the position and the get_global_transform() here: https://ask.godotengine.org/40558/follow-node-movement-but-ignore-rotation

Furthermore, if you want the net's position from the label node, you can use:
(In my case, the label was the grand-grandchild of the player's sibling, so a few parents were needed)

```
onready var netA = get_parent().get_parent().get_parent().get_node("GoalNet").get_global_transform().origin
```

No comments:

Post a Comment