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

Unity中GameObject按22.5°Z轴步进旋转的控制异常问题

Unity: Fixed Step Rotation with Toggle Control

Here's a solution that eliminates the extra unwanted rotation when disabling the toggle, while keeping your desired fixed-step rotation behavior:

using UnityEngine;

public class StepRotation : MonoBehaviour
{
    // Fixed rotation step (22.5 degrees as requested)
    [SerializeField] private float rotationStep = 22.5f;
    // Delay between each rotation step (controls rotation speed indirectly)
    [SerializeField] private float delayBetweenRotation = 1f;
    
    // Toggle property to enable/disable rotation
    private bool _isRotating;
    public bool isRotating
    {
        get => _isRotating;
        set
        {
            // Reset timer immediately when turning off rotation
            if (!value && _isRotating)
            {
                _rotationTimer = 0f;
            }
            _isRotating = value;
        }
    }

    private float _rotationTimer;

    void Update()
    {
        // Only run rotation logic if enabled
        if (isRotating)
        {
            _rotationTimer += Time.deltaTime;

            // Trigger rotation when delay threshold is reached
            if (_rotationTimer >= delayBetweenRotation)
            {
                transform.Rotate(0f, 0f, rotationStep);
                _rotationTimer = 0f; // Reset timer for next step
            }
        }
    }
}

Key Fixes & Details:

  • Toggle Property with Timer Reset: Using a property instead of a public field ensures the timer resets the moment rotation is disabled. This stops any pending rotation from triggering after the toggle is turned off.
  • Isolated Timer Logic: The timer only accumulates time when rotation is enabled. No unnecessary time counting when rotation is off, which prevents accidental immediate rotations if you re-enable the toggle later.
  • Immediate Stop: Disabling isRotating resets the timer instantly, so even if the timer was close to the delay threshold, it won't trigger an extra rotation in the next frame.

How to Use:

  1. Attach this script to your target object.
  2. Adjust delayBetweenRotation in the Inspector to control rotation speed (smaller values = faster step rotations).
  3. Toggle the isRotating property via code (e.g., from a UI button click event) to start/stop rotation.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:47:11