Kinematicbody2D randomly gets teleported to -521877127168

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

When running the game the player kinematicbody2d gets teleported extremely far away from 0 (like somewhere around 10^11 - 10^12 on both axes), even though there’s nothing about moving it to those coordinates in the code. The only part about moving the kinematicbody2d is a move_and_slide function which should either have a size of 500 or 2000.

Following is all the code related to the kinematicbody2ds movement.

func _process(_delta):
    velocity = Vector2.ZERO
    # Movement handling
    if Input.is_action_pressed("move_up"):
     	velocity.y -= 1
    if Input.is_action_pressed("move_down"):
    	velocity.y += 1
    if Input.is_action_pressed("move_left"):
    	velocity.x -= 1
    if Input.is_action_pressed("move_right"):
    	velocity.x += 1
    velocity = velocity.normalized()

	# Dodge
    if Input.is_action_just_pressed("move_dodge") and dodgingtimer == 0:
		dodgingtimer = 5
	
func _physics_process(_delta):
    if dodgingtimer > 0:
	   dodgingtimer -= 1
	   velocity *= dodgespeed
   else:
	   velocity *= speed

   move_and_slide(velocity)

500 and 2000 sound way too large for a single frame move. I assume you’ re saying those are the values of dodgespeed and speed here?

func _physics_process(_delta):
    if dodgingtimer > 0:
       dodgingtimer -= 1
       velocity *= dodgespeed
   else:
       velocity *= speed

   move_and_slide(velocity)

Again, that’ll be applied every physics frame. Are those values really what you intend?

jgodfrey | 2023-02-03 14:36

Yes, 500 and 2000 are speed and dodgespeed respectively. and it gets multiplied by delta within move_and_slide() so it’s not actually that big and I’ve used similar numbers in other projects without any issue.

Nonken | 2023-02-03 14:59

If you step through the code with the debugger, can you identify when the KB gets teleported?

jgodfrey | 2023-02-03 15:30

and it gets multiplied by delta within moveandslide() so it’s not actually that big

Right. So, those are effectively pixels per second speeds. As long as you’re aware…

jgodfrey | 2023-02-03 15:35

I managed to fix it by moving “velocity = velocity.normalized()” to the physics process instead of process.

Nonken | 2023-02-03 15:54

Nice. I’d recommend that you convert that to an Answer so someone with a similar problem in the future can see that the question contains potentially useful information from the board’s main view.

jgodfrey | 2023-02-03 16:36

:bust_in_silhouette: Reply From: Nonken

Fixed it by moving “velocity = velocity.normalized()” to _physics_process(), instead of having it in _process().

I believe it worked because if it’s in _process() then it may not be normalized for every physics frame making it multiply by “speed” multiple times, instead of resetting then multiplying.