C# 使用C在Unity 2D中旋转子对象#
我有一个移动的物体(船)和几个子物体(它的炮塔)。炮塔将朝玩家的目标旋转,而不考虑飞船面对的方向。问题是,除非飞船直接向上旋转,否则炮塔只能疯狂地旋转 旋转转台的代码如下所示:C# 使用C在Unity 2D中旋转子对象#,c#,unity3d,C#,Unity3d,我有一个移动的物体(船)和几个子物体(它的炮塔)。炮塔将朝玩家的目标旋转,而不考虑飞船面对的方向。问题是,除非飞船直接向上旋转,否则炮塔只能疯狂地旋转 旋转转台的代码如下所示: //Rotate towards player dir = PlayerScript.GlobalVariables.playerPosition - myPosition; angleToTarget = Vector2.Angle(dir, transform.up); angle = Mathf.Atan2(dir
//Rotate towards player
dir = PlayerScript.GlobalVariables.playerPosition - myPosition;
angleToTarget = Vector2.Angle(dir, transform.up);
angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90;
transform.localRotation = Quaternion.RotateTowards(transform.rotation, Quaternion.AngleAxis(angle, Vector3.forward), turnSpeed);
船是用这个代码实例化的。更改旋转会更改初始旋转。旋转=180时,垂直向上旋转:
newEnemyShip = Object.Instantiate(enemyShip2, new Vector3(mousePosition.x, mousePosition.y, 0), Quaternion.Euler(210, 0, rotation));
船有一个永远不会改变的初始旋转。它的运动代码是:
//moves in straight line at constant speed
transform.Translate(Vector3.up * currentSpeed * Time.deltaTime, Space.Self);
它还具有将其锁定到二维平面的功能:
//Lock rotation on 2d plane
Quaternion q = transform.rotation;
q.eulerAngles = new Vector3(0, 0, q.eulerAngles.z);
transform.rotation = q;
任何帮助都将不胜感激 我想出来了!我不确定原始代码的问题是什么,但塔楼的以下代码起了作用:
//Rotate towards player
dir = PlayerScript.GlobalVariables.playerPosition - myPosition;
angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90;
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.AngleAxis(angle, Vector3.forward), turnSpeed);
Bijan,谢谢你花时间查看和回复我明白了!我不确定原始代码的问题是什么,但塔楼的以下代码起了作用:
//Rotate towards player
dir = PlayerScript.GlobalVariables.playerPosition - myPosition;
angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90;
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.AngleAxis(angle, Vector3.forward), turnSpeed);
Bijan,感谢您花时间查看和回复为什么不使用
变换。查看(播放位置)
?为什么不使用变换。查看(播放位置)
?两个旋转如何相关?它们在同一个更新块中吗?两个旋转如何相关?它们是否在同一更新块中?