unity3d - 如何在unity2D中移动相机的一侧添加产卵器
问题描述
我正在 Unity2D 中创建一个 2D 赛车游戏,并且不确定如何为我的生成器编码对象,例如在我的移动相机右侧的加电、奖励和障碍物。摄像机跟随我的车辆并从左向右移动。当前对象在游戏中生成,但仅在一个点上生成,并在相机滚动过去时继续在同一点生成。抱歉,如果答案很简单。
以下是我使用的脚本:
coin.cs 附在我的硬币预制件上
public class coin : MonoBehaviour
{
public Camera mainCamera;
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
mainCamera = GameObject.FindObjectOfType<Camera>();
rb = this.gameObject.GetComponent<Rigidbody2D>();
transform.position = new Vector2(mainCamera.pixelWidth / 32, getRandomHeight());
}
float getRandomHeight(){
return Random.Range(-(mainCamera.pixelHeight / 2) / 100, (mainCamera.pixelHeight / 2) / 100);
}
private void OnTriggerEnter(Collider coll){
if (coll.gameObject.tag == "Player"){
Destroy(this.gameObject);
}
}
// Update is called once per frame
void Update()
{}
}
并且 coinSpawner.cs 附加到场景中的游戏对象
public class coinSpawner : MonoBehaviour
{
float LastSpawnTime = -500f;
float NextSpawnTime = 3;
public Object CoinPrefab; // declare coinPrefab
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Time.time - LastSpawnTime > NextSpawnTime)
{
NextSpawnTime = Random.Range(3, 10);
LastSpawnTime = Time.time;
Instantiate(CoinPrefab);
}
}
解决方案
Instantiate(CoinPrefab);
在没有任何位置或父对象信息的情况下生成此对象。这将始终在场景根和0,0,0
.
那么这一行
transform.position = new Vector2(mainCamera.pixelWidth / 32, getRandomHeight());
incoin
始终将其放置在绝对位置,具体取决于您pixelWidth
不会随时间变化的位置。
你说的Camera
是移动,所以你应该考虑到它transform.position
。
您基本上有两(三)种方式可以去这里:
您可以使生成器成为
GameObject
您的子级Camera
- 因此它会自动随之移动 - 并将其向右移动以获得所需的偏移量。然后简单地在这个 GameObjects 位置生成新对象。然后你可以这样做coinSpawner
:Instantiate(CoinPrefab, transform.position, Quaternion.Identity);
或获取
Camera
参考并使用它的位置+所需的偏移量,也只能在coinSpawner
类似// reference this already via the Inspector if possible [SerializeField] Camera _camera; // Otherwise get the reference on runtime void Awake() { if(!_camera)_camera = Camera.main; } float getRandomHeight => Random.Range(-(_camera.pixelHeight / 2) / 100, (_camera.pixelHeight / 2) / 100;
然后做类似的事情
Instantiate(CoinPrefab, new Vector2(_camera.transform.position.x + mainCamera.pixelWidth / 32, getRandomHeight()), Quaternion.Identity);
这实际上会更有效,因为整个
coin
脚本将被简化为仅OnTriggerEnter
部分而不是每个硬币都会使用FindObjectOfType
和GetComponent
生成时。基本上与上面相同,但坚持你的代码结构只是做
transform.position = new Vector2(mainCamera.transform.position.x + mainCamera.pixelWidth / 32, getRandomHeight());
我不会这样做,但由于如上所述的效率。
推荐阅读
- amazon-web-services - 使用 Terraform 的 Provisioner 升级 Kubernetes 集群
- r - 对 R 中的因子没有意义
- dart - UInt8List 中的 Int16 不可读,转换为字节数组时数据错误
- java - LockSupport.park 方法是否会释放监视器上的锁定以保护关键系统资源?
- java - 将对象存储在时间表中
- node.js - React Native 错误:您当前正在使用 Redux 在 NODE_ENV === 'production' 之外使用缩小代码
- python - 这三种解决方案的时间复杂度是多少?
- python - 如何将已安装的软件包移动到新创建的虚拟环境?
- firebase - Firestore 数据上的嵌套 v-for 循环反应性地复制最深层的更改
- css - 使网格或弹性框中的项目每行具有相等的动态列数