2d-3d velocity separation example

This commit is contained in:
Haze Weathers 2025-03-14 18:40:30 -04:00
parent c91c931ad3
commit 3a9a623de2

View file

@ -10,7 +10,7 @@ extends CharacterBody3D
@export var level_path: Path3D @export var level_path: Path3D
var h_speed: float = 0.0 var velocity_2d: Vector2 = Vector2.ZERO
func _physics_process(delta: float) -> void: func _physics_process(delta: float) -> void:
@ -24,20 +24,23 @@ func _physics_process(delta: float) -> void:
# horizontal movement # horizontal movement
var input_dir = signf(Input.get_axis(&"walk_left", &"walk_right")) var input_dir = signf(Input.get_axis(&"walk_left", &"walk_right"))
h_speed += input_dir * walk_acceleration * delta velocity_2d.x += input_dir * walk_acceleration * delta
if input_dir == 0.0: if input_dir == 0.0:
h_speed = move_toward(h_speed, 0.0, stopping_rate * delta) velocity_2d.x = move_toward(velocity_2d.x, 0.0, stopping_rate * delta)
h_speed = clampf(h_speed, -walk_speed, walk_speed) velocity_2d.x = clampf(velocity_2d.x, -walk_speed, walk_speed)
var h_velocity = global_transform.basis.z * h_speed
velocity.x = h_velocity.x
velocity.z = h_velocity.z
# vertical movement # vertical movement
velocity.y -= gravity * delta velocity_2d.y -= gravity * delta
if Input.is_action_just_pressed(&"jump"): if is_on_floor() and Input.is_action_just_pressed(&"jump"):
velocity.y = jump_force velocity_2d.y = jump_force
# translate 2d movement to 3d
velocity.x = global_transform.basis.z.x * velocity_2d.x
velocity.y = velocity_2d.y
velocity.z = global_transform.basis.z.z * velocity_2d.x
# apply movement and translate 3d velocity back to 2d
move_and_slide() move_and_slide()
var h_vel = (velocity * Vector3(1.0, 0.0, 1.0))
# update horizontal speed after slide velocity_2d.x = h_vel.length() * signf(global_transform.basis.z.dot(h_vel))
velocity_2d.y = velocity.y