2D游戏入门——小狐狸系列(二十四)通过控制不同物体的移动速度实现视觉差效果

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

image-20211106102923873

将环境中的树调成0.2

image-20211106103005657

这样背景图就比树移动的快,而都比主相机慢,就有视觉差效果了。

上面的脚本只实现了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轴方向的移动。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值