移动实例化对象
本文关键字:对象 实例化 移动 | 更新日期: 2023-09-27 18:19:07
我正在制作一个简单的游戏作为学习c#的手段。然而,我遇到了生成多个敌人的问题。
首先,克隆的敌人不会向下移动屏幕。其次,如果敌人相互碰撞,就会产生新敌人的无限循环。我弄清楚了运动问题的一部分,我需要在Unity内的克隆上启用脚本,但我不确定如何"正确"修复它(即非手动)。
以下是敌人的脚本:using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
public Transform TS;
public float minSpeed = 3f, maxSpeed = 8f, currentSpeed;
public float llocation = -9.15f, rlocation = 9.15f, ylocation = 7.65f; //Above visible screen
// Use this for initialization
void Start () {
TS = transform; //Cache Transform.
currentSpeed = Random.Range(minSpeed, maxSpeed); //Randomize enemy speed;
TS.position = new Vector3 (Random.Range (llocation, rlocation), ylocation, 0); //Randomize enemy spawn point.
}
// Update is called once per frame
void Update () {
TS.position += (Vector3.down * currentSpeed * Time.deltaTime); //Bring enemy down the screen.
if (TS.position.y < -5.35f) {
TS.position = new Vector3 (Random.Range (llocation, rlocation), ylocation, 0);
currentSpeed = Random.Range(minSpeed, maxSpeed);
} //end new spawnpoint and speed.
}
void OnTriggerEnter(Collider collider)
{
if (collider.CompareTag("Laser") || collider.CompareTag("Player")) { //Tag is name of prefab.
//When the laser hits the enemy, destroy the enemy.
Destroy(this.gameObject);
}
if (Player.score < 500 || Player.playerLives >= 1) {
for (int enemies = 0; enemies < 3; enemies++) {
print("Enemies: " + enemies);
Vector3 nposition = new Vector3 (Random.Range (llocation, rlocation), ylocation, 0);
Instantiate(this, nposition, Quaternion.identity);
//TS.position += (Vector3.down * currentSpeed * Time.deltaTime);
}
}
}
}
为函数"OnTriggerEnter"尝试下面的代码:
void OnTriggerEnter(Collider collider)
{
if (collider.CompareTag("Laser") || collider.CompareTag("Player")) { //Tag is name of prefab.
//When the laser hits the enemy, destroy the enemy.
Destroy(this.gameObject);
}
if(collider.CompareTag("Enemy")) {
if (Player.score < 500 || Player.playerLives >= 1) {
for (int enemies = 0; enemies < 3; enemies++) {
print("Enemies: " + enemies);
Vector3 nposition = new Vector3 (Random.Range (llocation, rlocation), ylocation, 0);
Instantiate(gameObject, nposition, Quaternion.identity);
//TS.position += (Vector3.down * currentSpeed * Time.deltaTime);
}
}
}
}