Advertisement
ZigZagZat

Godot movement code

May 30th, 2020
928
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. #This is a better way of doing movement. Instead of having if statements for every movement, you could use #Input.get_action_strength , which would return 1 if the key is pressed. This also allows you to use analogue sticks or #keys. For example is you are using a controller and press the joystick half way, you would get a decimal value. It would #work like this: velocity.x = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
  2. #So if you only press left, it will be 0 - 1 which is -1, so you move left. If you only press right it will be 1 - 0, so 1 #and you will move right. If you press both it will be 1 - 1, zero so nobody moves. You could have this in a get_direction #function and return it as a Vector2 and store it in a direction variable, so when you are calculating the velocity you #could do direction.x * speed.
  3. #This is a better way of doing it as it handles gravity, movement and jumping all within one calculation and has minimal if #statements. Also, the longer you hold the jump button for the higher you go, capped at your jump height which is your #speed.y. This means you can do short and heigh jumps so it feels better and smoother.
  4.  
  5. extends KinematicBody2D
  6.  
  7. var velocity: = Vector2.ZERO
  8. export var speed:= Vector2(400.0, 600.0)
  9. export var gravity = 3000.0
  10.  
  11. func _physics_process(delta: float) -> void:
  12. # checking to see if the player has let go of the jump key
  13. var is_jump_interrupted: = Input.is_action_just_released("jump") and velocity.y < 0.0
  14. var direction: = get_direction()
  15. velocity = calculate_move_velocity(velocity, direction, speed, is_jump_interrupted)
  16. velocity = move_and_slide(velocity, Vector2.UP)
  17.  
  18. func get_direction() -> Vector2:
  19. #getting the direction the player is moving in, returns 1, 0 or -1
  20. return Vector2(
  21. Input.get_action_strength("move_right") - Input.get_action_strength("move_left"),
  22. -1.0 if Input.is_action_just_pressed("jump") and is_on_floor() else 1.0
  23. )
  24.  
  25. func calculate_move_velocity(linear_velocity: Vector2, direction: Vector2, speed: Vector2, is_jump_interrupted: bool) -> Vector2:
  26. # calculating final velocity
  27. var out = linear_velocity
  28. # calculating the x velocity using the max speed and direction we got earlier
  29. out.x = speed.x * direction.x
  30. #applying gravity
  31. out.y += gravity * get_physics_process_delta_time()
  32. # checking to see if we are jumping and then calculating jump velocity
  33. if direction.y < 0:
  34. out.y = speed.y * direction.y
  35. # canceling jump if it is interrupted
  36. if is_jump_interrupted:
  37. out.y = 0
  38. return out
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement