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

Unity中玩家碰撞snowflake标签物体后如何暂停其他物体旋转

Unity 碰撞触发其他旋转对象暂停实现方案

前置配置检查

  • 给需要触发逻辑的目标对象设置Tag为snowflake,确保5个旋转对象、玩家对象都挂载了对应类型的碰撞体(3D项目用Collider系列组件,2D项目用Collider2D系列组件)
  • 玩家对象必须挂载Rigidbody(3D)/Rigidbody2D(2D)组件,否则Unity无法触发碰撞/触发检测回调;如果用触发检测模式,需要把碰撞体的Is Trigger选项勾选
  • 5个旋转对象统一挂载旋转控制脚本,方便统一管理旋转状态

第一步:编写旋转控制脚本

新建C#脚本命名为RotatingObject.cs,挂载到全部5个需要旋转的对象上:

using UnityEngine;

public class RotatingObject : MonoBehaviour
{
    [Header("旋转参数")]
    public float rotateSpeed = 60f; // 旋转速度,可在Inspector面板调整
    public bool canRotate = true; // 控制是否允许旋转的开关

    void Update()
    {
        if (canRotate)
        {
            // 3D项目默认绕Y轴旋转,2D项目可替换为 transform.Rotate(0,0,rotateSpeed * Time.deltaTime)
            transform.Rotate(Vector3.up * rotateSpeed * Time.deltaTime);
        }
    }
}

脚本默认canRotate为true,启动后对象会自动旋转,符合初始逻辑要求。

第二步:编写玩家碰撞检测逻辑

新建C#脚本命名为PlayerCollision.cs,挂载到玩家对象上,根据自己的项目类型(2D/3D、是否用触发器)保留对应回调即可:

using UnityEngine;

public class PlayerCollision : MonoBehaviour
{
    // ---- 3D项目回调 二选一 ----
    // 碰撞体勾选Is Trigger时使用
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("snowflake"))
        {
            PauseOtherRotators(other.gameObject);
        }
    }

    // 碰撞体未勾选Is Trigger时使用
    // private void OnCollisionEnter(Collision collision)
    // {
    //     if (collision.gameObject.CompareTag("snowflake"))
    //     {
    //         PauseOtherRotators(collision.gameObject);
    //     }
    // }

    // ---- 2D项目回调 二选一,替换上面3D回调即可 ----
    // private void OnTriggerEnter2D(Collider2D other)
    // {
    //     if (other.CompareTag("snowflake"))
    //     {
    //         PauseOtherRotators(other.gameObject);
    //     }
    // }
    // private void OnCollisionEnter2D(Collision2D collision)
    // {
    //     if (collision.gameObject.CompareTag("snowflake"))
    //     {
    //         PauseOtherRotators(collision.gameObject);
    //     }
    // }

    private void PauseOtherRotators(GameObject hitSnowflake)
    {
        // 获取场景内所有带旋转脚本的对象
        RotatingObject[] allRotators = FindObjectsOfType<RotatingObject>();
        foreach (RotatingObject rotator in allRotators)
        {
            // 跳过当前碰撞到的snowflake对象,其余对象全部关闭旋转开关
            if (rotator.gameObject != hitSnowflake)
            {
                rotator.canRotate = false;
            }
        }
    }
}

优化提示

  • 如果场景内除了这5个对象还有其他挂载RotatingObject的无关物体,可以提前把5个旋转对象拖到玩家脚本的数组成员里,不用FindObjectsOfType全局搜索,性能更高也不会误控其他对象
  • 旋转轴、旋转速度可以直接在脚本里修改对应参数适配项目需求
  • 如果后续需要恢复旋转,只要把对应对象的canRotate字段重新设为true即可

内容的提问来源于stack exchange,提问作者Mustafa Mert Sevim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 06:06:23