オブジェクトは特定の場所に移動し、自動的に破壊されます
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveForward : MonoBehaviour
{
//向前运动的物体的基本速度
public float speed;
//记录起始坐标
private Vector2 startPos;
void Start()
{
startPos = transform.position;
}
void Update()
{
//距离超过10 自动销毁
if(Mathf.Abs(transform.position.x - startPos.x) > 20){
Destroy(this.gameObject);
}
Move();
}
//让车一直移动的函数
private void Move(){
transform.position += transform.right * speed * Time.deltaTime;
}
}
オブジェクトは特定のポイントで無限にスポーンします
アイデア: 空の座標点を作成し、スクリプトにリストを追加して生成するアイテムを入れ、unity で作成された関数を使用して一定間隔でランダムに生成するのは比較的簡単です。
使用
するキー機能
// 在某个位置生成对象的函数,这是要用到的它的某一个重载
Instantiate((生成什么, 生成位置, 是否旋转, 父级位置));
//随机函数[first, last)
Random.Range(first, last)
//每一段时间循环函数
InvokeRepeating(循环对象的名称, 游戏开始后多久开始循环, 每多少秒执行一次);
空のスポーン ポイントを作成する
ランダムに生成するアイテムをいくつか作成します。
ここには 3 台の車があり、デフォルトでは異なる速度で前進します。
ランダムに生成されたスクリプトを書く
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
//存想无限生成的东西
public List<GameObject> spawnObjects;
void Start()
{
//循环函数
InvokeRepeating(nameof(Spawn), 0.2f, Random.Range(5f, 10f));
}
private void Spawn() {
//随机我们指定的一堆物品的一个数 (随机[0, 数组长度)
int index = Random.Range(0, spawnObjects.Count);
//unity准备的随机生成函数 (生成什么,生成位置,是否旋转,父级位置)
Instantiate(spawnObjects[index], transform.position, Quaternion.identity, transform);
}
}
次に、生成したいものを、作成した空のオブジェクトに入れます。
DLC:下の赤い誕生点で生まれた車を反対方向に向ける
アイデア: 誕生点に方向パラメータを設定して、車のオブジェクトが反転しているかどうかを示します。車はこれを使用して方向を判断し、対応する方向の速度を与える必要があります。
移動オブジェクトのスクリプトを見てみましょう。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveForward : MonoBehaviour
{
//向前运动的物体的基本速度
public float speed;
//记录起始坐标
private Vector2 startPos;
//小车跑的方向
public int dir; //重点
void Start()
{
startPos = transform.position;
//动画是否翻转
transform.localScale = new Vector3(dir, 1, 1); //重点
}
void Update()
{
//距离超过10 自动销毁
if(Mathf.Abs(transform.position.x - startPos.x) > 20){
Destroy(this.gameObject);
}
Move();
}
//让车一直移动的函数
private void Move(){
transform.position += transform.right * speed * Time.deltaTime * dir; //重点
}
}
出生点をもう一度変更しましょう。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
//存想无限生成的东西
public List<GameObject> spawnObjects;
//控制生成方向
public int direction;
void Start()
{
//循环函数
InvokeRepeating(nameof(Spawn), 0.2f, Random.Range(5f, 10f));
}
private void Spawn() {
//随机我们指定的一堆物品的一个数 (随机[0, 数组长度)
int index = Random.Range(0, spawnObjects.Count);
//unity准备的随机生成函数 (生成什么,生成位置,是否旋转,父级位置) 重点
GameObject car = Instantiate(spawnObjects[index], transform.position, Quaternion.identity, transform);
//改变生成的汽车的运动方向 重点
car.GetComponent<MoveForward>().dir = direction;
}
}
反対方向に移動する出生点を -1 に調整し、もう一方の出生点を 1 に調整します。
終了!