Reputation: 11
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:
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:
//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!
Upvotes: 0
Views: 490
Reputation: 11
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
Upvotes: 1