So my current project is sort of an asteroid style space shooter game where I want the player to be able fly around the map killing enemies and gathering resources. My character controller is very basic and moves the player along the x/y axis to move, very simple forward/back and left/right movement. I could keep it like that and just simply figure out how to have the player ship face the direction they are flying, however I feel the ability to rotate along the axis would be more aesthetically pleasing but also give the player greater control over where they are going/aiming.

Currently the code for the controller simply consists of:

func _process(delta):
	if Input.is_action_pressed("A"):
		self.position.x-= 10
	if Input.is_action_pressed("D"):
		self.position.x+= 10
	if Input.is_action_pressed("W"):
		self.position.y-= 10
	if Input.is_action_pressed("S"):
		self.position.y+= 10
	if Input.is_action_pressed("Fire"):
		var b = bullet.instance()
		add_child(b)

lol just goes to show how new I still am to coding. Anyway how can I modify this to get the desired effect?

If I understand the question correctly, you want to move the character based on where it is facing, with the left/right keys rotating the character, correct?

If so, using the code posted above, you just need to make a few modifications:

const ROTATION_SPEED = 50;
const MOVE_SPEED = 100;
func _process(delta):
	if Input.is_action_pressed("A"):
		# Rotate left
		self.rotation_degress -= ROTATION_SPEED * delta
	if Input.is_action_pressed("D"):
		# Rotate right
		self.rotation_degress += ROTATION_SPEED * delta
	if Input.is_action_pressed("W"):
		# Move forward based on rotation
		var forward_direction = Vector2(cos(rotation), sin(rotation))
		self.global_position += forward_direction * delta * MOVE_SPEED;
	if Input.is_action_pressed("S"):
		# Move backwards based on rotation
		var forward_direction = Vector2(cos(rotation), sin(rotation))
		# We're just using subtracting the forward direction to move backwards.
		self.global_position -= forward_direction * delta * MOVE_SPEED
	if (Input.is_action_pressed("Fire"):
		# Spawn a bullet
		var b = bullet.instance()
		add_child(b)
		# Side note: You probably want the following so your bullets don't
		# rotate with the player.
		# get_parent().add_child(b)

One thing you might need to change is the cosine and sine order in the forward_direction variable. I think the code I inputted works for sprites that are facing upwards, like the Godot logo, but you might need to swap them if your sprite faces sideways. I find I often trip myself up with the cosine/sine order when converting rotation to a vector.

Hopefully this helps!

3 years later