簡體   English   中英

改變障礙腳本統一的方向

[英]Change direction of obstacles script unity

我正在嘗試將此腳本中障礙物的方向從水平穿過屏幕更改為垂直穿過屏幕。 這是腳本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

    public class ObSpawn : MonoBehaviour
    {
        public GameObject asteroidPrefab;
        public float respawnTime = 1.0f;
        private Vector2 screenBounds;
    
        // Use this for initialization
        void Start()
        {
            screenBounds = Camera.main.ViewportToWorldPoint(
            new Vector3(0f, 0f, -Camera.main.transform.position.z));
            StartCoroutine(asteroidWave());
        }
        private void spawnEnemy()
        {
            GameObject a = Instantiate(asteroidPrefab) as GameObject;
            a.transform.position = new Vector2(screenBounds.y * -2, Random.Range(-screenBounds.y * -1, screenBounds.y * -1));
        }
        IEnumerator asteroidWave()
        {
            while (true)
            {
                yield return new WaitForSeconds(respawnTime);
                spawnEnemy();
            }
        }
    }

我不知道如何改變方向。 這是我從中獲取腳本的網站; 代碼有點不同,因為它最初並沒有按照我想要的方式工作。 https://pressstart.vip/tutorials/2018/09/25/58/spawning-obstacles.html希望大家幫忙

正如評論中提到的,問題中的代碼涵蓋了產卵而不是移動。 這是根據鏈接中的代碼嘗試回答您的預期問題的嘗試。 請注意,您使用的代碼要求相機固定在 x=0、y=0。

SpawnEnemy()中,更改:

    a.transform.position = new Vector2(screenBounds.y * -2, Random.Range(-screenBounds.y * -1, screenBounds.y * -1));

到:

    a.transform.position = new Vector2( Random.Range(screenBounds.x, -screenBounds.x), screenBounds.y * -2 );

然后假設您的代碼與教程鏈接中的代碼相同,小行星上的 Start() 更改:

    rb.velocity = new Vector2(-speed, 0);
    screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));

到:

    rb.velocity = new Vector2(0, -speed);
    screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(0, 0, -Camera.main.transform.position.z));

( screenBounds 更改是為了與您的其他代碼保持一致)。

Update ()中對小行星進行更改:

    if(transform.position.x < screenBounds.x * 2){
        Destroy(this.gameObject);
    }

到:

    if(transform.position.y < screenBounds.y){
        Destroy(this.gameObject);
    }

如果你想同時擁有垂直和水平移動的障礙物,那就是另一回事了。

假設教程視頻解釋了所使用的概念,我真的建議重新觀看它並嘗試了解實際做了什么以及為什么。 我有點后悔現在把它打出來,因為它避免了根本問題,但希望能夠比較各種版本會對你有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM