简体   繁体   English

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

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

I have a moving object (the ship) with several child objects (its turrets). 我有一个移动的物体(船),上面有几个子物体(其炮塔)。 The turrets are to rotate towards the player object regardless of the direction the ship is facing. 无论舰船朝向哪个方向,炮塔都将朝着玩家目标旋转。 The problem is, unless the ship is rotated straight up, the turrets just spin around wildly. 问题是,除非船垂直向上旋转,否则炮塔会疯狂旋转。

The code to rotate the turrets is as follows: 旋转炮塔的代码如下:

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

The ship is instantiated with this code. 用该代码实例化该船。 Changing rotation changes the intitial rotation. 更改旋转会更改初始旋转。 At rotation = 180 it is rotated vertically up: 旋转= 180时,垂直向上旋转:

newEnemyShip = Object.Instantiate(enemyShip2, new Vector3(mousePosition.x, mousePosition.y, 0), Quaternion.Euler(210, 0, rotation));

The ship has an initial rotation which never changes. 该船的初始旋转方向永远不变。 It's movement code is: 它的运动代码是:

//moves in straight line at constant speed               
transform.Translate(Vector3.up * currentSpeed * Time.deltaTime, Space.Self);

It also has this to lock it onto the 2d plane: 它还具有将其锁定到2d平面上的功能:

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

Any help would be great appreciated! 任何帮助将不胜感激!

I figured it out! 我想到了! I'm not sure what the problem was with the original code, but the following code for the turret worked: 我不确定原始代码是什么问题,但是炮塔的以下代码有效:

//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, thanks for taking the time to look and respond Bijan,感谢您抽出宝贵的时间来思考和回复

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

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

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