KinematicBody2D doesn't stay in the position set before

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

I’m making a shooter game follow Angega Studio’s studio. And I have some problems here.
My project’s screen’s size is (360, 640) and I set the ship (using KinematicBody2D) at (180, 540).
When I instanced and ran it, I noticed that the ship come from top-left of the screen to my mouse, not from the position I set before.
I tried printing the position out. The first one said (180, 540) but the ship its not on the screen. The second one is (-720, -2160) and after that the ship came closer and closer to the mouse’s position.

The ship’s scripts (Elite is the name of the ship):

extends KinematicBody2D

var mouse_pos = Vector2()
var direction = Vector2()
var elite_pos = Vector2()
var laser_pos = Vector2()

onready var main_cannon = get_node("weapons/main_cannon")

var elite_laser = preload("res://scenes/elite_laser.tscn")

export var speed = 5

func _ready():
	_process(true)
	pass

func _process(delta):
	print(self.position)
	mouse_pos = get_global_mouse_position()
	elite_pos = self.position
	direction = mouse_pos - elite_pos
	
	move_and_slide(direction * speed)
	pass
	
func _create_laser():
	var laser = elite_laser.instance()
	var cannon_pos = main_cannon.position
	laser.position = cannon_pos
	get_node("/root").add_child(laser)
	pass

func _on_Timer_timeout():
	_create_laser()
	pass

Hi,
Although i don’t see anything could be causing that problem, in my opinion there are a few changes i would do to the code.
First, i think move_and_slide() shouls be called inside _physics_process() instead than in _process() because it involves physics calculations. Second, i think you should update your movement like this:

movement = direction * speed
movement = move_and_slide(movement)

So movement gets updated. In your actual code is the same, but i think is a good practice to update the movement in case you want to use it in another place od your code later.

About the position issue, could you share us the script where the ship gets instantiated and its position is set?

p7f | 2018-12-09 15:00

Yeah, I no longer doing on this project but thank you anyway. I think this will help me later.

congbinh75 | 2019-08-10 05:26