我使用parallaxing进行统一的2D游戏,基本上,只要相机移动(相机在角色后面向右或向左移动),我就会在x轴上移动背景的位置。我无法理解这条线的含义parallaxScales[i] = backgrounds[i].position.z * -1;
z位置与深度有什么关系?当你说position.z * -1或position.z * 5时它究竟是什么意思。它不影响我在游戏中使用的背景的实际深度(因为它们左右移动)。那究竟是什么意思呢。为什么要使用Z轴?
using UnityEngine;
using System.Collections;
public class Parallaxing : MonoBehaviour {
public Transform [] backgrounds;
private float [] parallaxScales;
public float smoothing = 1f;
private Transform cam;
private Vector3 previousCamPos;
void Awake ()
{
cam = Camera.main.transform;
}
void Start ()
{
previousCamPos = cam.position;
parallaxScales = new float[backgrounds.Length];
for (int i = 0; i < backgrounds.Length; i++)
{
parallaxScales[i] = backgrounds[i].position.z * -1;
}
}
void Update ()
{
for (int i = 0; i < backgrounds.Length; i++)
{
float parallax = (previousCamPos.x - cam.position.x) * parallaxScales[i];
float backgroundTargetPosX = backgrounds[i].position.x + parallax;
Vector3 backgroundTargetPos = new Vector3 (backgroundTargetPosX, backgrounds[i].position.y, backgrounds[i].position.z);
backgrounds[i].position = Vector3.Lerp (backgrounds[i].position, backgroundTargetPos, smoothing * Time.deltaTime);
}
previousCamPos = cam.position;
}
}
答案 0 :(得分:1)
此Parallaxing类使用背景的z值来控制应用于它们的视差量。例如z越高,相机移动时该背景的移动就越多。使用gameObjects Z值来控制视差是很方便的,因为它允许您在编辑器中轻松地看到将对每个对象应用多少视差,并且不需要将自定义脚本添加到每个对象。