# Get player velocity relative to the rotation

4.2.1 (4.0+)

### Question

I’m making multiplayer and I need to get player’s velocity relative to his rotation to animate walk in the AnimationTree.
I need something like this:

``````extends CharacterBody3D

var previous_position := Vector3.ZERO

func _process(delta: float) -> void:
if !is_multiplayer_authority(): #just example
var run_direction: Vector3 = (position - previous_position) * 10.0
previous_position = position

run_direction = smth_to_make_relative_to(run_direction, -global_transform.basis.z)
#run_direction is (1, 0, 0) if running right, (0, 1, 0) if forward etc.
character_animation_tree.set('parameters/run/blend_position', Vector2(run_direction.x, run_direction.y))
``````

I finally did it
The solution was on the unity subreddit. Worth looking more often there

``````extends CharacterBody3D

const VELOCITY_THRESHOLD := 3.0

var _previous_position := Vector3.ZERO

_previous_position  = position

func _process(delta: float) -> void:
if !is_authority:
var _velocity := (position - _previous_position) * 100.0
_previous_position = position

var velocity_difference := (Quaternion.from_euler(global_rotation).inverse() * _velocity);
var blend_position := Vector2(
velocity_difference.x * (0.0 if (abs(velocity_difference.x) < VELOCITY_THRESHOLD) else 1.0),
-velocity_difference.z * (0.0 if (abs(velocity_difference.z) < VELOCITY_THRESHOLD) else 1.0), #minus because by default forward is -1, not 1
).normalized() #limit to 1:    (16.21, 0) -> (1, 0),    (0, 20) -> (0, 1) ...
``````
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.