- Home /
How do I flip a 3D object to look towards left or right on a 2D plane
Hello, I am developing a 2.5D fighting game in Unity 5.6.1. I am having an issue getting my player to look towards the enemy when the enemy is behind them. To do this I am trying to flip the player's rotation on the y axis when they are on the right side of the enemy.
Here's the code:
public Transform enemyPos;
public int speed;
void Update () {
TrackEnemy ();
Movement ();
}
void Movement () {
if (Input.GetKey (KeyCode.A)) {
if (transform.eulerAngles.y == 180) {
transform.Translate (Vector3.right * speed * Time.deltaTime);
} else {
transform.Translate (Vector3.left * speed * Time.deltaTime);
}
}
if (Input.GetKey (KeyCode.D)) {
if (transform.eulerAngles.y == 180) {
transform.Translate (Vector3.left * speed * Time.deltaTime);
} else {
transform.Translate (Vector3.right * speed * Time.deltaTime);
}
}
}
void TrackEnemy () {
Vector3 distance = transform.InverseTransformPoint (enemyPos.position);
if (distance.x < 0) {
this.transform.rotation = Quaternion.Euler (new Vector3 (0, 180, 0));
} else if (distance.x > 0) {
this.transform.rotation = Quaternion.Euler (new Vector3 (0, 0, 0));
} else {
print ("I'm directly on the enemy");
}
}
I think my issue has to do with either the function I'm using to track the enemy or where I'm calling the function. The current code I'm using causes the player to keep alternating which direction they are facing every frame when on the right side of the enemy, which I assume is because I'm calling the function in Update () (I've tried calling in LateUpdate () and FixedUpdate () as well). I only need the player to switch rotations when moving from one side of the enemy to the other, however I am not sure how to specify when this happens in the code more accurately.
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
Distribute terrain in zones 3 Answers
Make movement of an object independant. 1 Answer
2D Attack For Fighting Game 1 Answer