CangJie/Assets/Scripts//Parallax.cs
2022-03-20 23:28:11 +08:00

60 lines
1.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Sirenix.OdinInspector;
using Cinemachine;
/*
更新日期2021.7.24 视差类
使用方式将类挂载到需要视差的背景上将主摄像机赋值给Cam调节视差率即可
注意 移动的背景一定要比不移动的面积大
*/
//视差类,霄酱写的🤔
[ExecuteAlways]
public class Parallax : MonoBehaviour
{
private Transform Cam;//视差摄像机
[Header("代表水平方向上、随着相机运动的倍率。")]
public float moveRate;//视差率
[Header("有时候视差起点会被不可抗力污染,当场景的东西位置乱了,就手动处理一下这个值吧")]
public float startPoint;//起点,自动获取
// Start is called before the first frame update
void Start()
{
Cam = GameObject.FindGameObjectWithTag("MainCamera").transform;
//startPoint = transform.position.x;//获取当前起点位置
//startPoint = transform.localPosition.x;//获取当前起点位置
}
void TheUpdate()
{
if(Cam == null)
{
Cam = GameObject.FindGameObjectWithTag("MainCamera").transform;
//Debug.LogError("视差摄像机未赋值,把主摄像机赋值给Cam就行");
//return;
}
//每帧更新位置
//transform.position = new Vector2(startPoint + Cam.position.x * moveRate, transform.position.y);
transform.localPosition = new Vector2(startPoint + Cam.position.x * moveRate, transform.position.y);
}
//为了解决Updata矛盾使用了以下代码
private void OnEnable()
{
CinemachineCore.CameraUpdatedEvent.AddListener(CameraUpdate);
}
private void OnDisable()
{
CinemachineCore.CameraUpdatedEvent.RemoveListener(CameraUpdate);
}
private void CameraUpdate(CinemachineBrain arg0)
{
TheUpdate();
}
}