【发布时间】:2015-04-27 12:32:38
【问题描述】:
好的,所以我相信这个概念应该很简单。然而,答案让我望而却步。编辑器背景。 “其他”对象和带有此代码的游戏对象都具有作为触发器的球体碰撞器,此游戏对象具有附加的 CharacterController 用于移动,但都没有刚体。我的目标是让这个(玩家对象,自动移动 PacMan 风格)杀死它遇到的东西,但前提是它面对它们,否则,它应该受到伤害。我的问题是弄清楚如何判断它是否面向对象。为了完成图片,moveDirection 可以是以下之一(Vector3.Up、.Down、.Left 或 .Right),因为玩家和 NPC 仅沿 X 和 Y 轴移动(带有 3D 游戏对象的正交相机)
~旧方法
void OnTriggerEnter (Collider other)
{
if (other.gameObject.tag == "Human") {
RaycastHit hit;
if (Physics.Raycast (transform.position, moveDirection, out hit)) {
StartCoroutine (eatWithBlood (1, other.gameObject.GetComponent<NPCController> ()));
} else {
TakeDamage (other.gameObject.GetComponent<NPCController> ().attack);
}
}
}
我也尝试了以下代码,效果更好一些。数学计算并不完全正确,所以即使角度在 45 到 -45 之间,玩家仍然会被“震惊”并受到伤害。如果我需要其他变量进行更准确的计算,新方法已预先配置为扩展。 faceDirection 变量是 up=0、right=1、down=2、left=3,它们也对应于它们的 Vector3.up、left、down 和 right 群组。
~新方法
void OnTriggerEnter (Collider other)
{
if (other.gameObject.tag == "Human") {
float angle = Vector3.Angle (transform.forward, other.gameObject.transform.position);
Debug.Log ("Angle: " + angle + "; my forward: " + faceDirection + "; other forward: " + other.gameObject.GetComponent<NPCController> ().faceDirection + " ... " + Time.time);
if (IAteHim (faceDirection, other.gameObject.GetComponent<NPCController> ().faceDirection, angle)) {
other.gameObject.GetComponent<NPCController> ().EatMe ();
StartCoroutine (eatWithBlood (1, other.gameObject.GetComponent<NPCController> ()));
} else {
GameObject poof = PoofPooler.poof.GetPooledObject ();
if (poof != null) {
poof.transform.position = Vector3.Lerp (transform.position, other.gameObject.transform.position, 0.5f);
poof.GetComponent<PoofControl> ().reactivated = true;
poof.SetActive (true);
}
other.gameObject.GetComponent<NPCController> ().MakeInvincible ();
TakeDamage (other.gameObject.GetComponent<NPCController> ().attack, 2.0f);
}
}
}
bool IAteHim (int myDirection, int otherDirection, float angle)
{
if (angle > -45 && angle < 45) { // I'm facing toward yummies
return true;
} else {
return false;
}
}
【问题讨论】:
标签: vector unity3d collision-detection euler-angles