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

Unity角色对角线移动穿透墙角碰撞体问题求助

问题描述
  • 搭建的Unity场景:带相机的玩家、行走平面、两个带Box Collider的墙体
  • 异常表现:单方向(X/Z轴)移动时触墙会正常停下,但在墙角处同时按W+D对角线移动,玩家会穿透或滑过墙角
现有玩家控制脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerController : MonoBehaviour
{
    public float p_moveSpeed = 10f;

    void Start()
    {

    }

    void Update()
    {
        float horizontalInput = Input.GetAxisRaw("Horizontal");
        float verticalInput = Input.GetAxisRaw("Vertical");

        Vector3 moveDirection = new Vector3(horizontalInput, 0f, verticalInput);
        transform.position += moveDirection * p_moveSpeed * Time.deltaTime;
        moveDirection.Normalize();
    }
    void LateUpdate()
    {
        Vector3 position = transform.position;
        transform.position = position;
    }

}
已尝试但无效的解决方案
  • 在墙角添加带碰撞体的球体
  • 将墙体设置为Hierarchy中的Static
  • 将墙体设为Kinematic
  • 更换各类碰撞体
  • 添加多个Rigidbody并调整Collision Detection模式
  • 调整玩家和墙体的尺寸
解决方法

问题根源是直接修改transform.position移动玩家会绕过Unity碰撞检测系统,导致对角线移动时碰撞判定失效。正确做法是用Unity内置CharacterController组件的Move方法处理移动,它会自动处理碰撞和墙角挤压判定。

修改步骤:

  1. 确保玩家对象已添加CharacterController组件(Inspector面板点击Add Component搜索添加)
  2. 替换脚本代码:
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float moveSpeed = 10f;
    private CharacterController _controller;

    void Start()
    {
        _controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");

        Vector3 moveDir = new Vector3(horizontal, 0f, vertical).normalized;
        _controller.Move(moveDir * moveSpeed * Time.deltaTime);
    }
}

额外说明:

  • 移除无意义的LateUpdate代码,它对移动和碰撞无帮助
  • 先归一化移动方向,避免斜向移动速度过快
  • CharacterController.Move会自动处理与碰撞体的交互,包括墙角挤压,不会出现穿透问题

内容的提问来源于stack exchange,提问作者Juan-Jacques Joubert

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 08:19:57