物体运动到某个地方自动销毁
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;
}
}
物体在某个点无限生成
思路:比较简单 就是创建一个空的坐标点,然后在脚本里加一个list, 把想要生成的物品放进去,然后使用unity写好的函数定时随机生成就可以了。
要用到的关键函数
// 在某个位置生成对象的函数,这是要用到的它的某一个重载
Instantiate((生成什么, 生成位置, 是否旋转, 父级位置));
//随机函数[first, last)
Random.Range(first, last)
//每一段时间循环函数
InvokeRepeating(循环对象的名称, 游戏开始后多久开始循环, 每多少秒执行一次);
创建空出生点
做几个我们要随机生成的物品:
我这里是三辆小汽车,默认以不同速度向前走。
写随机生成的脚本
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;
完成!