Godot 4.0+ move_and_slide( MoveAndSlide )方法入参变属性、CharacterBody3D 重力WASD处理实例
Godot WASD移动方法基本概念和用法:
// Godot 3.x old method:
velocity = MoveAndSlide(velocity, new Vector3(0, 1, 0), false, 6, (float)(Math.PI / 4.0), false);
// 4.0+: KinematicBody2D、KinematicBody 已被 CharacterBody2D、CharacterBody3D 替代
// 以下各项均为可选属性:
UpDirection=new Vector3(0, 1, 0); // 等同 this.MotionMode = CharacterBody3D.MotionModeEnum.Grounded; 也等同 3.x 的 Vector3.Up
FloorStopOnSlope=false;
MaxSlides=6;
FloorMaxAngle=(float)(Math.PI / 4.0);
// infinite_inertia彻底废弃,可用单向碰撞层替代
Velocity = v3 ;
MoveAndSlide(); // 入参分散到CharacterBody3D属性了,比如移位 this.Velocity
GDScript 版本:
extends CharacterBody3D
const SPEED = 5.0
const JUMP_VELOCITY = 4.5
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")
func _physics_process(delta):
# Add the gravity.
if not is_on_floor():
velocity.y -= gravity * delta
# Handle Jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var input_dir = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
if direction:
velocity.x = direction.x * SPEED
velocity.z = direction.z * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
velocity.z = move_toward(velocity.z, 0, SPEED)
move_and_slide()