You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求适用于Unity 6.3的3D C# WASD基础移动参考代码

Unity 6.3 WASD基础移动实现(附实用扩展功能)

基础WASD移动代码

以下是适配Unity 6.3的基础移动代码,用C#编写,适合新手直接复用:

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    // 可在Inspector面板调整的移动速度
    [SerializeField] private float moveSpeed = 5f;
    private CharacterController controller;

    void Start()
    {
        // 获取玩家对象上的CharacterController组件
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        // 读取WASD的输入值(范围-1到1)
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        // 基于主相机视角计算移动方向,确保移动符合玩家视角
        Vector3 moveDirection = Camera.main.transform.right * horizontalInput + Camera.main.transform.forward * verticalInput;
        // 移除Y轴分量,保持水平移动
        moveDirection.y = 0f;
        // 标准化方向向量,避免斜向移动时速度过快
        moveDirection.Normalize();

        // 执行移动
        controller.Move(moveDirection * moveSpeed * Time.deltaTime);
    }
}

快速使用步骤

  • 给你的玩家对象添加CharacterController组件(菜单栏:Component → Physics → Character Controller)
  • 创建新C#脚本,命名为PlayerMovement,粘贴上述代码
  • 将脚本拖到玩家对象上,运行游戏即可用WASD控制移动

实用扩展功能

1. 重力与地面贴合

添加重力效果,让角色自然下落并保持贴地:

// 在原代码基础上新增以下变量和逻辑
[SerializeField] private float gravity = -9.81f;
private Vector3 velocity;

void Update()
{
    // 原有移动代码...

    // 重力处理:角色在地面时重置垂直速度
    if (controller.isGrounded && velocity.y < 0)
    {
        velocity.y = -2f; // 轻微向下力,确保角色稳定贴地
    }

    velocity.y += gravity * Time.deltaTime;
    controller.Move(velocity * Time.deltaTime);
}

2. 冲刺功能

按左Shift触发高速冲刺:

// 在原代码基础上新增以下变量和逻辑
[SerializeField] private float sprintSpeed = 8f;
private float currentSpeed;

void Update()
{
    // 根据Shift按键切换速度
    currentSpeed = Input.GetKey(KeyCode.LeftShift) ? sprintSpeed : moveSpeed;

    // 移动时替换为currentSpeed
    controller.Move(moveDirection * currentSpeed * Time.deltaTime);

    // 原有重力代码...
}

3. 移动脚步音效

给角色添加脚步音效(需先给玩家对象添加AudioSource组件):

// 在原代码基础上新增以下变量和逻辑
[SerializeField] private AudioClip footstepClip;
private AudioSource audioSource;

void Start()
{
    controller = GetComponent<CharacterController>();
    audioSource = GetComponent<AudioSource>();
}

void Update()
{
    // 原有移动代码...

    // 当角色移动且在地面时,播放脚步音效
    if (controller.velocity.magnitude > 0.1f && controller.isGrounded && !audioSource.isPlaying)
    {
        audioSource.PlayOneShot(footstepClip);
    }
}

内容的提问来源于stack exchange,提问作者Bippity_Boppity2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 15:22:27