- Home /
How do I flip the character when an object is infront/behind it?
I am making a 2d game and I have an enemy and player, I'm trying to make a Flip script that swaps two objects positions if another object is in front or behind it, but it just keeps flipping continuosly. Here's what I have:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NearestLocation : MonoBehaviour
{
public Transform enimy;
public Transform otherPlr;
public Vector3 tempPos;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
private void FixedUpdate()
{
if (otherPlr.position.x > enimy.position.x)
{
Swap(); return;
}
else if (otherPlr.position.x == enimy.position.x)
{
return;
}
else
{
Swap(); return;
}
}
public void Swap()
{
tempPos = enimy.transform.position;
enimy.transform.position = this.transform.position;
this.transform.position = tempPos;
}
}
Answer by MarekRimal · Apr 12 at 04:38 PM
Yes, you are swapping them whenever they dont have the same x coordinate. So they are swapping all the time.
So do you want to swap them when the player is behind the enemy or when he is in front of the enemy?
I am not really sure what you want to achieve. If you want to swap them only once no matter who is in front of another then you can use a bool. Initialize the bool to false and after first swap set it to true. Then do the swap only if the bool is false.
Your answer
![](https://koobas.hobune.stream/wayback/20220613055258im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Many cameras with Camera.main.ScreenToWorldPoint trouble. 2 Answers
How to hit differents gameobjects & enable the same gameobject (2d raycast) 0 Answers
Question on 2d planet gravity 1 Answer
I am trying to spawn multiple asteroids but only one is screen wrapping . Please help. 0 Answers
2D Tilemap stretching 2 Answers