• 3D
  • Creating object in front of player, with some distance

I want to create objects in front of player with some distance, so that prevents hit with player immediately. So first, I get the global player position and direction vector which player towards:

var player_position = player.transform.origin
var player_forward_vector = player.global_transform.basis.z

And then give additional distance:

var spawn_position = player_position
spawn_position.z -= player_forward_vector.z + 100

And then set the position:

var asteroid_instance = asteroid_scene.instance()
asteroid_instance.transform.origin = spawn_position

When I run the game, first it seems work, however when I rotated the player, still object spawned same position, not in front of where I'm looking at.

Here's the video to demonstrate:

Why object doesn't created in front of player, instead keep spawns in same location? Any advice will very appreciate it.

9 days later

var player_forward_vector = player.global_transform.basis.z Maybe you should get the global_transform.basis.z from your camera instead. Check which object you actually rotate.

I think the issue is that you are accessing only the Z coordinate of the forward/Z basis. This will only move the asteroid relative to the direction the player is facing on the world-space Z axis. Instead, you will want to multiply the basis by the distance you want, and then add that to the position. Something like this should work (untested):

# Get the player's position in world-space
# (not strictly required, but since we are working in global space for rotation...)
var player_position = player.global_transform.origin

# Get the direction the Z axis faces
var player_forward_vector = player.global_transform.basis.z
# If the player node is scaled, we will need to normalize the direction.
# This is because the Vector3s (X, Y, and Z) stored in a Basis are also used
# to store a node's scale.
player_forward_vector = player_forward_vector.normalized()
# Set the spawn position
var spawn_position = player_position
# Add the player's forward vector, multiplied by the desired distance.
spawn_position += player_forward_vector * 100
# Spawn the asteroid
var asteroid_instance = asteroid_scene.instance()
asteroid_instance.global_transform.origin = spawn_position

I think that should, hopefully, fix the issue :smile: