Using quaternions in 2D to follow a rotation. Both question and an Answer.
Hello so I have been looking around for a way of making a turret turn to face a object as it moves past it for a bit now. I look all over the internet, and quite a lot of it seemed to consist of using quaternions to do this plus lots of other stuff. I am new to unity and have not had the time to full research quaternions. So for not I came up with my own solution. This is an answer because I think I figured out a really easy way and a question because it seemed to easy to do and is there any downside to doing it this way?
I had two game objects. 1. Real turret head. (This one had the sprite on) 2. Fake turret head. I had a script attacked to fake turret head. that said
public Transform enemyTarget; public Transform lookAtPos; public Transform fakeRotator; public Vector3 WorldPos;
private CircleCollider2D turretAgroRange;
// Use this for initialization
void Start ()
{
turretAgroRange = this.GetComponent<CircleCollider2D>();
}
// Update is called once per frame
void Update ()
{
//this.transform.LookAt(enemyTarget);
//transform.LookAt(transform.position + new Vector3(0,0,1),enemyTarget);
Vector3 relativePos = enemyTarget.position - transform.position;
Quaternion tempQuat = Quaternion.LookRotation(relativePos);
Quaternion tempFloat = fakeRotator.rotation;
fakeRotator.rotation = Quaternion.LookRotation(relativePos);
print (tempQuat);
print (transform.rotation + "2");
}
void OnTriggerEnter2D(Collider2D col)
{
print ("Went into agro range");
enemyTarget = col.transform;
}
This would make the fake turret head look at an object as it moved past. Now I originally did this for for the real turret head. But as i'm sure people who have had the same problem know it would just turn on its side and you could not see the sprite.
So what I did after this, I made the real turret head a child of the fake on. so when the fake would turn so did the real. But still I had the same issue of it turning so all I did was make the fake turret's starting Y rotation of - 90. Then set the real turret head to to -90. Making it balance out. (This is to say that the front of the real turret. is facing down the y axis, you would have to change the directions depending on where yours is.)
So I hope this helps anyone else. If anyone has any ideas why this might not be a good idea for some reason please let me know. :D
Here is my question to this. I have a frog that jumps towards the left, as soon as the player is visible. When the frog hits a .tag named "wall" it will go towards the right, and vice versa.
How would I switch its image depending on which direction (left or right) it is facing?