我花了约一个小时的时间研究如何在Unity3d中制作NPC“排斥”(即从玩家处逃离)。无论我在哪里搜索,都会找到大量关于如何让NPC朝着玩家奔跑的内容,但从未涉及排斥。因为我是游戏开发新手,所以不知道怎么做。
我花了约一个小时的时间研究如何在Unity3d中制作NPC“排斥”(即从玩家处逃离)。无论我在哪里搜索,都会找到大量关于如何让NPC朝着玩家奔跑的内容,但从未涉及排斥。因为我是游戏开发新手,所以不知道怎么做。
获取玩家和NPC的Vector3位置,然后进行以下计算:
Vector3 direction = NPCPosition - playerPosition;
direction.y = 0;
direction = Vector3.Normalize(direction);
NPCTransform.rotation = Quaternion.Euler(direction);
//MOVE NPC forward (the calculations above calculate the direction away from the player)
NPCTransform.Translate(NPCTransform.position + (transform.forward * NPCSpeed));
在这个答案中,我会尽力解释我写的代码。
向量只是浮点数数组。Vector2 包含两个浮点数,Vector3 包含三个浮点数……在 Unity 中,Vector3 用于位置和方向。
第一行:
Vector3 direction = NPCPosition - playerPosition;
在第二行中,
direction.y = 0;
direction = Vector3.Normalize(direction);
NPCTransform.rotation = Quaternion.Euler(direction);
NPCTransform.Translate(transform.forward * NPCSpeed);
在Unity中有很多移动物体的方法。 如果你想让NPC有重力(以防他从某个地方掉下来,而不是漂浮在空中:D),你应该给NPC添加一个刚体并勾选“使用重力”。 在这种情况下,最后一行将会像这样,而不是NPCTransform.Translate(transform.forward * NPCSpeed):
NPCRigidbody.AddForce(direction * NPCSpeed);
NPCTransform.Translate(...);
translate方法将转换(在我们的情况下是NPC对象)移动到给定的位置。那么,我们在该方法中传递了什么?
我们传入了这个:
transform.forward * NPCSpeed
因为这个方法移动对象的位置,所以我们添加了transform.forward * NPCSpeed。在这里,我们只需取方向并将其乘以我们想要NPC移动的速度(速度是一个数字,通常是浮点数)。
因此,如果您要使用转换移动NPC,则代码将如下所示:
Vector3 direction = NPCPosition - playerPosition;
direction.y = 0;
direction = Vector3.Normalize(direction);
NPCTransform.rotation = Quaternion.Euler(direction);
NPCTransform.Translate(transform.forward * NPCSpeed);
如果您使用Rigidbody来移动NPC,就像这样:
Vector3 direction = NPCPosition - playerPosition;
direction.y = 0;
direction = Vector3.Normalize(direction);
NPCTransform.rotation = Quaternion.Euler(direction);
NPCRigidbody.AddForce(direction * NPCSpeed);