Advertisement
ivess_john

Top-down Movement Acceleration and Friction

Oct 2nd, 2021
1,416
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. extends KinematicBody2D
  2.  
  3. export(int) var SPEED: int = 200
  4. export(int) var ACCELERATION: int = 30
  5. export(int) var FRICTION: int = 50
  6. var velocity: Vector2 = Vector2.ZERO
  7.  
  8. onready var sprite = $Sprite
  9. onready var animPlayer = $AnimationPlayer
  10.  
  11.  
  12. func _physics_process(delta):
  13.     var input_dir: Vector2 = get_input_direction()
  14.     # Moving
  15.     if input_dir != Vector2.ZERO:
  16.         accelerate(input_dir)
  17.         animPlayer.play("run")
  18.        
  19.         # Turn around
  20.         if input_dir.x != 0:
  21.             sprite.scale.x = sign(input_dir.x)
  22.     # Idle
  23.     else:
  24.         apply_friction()
  25.         animPlayer.play("idle")
  26.     move()
  27.  
  28. func move():
  29.     velocity = move_and_slide(velocity)
  30.  
  31. func accelerate(direction: Vector2):
  32.     velocity = velocity.move_toward(SPEED * direction, ACCELERATION)
  33.  
  34. func apply_friction():
  35.     velocity = velocity.move_toward(Vector2.ZERO, FRICTION)
  36.  
  37. func get_input_direction() -> Vector2:
  38.     var input_direction = Vector2.ZERO
  39.    
  40.     input_direction.x = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
  41.     input_direction.y = Input.get_action_strength("move_down") - Input.get_action_strength("move_up")
  42.     input_direction = input_direction.normalized()
  43.    
  44.     return input_direction
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement