如何随机 spawn/instantiate 一个物体在游戏中随处可见? C#
how to randomly spawn/instantiate an object everywhere in game? c#
所以我要练习在 2D c# 中制作一个捕捉对象的游戏,我想用我的玩家对象捕捉掉落的物体。所以我所做的是创建一个空的游戏对象并向其添加一个可以产生坠落物体的脚本,问题是我不知道如何每 2 - 3 秒左右在随机位置产生它。
这是我的代码和游戏视图。
public class spawnball : MonoBehaviour {
public GameObject ballprefab;
GameObject ballclone;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) {
spawn ();
Destroy (ballclone,3);
}
}
void spawn()
{
ballclone = Instantiate (ballprefab,transform.position,Quaternion.identity)as GameObject;
}
}
在我希望它随机生成的线上方
到目前为止你已经掌握了基本概念。
第一步是开始使用 Time.deltaTime
这样您就可以算出自从我们上次生成球以来已经过去了多长时间。
例如:
private timeSinceLastDrop: float;
private dropInterval: float = 3f;
void Update(){
// have we surpassed our interval?
if(timeSinceLastDrop >= dropInterval){
this.spawn();
timeSinceLastDrop = 0;
}
else
timeSinceLastDrop += Time.deltaTime;
}
为了满足第二个丢到哪里的问题,可以用Random.Range(min, max)
,然后用min和max作为最外层的参数可以丢
例如:
void spawn(){
ballclone = Instantiate(ballprefab,transform.position,Quaternion.identity)as GameObject;
ballclone.transform.position.x += Random.Range(-10f, 10f);
}
我在没有 IDE 的情况下写了这篇文章,所以那里可能有语法错误。
所以我要练习在 2D c# 中制作一个捕捉对象的游戏,我想用我的玩家对象捕捉掉落的物体。所以我所做的是创建一个空的游戏对象并向其添加一个可以产生坠落物体的脚本,问题是我不知道如何每 2 - 3 秒左右在随机位置产生它。
这是我的代码和游戏视图。
public class spawnball : MonoBehaviour {
public GameObject ballprefab;
GameObject ballclone;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) {
spawn ();
Destroy (ballclone,3);
}
}
void spawn()
{
ballclone = Instantiate (ballprefab,transform.position,Quaternion.identity)as GameObject;
}
}
在我希望它随机生成的线上方
到目前为止你已经掌握了基本概念。
第一步是开始使用 Time.deltaTime
这样您就可以算出自从我们上次生成球以来已经过去了多长时间。
例如:
private timeSinceLastDrop: float;
private dropInterval: float = 3f;
void Update(){
// have we surpassed our interval?
if(timeSinceLastDrop >= dropInterval){
this.spawn();
timeSinceLastDrop = 0;
}
else
timeSinceLastDrop += Time.deltaTime;
}
为了满足第二个丢到哪里的问题,可以用Random.Range(min, max)
,然后用min和max作为最外层的参数可以丢
例如:
void spawn(){
ballclone = Instantiate(ballprefab,transform.position,Quaternion.identity)as GameObject;
ballclone.transform.position.x += Random.Range(-10f, 10f);
}
我在没有 IDE 的情况下写了这篇文章,所以那里可能有语法错误。