Change Instantiate Position?

Godot Version

Godot 4.3

Question

Hello. So I’m working on a shmup game, and I’m currently working on the code for shooting. I have this code that works, albeit without auto-shoot when held but that will be coming later. The code as I initially had it was as follows:

	if Input.is_action_just_pressed("action_shoot"): #and akane_upgrade == 0:
		var new_proj1 = proj1.instantiate()
		new_proj1.global_position = global_position
		add_sibling(new_proj1)

This works, but the laser blasts (proj1) are shot from the middle of the ship, while the gun is on the front of the ship. I tried doing the global_position line differently, with the position put as the x,y coordinates of where I want the proj1 to be spawned from where the gun is on the ship’s sprite, with the center of the entity being 0,0, but it doesn’t work how I put it:

		new_proj1.global_position = 23, 10

That line gives an error. What would be the correct way for putting the position at a specific point on the entity spawning it? The parent I’m spawning it on is an Area2D if it helps.

Hi!
What you want to do here is use a Vector2:

new_proj1.global_position = Vector2(23, 10)

This is how 2-dimensional values are used in general.

Usually, a good idea is to use type hints in your code early on, so you can build an understanding of the types that are used

2 Likes

You could also use a marker2d in the scene to set a ‘spawn’ position if its static. And then just get the global position of that instead.

It’s a bit overkill but it allows you to visually move it around without having to change the code.

2 Likes

Yes, as I’ve been getting info from tutorials and just figuring things out myself I’ve been using notes in the code to keep track of why I do each line of code the way I do. It’s been helping me learn. Thank you so much for your answer!

I figured there was a child I could add to the scene to achieve this, but I couldn’t figure out which. Thank you so much!

So, I tried doing your idea like this: (Main_Gun is the name of the Marker2D I created for the gun)

		new_proj1.global_position = $Main_Gun

But when I tried testing the shooting, it crashed and gave me the following error:

Invalid assignment of property or key ’ global_position’ with the value of type ‘Marker2D’ on a base object of type ‘Area2D (aka_proj_1.gd)’.

I’m assuming I can’t just do the assignment straight, I would have to do something different for the Marker2D method to work, but I don’t know how. Any further help would be greatly appreciated!

You want the global_position of the marker.

new_proj1.global_position = $Main_Gun.global_position
2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.