CangJie/Assets/Scripts//Parallax.cs

60 lines
1.9 KiB
C#
Raw Normal View History

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Sirenix.OdinInspector;
using Cinemachine;
/*
2021.7.24
使Cam
*/
//视差类,霄酱写的🤔
[ExecuteAlways]
public class Parallax : MonoBehaviour
{
2022-03-20 23:28:11 +08:00
private Transform Cam;//视差摄像机
[Header("代表水平方向上、随着相机运动的倍率。")]
public float moveRate;//视差率
[Header("有时候视差起点会被不可抗力污染,当场景的东西位置乱了,就手动处理一下这个值吧")]
public float startPoint;//起点,自动获取
// Start is called before the first frame update
void Start()
{
2022-03-20 23:28:11 +08:00
Cam = GameObject.FindGameObjectWithTag("MainCamera").transform;
//startPoint = transform.position.x;//获取当前起点位置
//startPoint = transform.localPosition.x;//获取当前起点位置
}
void TheUpdate()
{
if(Cam == null)
{
2022-03-20 23:28:11 +08:00
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();
}
}