How do I rotate a 2d Object to face another object?
Hello, I am trying to make a compass in 2d that will target another 2d object on the z axis perhaps.
I've tried and tried for hours and cannot work it out. It should be simple, but its not.
Here is some code that doesn't work, I've tried heaps of different variations of code but with no success, I've tried Lookat and anything else I could think about.
newdir = staticCompassTarget.transform.position;
newdir.x = 0f;
newdir.y = 0f;
// newdir.z = 0f;
print(newdir);
transform.LookAt(newdir);
I've tried using all axis's or just one or two, cannot find any help for this in Unity Answers.
Could someone please help?
Answer by Kastenessen · May 07, 2017 at 06:05 AM
I've done this before years ago, so I solved it myself with this code:
Vector3 targ = staticCompassTarget.transform.position;
targ.z = 0f;
Vector3 objectPos = transform.position;
targ.x = targ.x - objectPos.x;
targ.y = targ.y - objectPos.y;
float angle = Mathf.Atan2(targ.y, targ.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
Answer by RDSquare · Jul 24, 2020 at 08:13 PM
This is for smooth rotation in 2d to look at target object. Change the SPEED to const value or with your variable.
float angle = Mathf.Atan2(TargetObjTransform.position.y - transform.position.y, TargetObjTransform.position.x -transform.position.x ) * Mathf.Rad2Deg;
Quaternion targetRotation = Quaternion.Euler(new Vector3(0, 0, angle));
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, SPEED * Time.deltaTime);
This is upgraded version of @Kastenessen . His code is not working correctly.
Answer by mannychacon2005 · Mar 10, 2021 at 09:47 AM
Your objects x axis can face another object by
transform.right = target.position - transform.position;
after that to make it move in the direction of the object just add to the x.,You can rotate your objects right axis to face another by doing something like - transform.right = targetobject.position - transform.position; Then all you have to do to make it move toward the other object is just add to the x axis.
In my case, to rotate a laser towards the player in a 2D game, I used: transform.up= target.position - transform.position;
Your answer
Follow this Question
Related Questions
How to object rotate on a single axis towards another object? C# 2 Answers
Align an object rotation in relation to another object 0 Answers
Boss AI Help in a 2D Platform game 0 Answers
Rotate an Object while moving forward using empty gameObject 0 Answers
Rotating object relative to player to orient it center of camera regardless of direction. 0 Answers