HeavenStudioPlus/Assets/Scripts/Common/Parallax.cs

57 lines
1.8 KiB
C#
Raw Normal View History

2022-01-30 23:40:12 +00:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
2022-03-14 14:21:05 +00:00
namespace HeavenStudio.Common
2022-01-30 23:40:12 +00:00
{
public class Parallax : MonoBehaviour
{
[SerializeField]
private Vector2 parallaxEffectMultiplier;
private Transform camTransform;
private Vector3 lastCamPos;
public float textureUnitSizeX;
2022-02-03 08:25:27 +00:00
public Camera cam;
2022-01-30 23:40:12 +00:00
public bool sprite = true;
2022-02-03 08:25:27 +00:00
private void Awake()
{
if (cam == null)
cam = Camera.main;
}
2022-01-30 23:40:12 +00:00
private void Start()
{
2022-02-03 08:25:27 +00:00
camTransform = cam.transform;
2022-01-30 23:40:12 +00:00
lastCamPos = camTransform.position;
/*if (sprite)
{
Sprite sprite = GetComponent<SpriteRenderer>().sprite;
Texture2D texture = sprite.texture;
textureUnitSizeX = texture.width / sprite.pixelsPerUnit;
}
else
{
Image image = GetComponent<Image>();
Texture texture = image.mainTexture;
textureUnitSizeX = texture.width / image.pixelsPerUnit;
}*/
}
private void LateUpdate()
{
Vector3 deltaMovement = camTransform.position - lastCamPos;
transform.position += new Vector3(deltaMovement.x * parallaxEffectMultiplier.x, deltaMovement.y * parallaxEffectMultiplier.y, 0);
lastCamPos = camTransform.position;
if (Mathf.Abs(camTransform.position.x - transform.position.x) >= textureUnitSizeX)
{
float offsetPosX = (camTransform.position.x - transform.position.x) % textureUnitSizeX;
transform.position = new Vector3(camTransform.position.x + offsetPosX, transform.position.y);
}
}
}
}