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

Unity CharacterController碰撞检测失效无法触发死亡重生问题求助

核心问题原因

你当前使用CharacterController组件处理玩家移动,该组件的移动逻辑不依赖Unity原生物理刚体系统,默认不会触发OnCollisionEnter这类物理碰撞回调,这是脚本完全无法触发重生的根本原因。
之前的版本仅跳跃下落时触发,是因为当时的逻辑大概率是通过落地检测分支间接判断碰撞,步行时y轴速度为0没有触发对应判断分支。

修复步骤

1. 替换碰撞回调

将代码中的OnCollisionEnter替换为CharacterController专属的碰撞回调OnControllerColliderHit,该回调会在CharacterController移动碰到碰撞体时稳定触发,不管是步行还是跳跃状态。

2. 调整代码

修改后的完整代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovementScript : MonoBehaviour
{
    public CharacterController controller;
   
    public float speed = 12f;
    public float gravity = -9.81f;
    public float jumpHeight = 3f;

    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;

    Vector3 velocity;
    bool isGrounded;

    [SerializeField] 
    private Transform respawnPoint;

    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if(isGrounded && velocity.y < 0 )
        {
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z;

        controller.Move(move * speed * Time.deltaTime);

        if(Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
    }

    // CharacterController专属碰撞回调
    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        if(hit.gameObject.CompareTag("Obstacle"))
        {
            Debug.Log("We hit " + hit.gameObject.name);
            transform.position = respawnPoint.position;
            // 重置下落速度,避免重生后直接掉落
            velocity.y = -2f;
        }
    }
}

3. 项目配置检查

  • 所有危险障碍物必须正确设置Tag为Obstacle,注意拼写和大小写完全匹配
  • 障碍物必须挂载Collider组件,且不要勾选Is Trigger选项
  • 原代码中没用的MeshCollider相关声明和获取逻辑可以直接删除,CharacterController自带碰撞检测能力不需要额外的MeshCollider

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:21:02