[英]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.