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: https://youtu.be/zvMU9ad33SA
Why object doesn't created in front of player, instead keep spawns in same location? Any advice will very appreciate it.
Here's the full code of spawning object. Note that asteroid is just Rigidbody object with collision shape as child.
# AsteroidSpawner.gd extends Node onready var player: Player = get_tree().get_root().find_node("Player", true, false) var asteroid_scene: PackedScene = preload("res://Asteroid/Asteroid.tscn") func _ready(): spawn_asteroids() func spawn_asteroids(): while true: spawn_asteroid() yield(get_tree().create_timer(2), "timeout") func spawn_asteroid(): var spawn_position: Vector3 = get_spawn_position() var asteroid_instance = asteroid_scene.instance() asteroid_instance.global_transform.origin = spawn_position # Push towards player var direction_to_player: Vector3 = player.transform.origin - spawn_position var speed = min(rand_range(5, 10), 10) asteroid_instance.add_force(direction_to_player * speed, Vector3()) add_child(asteroid_instance) func get_spawn_position() -> Vector3: var player_position = player.global_transform.origin var player_forward_vector = player.global_transform.basis.z var spawn_position = player_position spawn_position.z -= player_forward_vector.z + 100 return spawn_position