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
isRotatingresets 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:
- Attach this script to your target object.
- Adjust
delayBetweenRotationin the Inspector to control rotation speed (smaller values = faster step rotations). - Toggle the
isRotatingproperty via code (e.g., from a UI button click event) to start/stop rotation.
内容的提问来源于stack exchange,提问作者Aditya
相关产品推荐
相关产品推荐

