繁体   English   中英

使用C#在Unity 2D中旋转子对象

[英]Rotating Child Object in Unity 2D with C#

我有一个移动的物体(船),上面有几个子物体(其炮塔)。 无论舰船朝向哪个方向,炮塔都将朝着玩家目标旋转。 问题是,除非船垂直向上旋转,否则炮塔会疯狂旋转。

旋转炮塔的代码如下:

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

任何帮助将不胜感激!

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

//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,感谢您抽出宝贵的时间来思考和回复

为什么您不使用transform.LookAt(playerPosition)呢?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM