- Home /
Look at target and flip
Hi, everybody. I've been a couple of days trying to make part of my project's gameplay work. The concept is simple. My 2D character (planes on both sides) has a 2D weapon (again, a plane for each side) that is supposed to look at a certain target (an empty GameObject I will move through another script). These are the two lines of code that are making it work:
Aim = new Vector3((target.transform.position.x - transform.position.x), target.transform.position.y - transform.position.y, 0);
transform.rotation = Quaternion.FromToRotation (Vector3(0, 5, 0), Aim);
I must say I'm still a noob, specially when it comes to Quaternions.
So, what's the problem? Have a look at these pics:
As you can see, when the target is behind the character, the arms don't flip direction. What I need is the arms to turn 180 so that it's other plane (the one that faces left) is seen.
Answer by owenpat · Feb 26, 2011 at 06:01 PM
Try: transform.LookAt(target.transform);
The problem is that FromToRotation doesn't know you want the magazine at the bottom, so just spins the quickest way. It is possible to make a quaternion to flip it around the local x-axis and then multiply your rotation by that, if you really want to play with Quats.
LookAt automatically tries to keep the up part of your object facing up. It sort of does the subtraction, the FromToRotation you had, plus the extra "face up" step. I love doing my own trig, so it's depressing how many problems can be solved using LookAt.