0 votes

I got a car that i want to place in a 2d race, and i want to spawn if via code(so i could scramble game modes and maps) and as the title say how can i spawn it in a specific x and y(lets say 300,230)

in Engine by (1,200 points)

1 Answer

+4 votes
Best answer

You can do it that way:

var car_resource = preload("car.tscn")
var car = car_resource.instance()
car.set_pos(custom_position) # use set_translation() if you are in 3D
parent.add_child(car) # parent could be whatever node in the scene that you want the car to be child of

As a suggestion, I would not spawn cars in hardcoded positions. Instead, in every map I would place spawn points (Spatial or Node2D nodes) to know where to position the cars.

by (28,835 points)
selected by

do i need to make the instance first or i can set the position whenever i want to?

You have to make an instance first.

You can set the position on the instance only because car_resource is a resource, not a node. You can set the position before or after add_child, but I prefer before because the node's _enter_tree logic will be able to use it, in case it needs to.

thanks for 3d comment :)

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.