【发布时间】:2017-11-22 22:50:17
【问题描述】:
我正在开发一款 2D 飞机躲避游戏,但在 Unity 5 中遇到了问题,我试图阻止两架来袭飞机之间的碰撞,我尝试了许多不同的解决方案,但都不起作用。我不能将它们放在不同的层中,因为它们仍然需要与玩家发生碰撞。这是我第一架飞机的代码。敌人和子弹都是标签。谢谢
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletPlane : MonoBehaviour {
public float speed = 6f;
public float reloadTime = 1f;
public GameObject bulletPrefab;
public GameObject explosion;
public GameObject smoke;
public GameObject warning;
public GameObject self;
public float reloadSecond = .10f;
private float elapsedTime = 0;
public float timeElapsed = 0;
private Rigidbody2D rigidBody;
void Start()
{
rigidBody = GetComponent<Rigidbody2D> ();
rigidBody.velocity = new Vector2 (0, speed);
Vector3 warningPos = transform.position;
warningPos += new Vector3 (0, -10.5f, 0);
Instantiate (warning, warningPos, Quaternion.identity);
}
void Update() {
elapsedTime++;
Vector3 spawnPos = transform.position;
Vector3 secondPos = transform.position;
elapsedTime = 0f;
spawnPos += new Vector3 (0, -1.2f, 0);
secondPos += new Vector3 (-1, -0.9f, 0);
Instantiate (bulletPrefab, spawnPos, Quaternion.identity);
Instantiate (smoke, secondPos, Quaternion.identity);
if (elapsedTime > reloadSecond) {
spawnPos += new Vector3 (0, -1.2f, 0);
secondPos += new Vector3 (-1, -0.9f, 0);
Instantiate (bulletPrefab, spawnPos, Quaternion.identity);
Instantiate (smoke, secondPos, Quaternion.identity);
elapsedTime = 0f;
timeElapsed++;
}
}
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.CompareTag ("Player")) {
Destroy (other.gameObject);
} else if (other.gameObject.CompareTag ("Enemy")) {
Physics2D.IgnoreCollision (other.GetComponent<Collider2D> (), gameObject.GetComponent<Collider2D> (), true);
} else if (other.gameObject.CompareTag ("Bullets")) {
Physics2D.IgnoreCollision (other.GetComponent<Collider2D> (), gameObject.GetComponent<Collider2D> (), true);
}
}
}
这是另一架敌机的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyPlane : MonoBehaviour {
public float speed = -6f;
public float reloadTime = 1f;
public GameObject bulletPrefab;
public GameObject explosion;
private float elapsedTime = 0;
private Rigidbody2D rigidBody;
void Start()
{
rigidBody = GetComponent<Rigidbody2D> ();
rigidBody.velocity = new Vector2 (0, speed);
}
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.CompareTag ("Ally")) {
} else if (other.gameObject.CompareTag ("Enemy")) {
Physics2D.IgnoreCollision (other.GetComponent<Collider2D> (), gameObject.GetComponent<Collider2D> (), true);
} else if (other.gameObject.CompareTag ("BulletPlane")) {
Physics2D.IgnoreCollision (other.GetComponent<Collider2D> (), gameObject.GetComponent<Collider2D> (), true);
}
}
}
【问题讨论】:
-
编辑 -> 项目设置 -> Physics2D。在此设置面板(底部)中,您可以将图层默认设置为非碰撞。
-
@Draco18s 这不起作用,因为我仍然需要它们与播放器发生碰撞
-
...这就是碰撞网格的用途...您可以将平面图层设置为不与自身或您想要的任何其他图层碰撞,但仍与播放器层。
标签: unity3d c#-4.0 unity5 collision-detection