UnityProjekt/Assets/Scripts/Parallaxing.cs
NorbiPeti cbabc6e6a2
Jumping animation without sprinting as well
State of the code before and after presentation
2020-11-20 15:34:20 +01:00

47 lines
No EOL
1.5 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Parallaxing : MonoBehaviour
{
private Transform _background;
private float _parallaxScale;
public float smoothing = 1f;
private Transform _cam;
private Vector3 _previousCamPos;
// Is called before Start(). Great for references.
void Awake () {
_cam = Camera.main.transform;
_background = transform;
}
// Start is called before the first frame update
void Start()
{
_previousCamPos = _cam.position;
_parallaxScale = _background.position.z * -1;
}
// Update is called once per frame
void Update()
{
// the parallax is the opposite of the camera movement because the previous frame multiplied by the scale
float parallax = (_previousCamPos.x - _cam.position.x) * _parallaxScale;
// set a target x position which is the current position plus the parallax
var position = _background.position;
float backgroundTargetPosX = position.x + parallax;
// create a target position which is the background's current position with it's target x position
Vector3 backgroundTargetPos = new Vector3(backgroundTargetPosX, position.y, position.z);
// fade between current position and the target position using lerp
position = Vector3.Lerp(position, backgroundTargetPos, smoothing * Time.deltaTime);
_background.position = position;
// set the previousCamPos to the camera's position at the end of the frame
_previousCamPos = _cam.position;
}
}