How to make player not only rotate, but move in it's rotation direction?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Yozhik

I have a playercontroller 2d in top-down view game, where the players ship follows the cursor.
I have already done that my ship rotates to cursor with a small latency
code below shows how it was done

var rotation_speed = PI * 1.5 # PI = 180 degrees

func _look_at_mouse(delta):
	var v = get_global_mouse_position() - global_position
	var angle = v.angle()
	var r = global_rotation
	var angle_delta = rotation_speed * delta
	angle = lerp_angle(r, angle + 1.57, 1.0)
	angle = clamp(angle, r - angle_delta, r + angle_delta)
	global_rotation = angle

but now I need my ship not only rotate with latency, but also to move not exactly to cursor global position, but to it’s position with the same interpolation / latency as the rotation of the ship. I have no idea how to do it, tried many things. Code below represents my move function:

func _move_to_mouse(delta):
	if position.distance_to(get_global_mouse_position()) > stop_distance:
		var direction = get_global_mouse_position() - position
		var normalized_direction = direction.normalized()
		var direction_distance = direction.length()
		move_and_slide(normalized_direction * max(move_speed, direction_distance))
:bust_in_silhouette: Reply From: Liam Steyn

extends KinematicBody2D

onready var speed = 200

export var rotation_speed = 0.5*

var shift = false
var rotation_dir = 0 *
var velocity = Vector2() *

func _physics_process(delta):

rotation_dir = 0       *
velocity = Vector2()      *

if Input.is_action_pressed("shift up"):
	speed = 500
elif Input.is_action_pressed("shift down"):
	speed = 200

if Input.is_action_pressed("forward"):        *
	velocity += Vector2(-speed, 0).rotated(rotation)      *
elif Input.is_action_pressed("back"):       *
	velocity += Vector2(speed, 0).rotated(rotation)        *
	velocity.y = 0

if Input.is_action_pressed("left"):          *
	#rotation_dir -= 10*
if Input.is_action_pressed("right"):        *
	#rotation_dir += 108

if velocity.y == 0:
	rotation_speed = 0
	rotation_speed = 0.5

rotation += rotation_dir * rotation_speed * delta        *

move_and_slide(velocity)          *

I know this is more than what you asked for but I got the code from a similar thread and modified it a bit. You could use it if you want lol I don’t mind.

You should just change the variables to your comfort level.
The lines with the * after is the code you’d want to use.

I’m grateful for your help, no, really, I mean that. Yet I don’t really get how to use this code you gave me. Hence, I can’t use it. There are various input’s and I don’t have any inputs, the only thing I have is mouse position. Won’t it work with this? Do I have to change controlls? Or I just have to modify this somehow?

Yozhik | 2021-10-19 17:12