首页 > 解决方案 > 如何在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);
    }
}

标签: unity3d

解决方案


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部分而不是每个硬币都会使用FindObjectOfTypeGetComponent生成时。

  • 基本上与上面相同,但坚持你的代码结构只是做

    transform.position = new Vector2(mainCamera.transform.position.x + mainCamera.pixelWidth / 32, getRandomHeight());
    

    我不会这样做,但由于如上所述的效率。


推荐阅读