- Home /
Object won't rotate correctly
I have 2d turret that is suppose to follow a player as seen in the image.
I tried a couple ways to get this to work, but both ways aren't giving me the desired results.
The first way flips my turret image horizontally, instead of letting it rotate in its original position.
public Transform target;
Quaternion rotation = Quaternion.LookRotation
(target.transform.position - transform.position, transform.TransformDirection(Vector2.up));
transform.rotation = new Quaternion (0, 0, rotation.z, rotation.w);
My second attempt worked perfectly, but the turret follows the mouse and not the player. Maybe I would have to change the Input.mousePosition part to something else, but I'm not sure at this point.
Vector3 diff = Camera.main.ScreenToWorldPoint (Input.mousePosition) - transform.position;
diff.Normalize ();
float rot_z = Mathf.Atan2 (diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler (0f, 0f, rot_z - 90);
I've also tried the LookAt method, but that flips my turret image into a different position as well. Any help would be greatly appreciated.
You can use the LookAt method (or any other script), then put the script onto an empty GameObject, parent your turret to the game empty, rotate the turret inside it's parent so that it works correctly.
Answer by Dazdingon · Jun 06, 2014 at 06:41 AM
Assuming that you are using the x and y axis for movement.
You could use :
transform.LookAt(Vector3.back, target.position);
Or you could use :
Vector3 direction = this.transform.position - target.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg + 90;
// ajust the angle at a speed of rotateSpeed (float)
angle = Mathf.MoveTowardsAngle(this.transform.eulerAngles.z, angle, Time.deltaTime * rotateSpeed);
this.transform.rotation = Quaternion.Euler(0, 0, angle);
Answer by pacific00 · Jun 06, 2014 at 06:54 AM
itd be much more easier if you could fix center of the turret at its rear end..
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Inheritance code acts differently (Quaternion.LookRotation) 0 Answers
Rotating a model with increments 1 Answer
Tilt object x degrees, smoothly 0 Answers