Topic was automatically imported from the old Question2Answer platform.
Asked By
Millard
So, i have a simple kinematic 2d character with this code
extends KinematicBody2D
export var direction = Vector2(0,0)
export var walk_speed = 200
export var jump_speed = -400
export var gravity = 200
func _ready():
pass
func _physics_process(delta):
direction.y += gravity * delta
direction.x = 0
if Input.is_action_pressed("left"):
direction.x -= walk_speed
if Input.is_action_pressed("right"):
direction.x += walk_speed
if Input.is_action_just_pressed("jump"):
direction.y = jump_speed
var movement = move_and_slide(direction, Vector2(0,-1))
And it works well, but it isn’t consistent (obviously) so in my move and slide function, i added:
var movement = move_and_slide(direction * delta, Vector2(0,-1)
The only problem is that it causes my character to move very slowly. I tried increasing the jump_speed and walk_speed variables, which works somewhat, but it seems like they would need to be big numbers to move correctly and i would rather deal with smaller variables.
So, is there a way to fix this, or do i have to multiply my variables by a hundred?
Also, out of curiosity, why does multiplying it with delta cause this?
You’re absolutely right! And the hundreds is actually the right place for those velocity values. Let me explain:
move_and_slide is a method that factors delta internally. So your code is basically multiplying by delta twice. Just remove the delta and move_and_slide will make it consistent.
Unlike in move_and_collide, you should not multiply it by delta — the physics engine handles applying the velocity.
thanks to both Kanor and exuln! I had no idea that move and slide already factors delta. Nice. Unsure which answer to select as best though. I guess i’ll choose Kanors since it was first, although exulns was helpful as well. Thanks again!
The delta parameter in the _process() function refers to the frame length - the amount of time that the previous frame took to complete. Using this value ensures that your movement will remain consistent even if the frame rate changes.
move_and_slide() automatically calculates frame-based movement using delta. Do not multiply your velocity vector by delta before passing it to move_and_slide().
So the reason your character moves slower when you multiple the movement vector by delta in the move_and_slide() function is because delta is less than one, so multiplying the movement vector by it reduces the length of the vector. The move_and_slide() method is consistent already since it multiples by delta automatically.
The speed that you multiple the movement vector by is in pixels/second. I don’t think you need to multiple the variable by 100, since the character would then be moving 20,000 pixels every second, which is bigger than anyone’s computer screen.