Thank you very much for your response, that_duck. I highly appreciate it.
The code you provided worked well. I had to modify some of my other code but here it is:
extends RigidBody2D
@export var thrust_power: float = 3000.0
@export var torque_power: float = 800.0
@export var model_scale: float = 3.0
@export var max_speed: float = 250.0
@onready var model: Node3D = $Viewport3D/Model
@onready var viewport: SubViewport = $Viewport3D
@onready var ship_sprite: Sprite2D = $ShipSprite
func _ready() → void:
ship_sprite.texture = viewport.get_texture()
var glb_path: String = "res://spaceship.glb"
var ship_scene: PackedScene = load(glb_path) as PackedScene
if ship_scene:
var ship_instance = ship_scene.instantiate()
ship_instance.scale = Vector3(model_scale, model_scale, model_scale)
model.add_child(ship_instance)
if model.has_node("Mesh"):
model.get_node("Mesh").queue_free()
linear_damp = 0.0
angular_damp = 0.0
func _physics_process(_delta: float) → void:
if Input.is_action_pressed(“thrust”):
var facing_dir: Vector2 = Vector2.RIGHT.rotated(rotation - PI / 4) # +45 CW shift for back-thrust
apply_central_force(facing_dir * thrust_power)
if Input.is_action_pressed("turn_left"):
apply_torque(-torque_power)
if Input.is_action_pressed("turn_right"):
apply_torque(torque_power)
var facing_2d: Vector2 = Vector2.RIGHT.rotated(rotation)
var target_dir: Vector3 = Vector3(facing_2d.x, facing_2d.y, 0.001).normalized()
var right_dir: Vector3 = Vector3(0, 0, 1).cross(target_dir).normalized()
var up_dir: Vector3 = target_dir.cross(right_dir).normalized()
model.basis = Basis(right_dir, up_dir, target_dir)
func _integrate_forces(state: PhysicsDirectBodyState2D) → void:
var pos: Vector2 = state.transform.origin
pos.x = clamp(pos.x, 0.0, 6400.0)
pos.y = clamp(pos.y, 0.0, 3600.0)
state.transform.origin = pos
var vel: Vector2 = state.linear_velocity
if vel.length() > max_speed:
state.linear_velocity = vel.normalized() * max_speed
The issue I am facing now is that the thruster seems wonky. For example, when I turn the ship towards the 9 o’clock mark (left side), it flies up. When I’m facing up, it veers It’s as if it is being applied from the left side of the ship itself. I’m still learning this, so I haven’t the foggiest as to what exactly is causing such erratic behavior.
I could try and post screenshots later on if necessary. I will keep working on it and report back if I accidentally fix it, somehow. :]
Thank you again for the response. It really did help us a lot.