GameControl.cs
2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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;
}
}