【问题标题】:Rotating Child Object in Unity 2D with C#使用 C# 在 Unity 2D 中旋转子对象
【发布时间】:2018-08-05 19:12:04
【问题描述】:

我有一个移动物体(船)和几个子物体(它的炮塔)。无论船面向哪个方向,炮塔都将朝着玩家对象旋转。问题是,除非船直接向上旋转,否则炮塔只会疯狂地旋转。

旋转炮塔的代码如下:

//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);

它还具有将其锁定在 2d 平面上的功能:

//Lock rotation on 2d plane
Quaternion q = transform.rotation;
q.eulerAngles = new Vector3(0, 0, q.eulerAngles.z);
transform.rotation = q;

任何帮助将不胜感激!

【问题讨论】:

  • 两个旋转有什么关系?它们在同一个更新块中吗?

标签: c# unity3d


【解决方案1】:

我想通了!我不确定原始代码有什么问题,但炮塔的以下代码有效:

//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,感谢您抽出宝贵时间查看和回复

【讨论】:

    【解决方案2】:

    为什么你不使用transform.LookAt(playerPosition)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      相关资源
      最近更新 更多