- Home /
2D character face another character
So heres what I'm trying to do. I want a 2D object that will look at another 2D object, and when that object passes to the other side of it, it will flip and continue to look at the target so that it never rotates upside down. So if I was putting this code on a 2D characters head they would look up as the target passed over head, but then flip and start looking more downward as it passed by instead of the head rotating upside down.
Answer by robertbu · Mar 22, 2014 at 05:42 PM
Here is a bit of code that does what I believe you want. Setup:
The object must be a sprite or other object that is rendered on both sides
The 'front' of the object needs to be on the right when rotation is (0,0,0)
Select the sprite texture and set the anchor to 'Right'
After attaching your script, select the game object with the script and drag and drop the target object on the 'target' variable in the Inspector.
pragma strict
var target : Transform;
function Update () { var dir = target.position - transform.position;
var q : Quaternion; if (dir.x >=0) { q = Quaternion.identity; } else { q = Quaternion.Euler(0,180,0); dir.x = -dir.x; } var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg; transform.rotation = q * Quaternion.AngleAxis(angle, Vector3.forward); }
Answer by Destran · Mar 22, 2014 at 05:14 PM
Try This:
var rotationSpeed : float = 5.0f;
functon Start()
{
rotationSpeed = 5.0f;
}
function Update()
{
FacePlayer();
// rotate to look at player
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(target.position, transform.positon), rotationSpeed * Time.deltaTime);
}
function FacePlayer ()
{
var relativePoint = transform.InverseTransformPoint(target.transform.position);
if (relativePoint.x < 0.0)
{
transform.Rotate(0,180,0);
}
else
{
transform.Rotate(0,0,0);
}
}
Edit: Looking back at your original question this might not be exactly what you wanted, but if you want something with a different functionality let me know and I'll try to help.
The
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(target.position, transform.positon), rotationSpeed * Time.deltaTime);
Line doesn't work at all, the object points into the Z axis and twitches a bunch.
sorry that should be transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(target.position - transform.positon), rotationSpeed * Time.deltaTime);
But, robertbu posted, and he's almost always perfect so.
Your answer
Follow this Question
Related Questions
Top Down Sprite Facing Mouse 2 Answers
Ground checking with a frequently rotating player 2 Answers
Find point of top of rotated sprite 1 Answer
Rotating a Sprite to face mouse / target? 2 Answers
How can I achieve this particular 2D lighting effect? 2 Answers