gdquest

Platform #2 - Refactored movement with _input method

Jan 24th, 2017
745
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. extends KinematicBody2D
  2.  
  3. var input_direction = 0
  4. var direction = 1
  5.  
  6. var speed = 0
  7. const MAX_SPEED = 800
  8. const ACCELERATION = 2000
  9. const DECELERATION = 8000
  10. var velocity = 0
  11.  
  12. func _ready():
  13.     set_process(true)
  14.     set_process_input(true)
  15.  
  16.  
  17. func _input(event):
  18.     var move_left = event.is_action_pressed("move_left")
  19.     var move_right = event.is_action_pressed("move_right")
  20.     var stop_moving = not (Input.is_action_pressed("move_right") or Input.is_action_pressed("move_left"))
  21.    
  22.     if move_left:
  23.         input_direction = -1
  24.     elif move_right:
  25.         input_direction = 1
  26.     elif stop_moving:
  27.         input_direction = 0
  28.    
  29.     if move_left or move_right and input_direction:
  30.         if input_direction == -1 * direction:
  31.             speed /= 3
  32.             direction = input_direction
  33.  
  34.  
  35. func _process(delta):
  36.     if input_direction:
  37.         speed += ACCELERATION * delta
  38.     else:
  39.         speed -= DECELERATION * delta
  40.     speed = clamp(speed, 0, MAX_SPEED)
  41.    
  42.     velocity = speed * delta * direction
  43.     move(Vector2(velocity, 0))
Add Comment
Please, Sign In to add comment