本文实例为大家分享了Unity实现简单场景分层移动的具体代码,供大家参考,具体内容如下
前言
开发游戏经常需要用到把前景、场景、背景等不同层级的物体进行不同速度的移动以实现真实感。
效果
云、建筑、地面、前景植被各层次场景分层移动。
代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
using UnityEngine; public class DistantView : MonoBehaviour { public GameObject follow; public float scaleOffset; public bool isHorizontal = true ; public bool isVertical = true ; Vector2 pos; Vector2 followPos; float offsetX; float offsetY; private void Start() { if (follow != null ) followPos = follow.transform.localPosition; } void LateUpdate() { if (follow!= null ) { pos = transform.localPosition; if (isHorizontal) { offsetX = (follow.transform.localPosition.x - followPos.x) * scaleOffset; pos.x += offsetX; } if (isVertical) { pos.y += offsetY; offsetY = (follow.transform.localPosition.y - followPos.y) * scaleOffset; } transform.localPosition = pos; followPos = follow.transform.localPosition; } } } |
用法
将不同层级的物体放入不同的父物体下分别管理。
给每个父物体挂上脚本。
Follow为跟随的基准对象。(比如玩家,相机等)
ScaleOffset为移动速率,1为和目标移速一致,越小越慢,越大越快。0为不移动,负值为反向移动。(前景可能要用到负值)
Hor和Ver为跟随哪个轴。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_39162826/article/details/118723153