Vlad Ivanov
Vlad Ivanov

Reputation: 59

How do i set the x and y coordinates of a instance in GDscript

I do not know how to set the position of a instance in gd script. The instanced shows up on the corner of the screen.

Upvotes: 0

Views: 21036

Answers (2)

Christopher Bennett
Christopher Bennett

Reputation: 801

Depends on whether you want 2D or 3D.

A common method is as such:

  1. Create the object you want to instance in its own scene.
  2. Save the object as a scene (.tscn file) - for example "Scene1.tscn"
  3. Call upon your instanced scene from your main scene as follows:

    • Make sure to preload the scene you plan to instance before your ready() function. For example if was called "Scene1", then declare :

onready var Scene1 = preload("res://Scene1.tscn")

  • Then, later in your code when you want to call an instance of the scene, do it as such:

    var InstancedScene = Scene1.instance()
    add_child(InstancedScene)

// This simply instances the scene (I think at co-ordinates (0,0,0)), but you can tell it where to instance it using the following example:

For 3D use:

InstancedScene.transform.origin = Vector3(50.0, 0.0, -50.0)

//Gives position x=50, y=0, x=-50. This can also be used for rotation, just specify transform.basis and give a similar Vector3 coordinate set.

OR for 2D use:

InstancedScene.position = Vector2(100.0, 100.0)

//This instances the object 100 pixels across and 100 pixels down. Sub in whatever values you need. You can also specify a rotation using InstancedScene.rotation_degrees = 45 (To give 45 degrees for example)

Upvotes: 1

NautMeg
NautMeg

Reputation: 141

It depends on what type of instance. If it's an object that has been derived from something like a Node2D, then position.x or position.y should do it. Do you have any code we can look at?

Upvotes: 1

Related Questions