Session24:视觉差Parallax
其实就是通过背景物体的不同移动速度来实现视觉差效果。
public class Parallax : MonoBehaviour
{
public Transform cam;
public float moveRate;
private float startPoint;
// Start is called before the first frame update
void Start()
{
startPoint = transform.position.x;
}
// Update is called once per frame
void Update()
{
transform.position = new Vector2(startPoint + cam.position.x * moveRate, transform.position.y);
}
}
然后将Parallax这个脚本拖到想要实现视觉差的物体身上,把主相机拖进去,调整移动速率即可。
比如将背景调成0.5
将环境中的树调成0.2
这样背景图就比树移动的快,而都比主相机慢,就有视觉差效果了。
上面的脚本只实现了x轴方向的视觉差效果,那么如果y轴也需要的话怎么办呢,需要添加一个判断条件
public class Parallax : MonoBehaviour
{
public Transform cam;
public float moveRate;
public bool lockY;
private float startPointX, startPointY;
// Start is called before the first frame update
void Start()
{
startPointX = transform.position.x;
startPointY = transform.position.y;
}
// Update is called once per frame
void Update()
{
if (lockY)
transform.position = new Vector2(startPointX + cam.position.x * moveRate, transform.position.y);
else
transform.position = new Vector2(startPointX + cam.position.x * moveRate, startPointY + cam.position.y * moveRate);
}
}
如果把lockY勾选的话,就只有x轴方向的移动。