- Home /
OnCollision2D Sprite Flip C#
I want to create a non-player controller sprite flip when they get from on collider to another so I can have a patrolling enemy, but I can't get the sprite to flip. Any suggestions?
using UnityEngine; using System.Collections;
public class JousterController : MonoBehaviour {
public Vector3 pointB;
Animator anim;
public bool facingRight;
// Use this for initialization
IEnumerator Start () {
var pointA = transform.position;
while(true)
{
yield return StartCoroutine(MoveObject(transform, pointA, pointB, 3.0f));
yield return StartCoroutine(MoveObject(transform, pointB, pointA, 3.0f));
}
}
IEnumerator MoveObject(Transform thisTransform, Vector3 startPos, Vector3 endPos, float time)
{
var i= 0.0f;
var rate= 1.0f/time;
while(i < 1.0f)
{
i += Time.deltaTime * rate;
thisTransform.position = Vector3.Lerp(startPos, endPos, i);
yield return null;
}
}
void CollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "left")
{
facingRight = true;
Flip();
}
if (col.gameObject.tag == "right")
{
facingRight = false;
Flip();
}
}
void Flip(){
facingRight = !facingRight;
Vector3 theScale=transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
Are you sure sure about the tags that you are checking (left and right) ?? Also i dont get the use of facingRight in your Flip method. Just try to debug and see if it is even going in the CollisionEnter2D or not or if it is even reaching inside the Flip method. I dont see what you are doing wrong, i will only say you need bit more debugging on what you have.
Answer by IAMBATMAN · Mar 31, 2016 at 07:49 AM
Can't you use
transform.eulerAngles = new Vector3(0,180,0);
and transform.eulerAngles = new Vector3(0,0,0);
to reset it back to normal?
Also you could make a new variable of type SpriteRenderer called spriteRenderer and In Start set it to the spriteRenderer on your object with
spriteRenderer = GetComponent (SpriteRenderer);
and then you could use spriteRenderer.flipY = true; but this wouldn't flip your collider.
Hope this helps :)
I tried that and it didn't work, but I might try the sprite renderer to see it that works. I don't think I need the collider to be flipped
Answer by dapa5678 · Mar 30, 2016 at 10:34 PM
You need to use eulerAngles so something like this.
facingRight = !facingRight;
transform.eulerAngles = new Vector2(int,int);
I get this error when I tried that. Is there something I'm supposed to be putting in the ()? Sorry, I'm really sick so I'm probably just being stupid.
This works fine
GetComponent<SpriteRenderer>().flipX = true;
hope this helps
$$anonymous$$ :)
Your answer
Follow this Question
Related Questions
Help me with the 2d lights! 0 Answers
2D rendering Order 0 Answers
Instantiate a GameObject with a specific Z rotation 2 Answers
How do I stop my sprite from jumping in the air? 1 Answer
Problem With Pixel Art Pixel Size 2 Answers