miepzerino
2023-12-25 89c72b3b11cbfbd9a8f86abb418ae8ada3ee237b
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class ParallexEffect : MonoBehaviour
{
    public Camera cam;
    public Transform followTarget;
 
    // Starting position for the parallax game object
    Vector2 startingPosition;
 
    // Start Z value of the parallax game object
    float startingZ;
    // Start Y value of the parallax game object
    float startingY;
 
    Vector2 camMoveSinceStart => (Vector2) cam.transform.position - startingPosition;
 
    float zDistanceFromTarget => transform.position.z - followTarget.transform.position.z;
    float clippingPlane => (cam.transform.position.z + (zDistanceFromTarget > 0 ? cam.farClipPlane : cam.nearClipPlane));
 
    float parallaxFactor => Mathf.Abs(zDistanceFromTarget) / clippingPlane;
 
    // Start is called before the first frame update
    void Start()
    {
        startingPosition = transform.position;
        startingZ = transform.position.z;
        startingY = transform.position.y;
        
    }
 
    // Update is called once per frame
    void Update()
    {
 
        //Debug.Log("startingPos: " + startingPosition + ", camMoveSinceStart: " + camMoveSinceStart + ", parallaxFactor: " + parallaxFactor / 100);
        Vector2 newPosition = startingPosition + camMoveSinceStart * (parallaxFactor / 10);
 
        transform.position = new Vector3(newPosition.x, startingY, startingZ);
    }
}