-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParallaxing.cs
More file actions
57 lines (45 loc) · 2.37 KB
/
Parallaxing.cs
File metadata and controls
57 lines (45 loc) · 2.37 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
using UnityEngine;
using System.Collections;
public class Parallaxing : MonoBehaviour {
public Transform[] backgrounds; // Array (list) of all the back- and foregrounds to be parallaxed.
private float[] parallaxScales; // Proportion of the camera's movement to move the backgrounds by.
public float smoothing = 1f; // How smooth the parallax is going to be. Make sure to set this above 0.
private Transform cam; // Reference to the main camera's Transform.
private Vector3 previousCamPos; // Stores the position of the camera in the previous frame.
// Is called before Start(). Great for references between scripts and objects.
void Awake ()
{
// Set up the camera reference.
cam = Camera.main.transform;
}
// Use this for initialization
void Start ()
{
// The previous frame had the current frame's camera position.
previousCamPos = cam.position;
// Assigning corresponding parallexScales.
parallaxScales = new float[backgrounds.Length];
for (int i = 0; i < backgrounds.Length; i++)
{
parallaxScales[i] = backgrounds[i].position.z * -1;
}
}
// Update is called once per frame
void Update ()
{
// For each background
for (int i = 0; i < backgrounds.Length; i++)
{
// The parallax is the opposite of the camera movement because the previous frame is multiplied by the scale.
float parallax = (previousCamPos.x - cam.position.x) * parallaxScales[i];
// Set a target x position which is the current position + the parallax.
float backgroundTargetPosX = backgrounds[i].position.x + parallax;
// Create a target position which is the background's current position with its targets x-position.
Vector3 backgroundTargetPos = new Vector3(backgroundTargetPosX, backgrounds[i].position.y, backgrounds[i].position.z);
// Fade between current position and the target position with 'lerp'. deltaTime converts frames to seconds.
backgrounds[i].position = Vector3.Lerp(backgrounds[i].position, backgroundTargetPos, smoothing * Time.deltaTime);
}
// Set previousCamPos to the camera's position at the end of the frame.
previousCamPos = cam.position;
}
}