Hello community, I have a question that have been messing with my brain these days.
I’m making a simple 2d character using the new 2d features(sprites). I’m rotating the character’s arms and head so it always faces a target controlled by mouse input, and it works well, except for one issue: when the arms or the head (they are 2 separate GOs) rotation in Z are equal to 180 degrees, it suddenly goes to 0 in Y and Z, so it actually never can have 180º of rotation in Z, causing the sprite to be totally inverted. I use a sprite for the case where the target’s .x is higher than the char’s and one for the opposite, if it matters.
Any help is strongly appreciated =D
Vector3 tempRotHead = head.position - target.position;
head.right = Vector3.RotateTowards(head.right, -tempRotHead, 30, 30);
Vector3 tempRotGun = gun.position - target.position;
gun.right = Vector3.RotateTowards(gun.right, -tempRotGun, 30, 30);
This is the code I’m using to rotate the objects.
I have a bit of a guess here. With Quaternions, sometimes they meet the letter of function, but they end up flipping things. That is, at the end of your RotateTowards(), gun.right and -tempRotGun are aligned, though the object is flipped in the process. Here is a bit of alternate code for rotating an object to aim at a target with a bit of smoothing. It will not flip the object. It expects that when the rotation is (0,0,0), the object will point to the right. You’ll have to evaluate this code, and then figure out how to change your code to match. To test, put it on an sprite with the “pointer” pointing right, drag and drop the target onto the ‘target’ variable in the inspector, hit play, and move the target around in the inspector.
#pragma strict
var target : Transform;
var speed = 180.0;
private var qTo : Quaternion;
function Update () {
var lookPos = target.position - transform.position;
var angle : float = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;
qTo = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.RotateTowards(transform.rotation, qTo, speed * Time.deltaTime);
}