The rocket flies after the ship

Godot Version 4.3

I want to launch a rocket from a 2d marker point and make it fly further. But when I release the rocket, it stays in its original position (not on the marker) when I use ui_right, ui_left, and slows down when I press ui_down.

extends CharacterBody2D

var engine_thrust = 5
var accelerate = Vector2()
var rotation_dir = 0
var max_speed = 100
var max_back_speed = -20
@export var missile: PackedScene

func _input(_InputEvent):
	if Input.is_action_pressed("ui_up"):
		if accelerate.length() < max_speed:
			accelerate += Vector2(engine_thrust, 0)
	
	if Input.is_action_pressed("ui_down"):
			accelerate -= Vector2(engine_thrust, 0)
	
	accelerate.x = clamp(accelerate.x, max_back_speed, max_speed)

	rotation_dir = clamp(rotation_dir, -0.01, 0.01)
	rotation_dir = 0

	if Input.is_action_pressed("ui_right"):
		rotation_dir += 0.01
	if Input.is_action_pressed("ui_left"):
		rotation_dir -= 0.01


func shoot():
	var b = missile.instantiate()
	add_child(b) 
	b.transform = $Node/Marker2D.transform
	

func _physics_process(_delta):
	_input(InputEvent)
	rotation += rotation_dir
	velocity =  accelerate.rotated(rotation)
	if Input.is_action_just_pressed("ui_select"):
		shoot()
	print(rotation_dir)
	print(accelerate)
	move_and_slide()

Do you mean the rocket is staying in its original position? Because your code here is moving your CharacterBody2D, and when you shoot, it’s creating a child at the marker with no other properties (velocity, angle, etc., all default).

Edit: Also, you have a maximum velocity, but no minimum, which could cause issues down the line. Might want to clamp the values if you don’t want to be able to move in reverse at infinite speed.

2 Likes

Thx for the help. Really i didn no have min speed. But i talk about:

func shoot():
	var b = missile.instantiate()
	add_child(b) 
	b.transform = $Node/Marker2D.transform

I’m right now launch missile forward and this good. But when i rotate character, my rocket rotate and change speed to.

My rocket code he not crossing whith character code:

extends Area2D

var speed = 200

func _process(delta: float) -> void:
	position += transform.x * speed * delta

When you use “add_child”, you’re adding the missile to the ship, so any changes to the ship affect all of its children. Which now includes the rocket.

Basically using add_child in the ship code means your rocket is part of the ship

You’re going to want to add the rocket/missile as a child from the scene or something else. You could either have a the ship emit a signal to spawn the rocket in the main/parent scene, or you could have the code to spawn the rocket in the main/parent scene and then grab the variables/information you need from the ship when coding it there.

1 Like

thx you