【发布时间】:2016-03-04 09:33:49
【问题描述】:
我正在尝试构建一个游戏,其中 AI 需要不断远离玩家并不断收集地图上随机生成的收藏品。如何让它朝向新生成的收藏对象旋转?
玩家和对手都需要特殊移动,如下代码所示..
if (touch.position.x < Screen.width / 2 && touch.position.y < Screen.height / 2) {
Player.Rotate (0, 0, 5);
}
if (touch.position.x > Screen.width / 2 && touch.position.y < Screen.height / 2) {
Player.Rotate (0, 0, 5);
}
对手也根据旋转角度不断向前移动,因此只需将对手旋转到正确的方向
void Update(){
transform.position += transform.up * Time.deltaTime * EnemySpeed;
}
这是我让对手 AI 找到收藏品的位置并朝它旋转的代码
void AIControls ()
{
if (GameManager.Instance.CollectibleReady) {
//rotate towards collectible Item
Vector3 opponentPos = transform.position;
foodPos.x = foodPos.x - opponentPos.x;
foodPos.y = foodPos.y - opponentPos.y;
angle = Mathf.Atan2 (foodPos.y, foodPos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler (new Vector3 (0, 0, angle));
} else {
//Wander aimlessly avoid the player
}
}
这不能正常工作,对手不会向新生成的收藏品旋转。请帮忙!
【问题讨论】:
-
你不应该反转targetDir吗?那个向量是从 AI 到玩家的,我猜你想要相反的东西,或者从那个向量旋转 90 度。
-
哦,是的,谢谢,这是有道理的,但我不确定如何从矢量旋转 90 度。另外,想知道如何将我的对手旋转到 vector3 点
-
(x, y) 旋转 90 度就是 (-y, x),如果你想逆时针旋转它就是 (y, -x)。但是,如果您想以任意角度旋转矢量。 ` theta = deg2rad(角度); cs = cos(θ); sn = sin(θ);点X = x * cs - y * sn; pointY = x * sn + y * cs;`
-
希望我能注意学校教的所有数学。所以我尝试应用一些三角函数并修改了我的问题
-
Transform.LookAt怎么样? docs.unity3d.com/ScriptReference/Transform.LookAt.html
标签: unity3d artificial-intelligence