Parallax.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /// <summary>
  2. /// Copyright (c) 2021 MirzkisD1Ex0 All rights reserved.
  3. /// Code Version 1.0
  4. /// </summary>
  5. using UnityEngine;
  6. using ToneTuneToolkit.Common;
  7. namespace ToneTuneToolkit.UI
  8. {
  9. /// <summary>
  10. /// 多层次视差
  11. /// </summary>
  12. public class Parallax : MonoBehaviour
  13. {
  14. public GameObject[] ParallaxGO; // 通常第一个为壁纸
  15. public float[] parallaxLevel = new float[] {
  16. 0.05f,
  17. 0.1f }; // 视差等级 // 数值越高偏移越大
  18. private Vector2 parallaxOffset = Vector2.zero;
  19. private Vector2 screenOffset = Vector2.zero;
  20. private Vector2[] specialOffset;
  21. private void Start()
  22. {
  23. if (this.ParallaxGO.Length == 0)
  24. {
  25. TipTools.Error("[Parallax] Cant find Parallax Object(s).");
  26. this.enabled = false;
  27. return;
  28. }
  29. for (int i = 0; i < this.ParallaxGO.Length; i++)
  30. {
  31. if (!this.ParallaxGO[i])
  32. {
  33. TipTools.Error("[Parallax] Parallax Object(s) missing.");
  34. this.enabled = false;
  35. return;
  36. }
  37. }
  38. this.Presetting();
  39. }
  40. private void Update()
  41. {
  42. this.ParallaxMethod();
  43. }
  44. private void Presetting()
  45. {
  46. this.screenOffset = new Vector2(Screen.width / 2, Screen.height / 2);
  47. this.specialOffset = new Vector2[this.ParallaxGO.Length];
  48. for (int i = 0; i < this.ParallaxGO.Length; i++)
  49. {
  50. this.specialOffset[i] = this.ParallaxGO[i].transform.localPosition;
  51. }
  52. this.ParallaxGO[0].transform.localScale = new Vector3(1.1f, 1.1f, 1.1f); // 背景图片增加至1.1倍
  53. return;
  54. }
  55. private void ParallaxMethod()
  56. {
  57. this.parallaxOffset.x = Input.mousePosition.x - this.screenOffset.x;
  58. this.parallaxOffset.y = Input.mousePosition.y - this.screenOffset.y;
  59. this.ParallaxGO[0].transform.localPosition = this.parallaxOffset * this.parallaxLevel[0] + this.specialOffset[0];
  60. this.ParallaxGO[1].transform.localPosition = this.parallaxOffset * this.parallaxLevel[1] + this.specialOffset[1];
  61. return;
  62. }
  63. }
  64. }