Kinematicbody2d movement

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By IranosMorloy
:warning: Old Version Published before Godot 3 was released.

Hey all.

Firstly, I am not any kind of programmer. So, I came into a moment, when I don’t know what to do with my player to just move it straight, no matter where it looks. Imagine an universe map, where player is piloting a spaceship. I know how to make it rotate, but how can I just push it in the way it’s currently looking at? E.g. to the right down corner of the screen? I truly don’t know.

Thank you for help.

You should show what you have so far, so we have an idea what you need help with.

kidscancode | 2017-10-14 23:21

This is what I actually have written down to my player node. For pressing the W button, I want to just add velocity in the direction it is facing at the moment, no matter which orientation it has on the 2d map. Idk if I should use move(), or something else.


extends KinematicBody2D

export var player_speed = 150
var rotation_speed = 10

var velocity = Vector2()

var btn_A = Input.is_action_pressed("btn_A")
var btn_D = Input.is_action_pressed("btn_D")
var btn_W = Input.is_action_pressed("btn_W")

func _ready():
	set_fixed_process(true)
	set_process_input(true)
	
func _fixed_process(delta):
	btn_A = Input.is_action_pressed("btn_A")
	btn_D = Input.is_action_pressed("btn_D")
	btn_W = Input.is_action_pressed("btn_W")
	
	if Input.is_action_pressed("btn_A"):
		set_rot(get_rot() + delta * rotation_speed)
	elif Input.is_action_pressed("btn_D"):
		set_rot(get_rot() + delta * -rotation_speed)
	elif Input.is_action_pressed("btn_W"):
		move()
	else:
		velocity = 0
		
	var motion = velocity * delta
	move(motion)

IranosMorloy | 2017-10-15 08:39

:bust_in_silhouette: Reply From: MScribner

I would put code in your loop like this:

if Input.is_action_pressed("btn_W"):
    set_linear_velocity(Vector2(speed*cos(get_rot()), speed*sin(get_rot()))
else:
    set_linear_velocity(Vector2(0,0))

This will allow your character to move in their current rotational direction. Cosine and Sine are trigonometric functions that translate angle into distance in the X and Y directions, respectively.

I think that this was meant for rigidbody2d, wasn’t it? I tried it anyway, but can’t even make it correct. This part of code u wrote for me makes the whole script see errors everywhere. In addition, when I play the whole project, I can’t move at all. What am I doing wrong?

EDIT: I tried to find a way how to implement what u wrote and it worked! So thank you very much! :slight_smile:

IranosMorloy | 2017-10-16 13:17