FOPENP

Godot: walking and turn around

This is an example of how I implemented (on Godot 3.4.2 stable) a walking and turning around system for a protagonist character.

  1. extends KinematicBody
  2. export var velocity 10
  3. onready var camera $"../pointOfView/Camera"
  4. onready var navigation $"../navigation"
  5. var spacestate PhysicsDirectSpaceState
  6. var path = []
  7. var pathidx 0
  8. var animstate 0   # 0 => idle ; 1 => walking
  9. func _ready():
  10.     spacestate get_world().direct_space_state
  11. func _input(event):
  12.     var mouseevent event as InputEventMouseButton
  13.     if not mouseevent:
  14.         return
  15.     
  16.     if mouseevent.pressed and mouseevent.button_index == 1:
  17.         var from camera.project_ray_origin(mouseevent.position)
  18.         var to from camera.project_ray_normal(mouseevent.position) * 200
  19.         var res spacestate.intersect_ray(fromto)
  20.         if not res.empty():
  21.             path navigation.get_simple_path(global_transform.originres.position)
  22.             # Reset the index
  23.             pathidx 0
  24.             # Begin of the walking
  25.             $"protagonist/AnimationPlayer".play("walk"0.5)
  26.             animstate 1  # walk
  27. func _physics_process(delta):
  28.     if pathidx path.size():
  29.         var direction path[pathidx] - global_transform.origin
  30.         if direction.length() < 1:
  31.             pathidx += 1
  32.         else:
  33.             move_and_slide(direction.normalized() * velocity)
  34. func _process(delta):
  35.     # The character turns around
  36.     if pathidx path.size():
  37.         var newT global_transform.looking_at(path[pathidx], Vector3.UP)
  38.         global_transform global_transform.interpolate_with(newT1.0 delta)
  39.     
  40.     # Finish the walking when the character doesn't have
  41.     # any path to follow.
  42.     if animstate == and pathidx path.size():
  43.         var distance global_transform.origin.distance_to(path[path.size()-1])
  44.         if distance 1.5:
  45.             animstate 0
  46.             $"protagonist/AnimationPlayer".play("idle"0.5)

This is a KinematicBody with a "protagonist" child. The protagonist follows a "path", and the end of the path is the destination point. With looking_at() and interpolate_with() the protagonist will progressively turn around through the destination point. It's also featuring the start and the end of a "walk".
example

2022
Feb, 21