GameControl.cs 2.22 KB
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameControl : MonoBehaviour
{
    [SerializeField] private BackGroundSroll bg;
    [SerializeField] private SnakeControl snake;
    [SerializeField] private AngleReader angleReader;

    private float beforeAngle = 0;
    private float beforeTime = 0;

    public float speed = 1f;
    private float smoothVelocity;

    void Start()
    {
        if (angleReader != null)
        {
            // 先获取一下 触发器的初始角度
            beforeAngle = angleReader.GetAngle();
            beforeTime = DateTime.Now.Millisecond;
        }
    }

    void Update()
    {
        float curAngle;
        if (angleReader != null)
        {
            curAngle = angleReader.GetAngle();
            Debug.Log("当前角度:  " + curAngle);
            float angleDelta = GetAngleDelta(beforeAngle, curAngle);
            Debug.Log("转动角度:  " + angleDelta);
            float targetSpeed = CalculateTargetSpeed(angleDelta);
            targetSpeed = Mathf.SmoothDamp(
                bg.speedScale,
                targetSpeed,
                ref smoothVelocity,
                0.1f // 平滑时间(秒)
            );
            beforeAngle = curAngle;
            bg.speedScale = targetSpeed;
        }
    }

    /// <summary>
    /// 处理360°跳变的角度差值计算
    /// </summary>
    float GetAngleDelta(float oldAngle, float newAngle)
    {
        // 处理跨越360°到0°的情况
        float delta = newAngle - oldAngle;
        if (delta > 180f) delta -= 360f; // 正向跳变修正
        else if (delta < -180f) delta += 360f; // 反向跳变修正
        return delta;
    }

    /// <summary>
    /// 根据角度变化计算目标速度
    /// </summary>
    float CalculateTargetSpeed(float angleDelta)
    {
        // 当角度不在转动 速度倍率为0
        if (Mathf.Abs(angleDelta) <= 0.0001f)
        {
            return 0;
        }

        float inputRatio;
        if (Mathf.Abs(angleDelta) > 0.01f)
        {
            inputRatio = Mathf.Clamp(Mathf.Abs(angleDelta) / 90f, 0.1f, 1f);
            return 1f + inputRatio * 99f * 2;
        }

        return 2;
    }
}