我制作了一个经典的陷阱,两面墙聚集在一起粉碎玩家。为此,我创建了两个单独的标签," Crush"和" Crush1",并为每面墙分配一个标签。这是我的播放器类中的代码:
void OnCollisionEnter(Collision other)
{
if (other.transform.tag == "Crush" && other.transform.tag == "Crush1")
{
Die ();
}
}
如果两个墙壁同时触碰到玩家,我只希望玩家被摧毁。当我删除参数中的一个标签时,该方法工作正常(只有我不想要的方式)。我确定这里有一个简单的解决方法,我只是没有看到它。谢谢你的帮助!
答案 0 :(得分:2)
@Christiopher G说你需要在他们击中你时存放旗帜(并且不再打你),这是正确的。
我觉得他有点臃肿,但由于不需要新课程,你现在的代码很容易扩展到你想做的事情。
注意:Unity目前无法进行此类未经测试。
bool wall1 = false;
bool wall2 = false;
void Update()
{
if( wall1 && wall2 )
{
Die();
}
}
void OnCollisionEnter(Collision other)
{
if (other.transform.tag == "Crush")
{
wall1 = true;
}
else if(other.transform.tag == "Crush1")
{
wall2 = true;
}
}
void OnCollisionExit(Collision other)
{
if (other.transform.tag == "Crush")
{
wall1 = false;
}
else if(other.transform.tag == "Crush1")
{
wall2 = false;
}
}
答案 1 :(得分:0)
您可以做的是使用以下代码创建一个脚本并将其附加到您的Wall对象:
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.js"></script>
<select style="width: 200px">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
然后在播放器脚本中执行以下操作:
public class WallScript : MonoBehaviour
{
[HideInInspector] //Optional Attribute
public bool collidedWithPlayer;
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.name == "Player")
{
collidedWithPlayer = true;
}
}
private void OnCollisionExit(Collision collision)
{
if(collision.gameObject.name == "Player")
{
collidedWithPlayer = false;
}
}
//We don't want "collidedwithPlayer" to remain true if either of the walls touches the player before both do so we call "OnCollisionExit" to set it to false.
}
OR
private WallScript wall1Script;
private WallScript wall2Script;
private void Awake()
{
wall1Script = GameObject.Find("Wall1").GetComponent<WallScript>();
wall2Script = GameObject.Find("Wall2").GetComponent<WallScript>();
}
然后在同一个脚本中:
private WallScript wall1Script;
private WallScript wall2Script
public GameObject wall1;
public GameObject wall2; //Assign GameObjects in Inspector
private void Awake()
{
wall1Script = wall1.GetComponent<WallScript>();
wall2Script = wall2.GetComponent<WallScript>();
}
答案 2 :(得分:0)
你知道,当玩家碰到两面墙时。
函数OnCollisionEnter
将执行两次。
第一次,other.transform.tag == "Crush"
是真的。
第二次,other.transform.tag == "Crush1"
是真的。
在OnCollisionEnter
中,other
只有一个标记。
tag == tag1 && tag == tag2
tag1 != tag2