Oliver Sradnick Oliver Sradnick - 12 days ago 9
C# Question

Unity: Flip 2D GameObject(Clone) while GetKeyDown

my problem is when im instantiate an GameObject, it should flip like my Player
but it just flipping arround when im turn left.

using UnityEngine;
using System.Collections;

public class beam : MonoBehaviour {

public Transform firePoint;
public move dino;

void Awake()
{
dino = GetComponent<move>();
dino = FindObjectOfType<move>();
firePoint = GameObject.FindGameObjectWithTag("spawn").transform;
}

// Use this for initialization
void Start () {
}

void FixedUpdate ()
{
transform.position = firePoint.position;
}
void Update ()
{
if (dino.GetComponent<move>().facingRight == false)
{
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}

}
}


for example: my Player facing right side, the "Beam" is Facing right too but when my Player facing left side the "Beam" switching between-1 and +1

hope you understand what i mean. pls some Help :)

Answer

You are doing the fast flip in the update method: while dino not face right flip it like crazy! change *= to = and it should work. Or if it is already scaled then do this:

void Update ()
{
    if (dino.GetComponent<move>().facingRight == false)
    {
        Vector3 theScale = transform.localScale;
        theScale.x = Mathf.Abs(theScale.x) * -1;
        transform.localScale = theScale;
    }
}

Note:

It's better to use SpriteRenderer.FlipX = true/false rather than scale.

Another Note:

If you use batching, non-uniform scale and flip are deadly. use multiple sprites and switch between them.

Comments