- Home /
Unity 2D, Flip Sprite without using a rigidbody
I have made an npc that patrols between random points. A new point is generated, and the enemy's transform is changed to that new point.
I want its sprite to flip based on whether it is moving left or right. I have found examples like this:
if(myRigidbody.velocity.x >= 0){
spriteRenderer.flipX = false;
}
else {
spriteRenderer.flipX = true;
}
But they don't work with my script, even if my npc has a rigidbody. I think its because the rigidbody.velocity.x isnt actually changing, just the transform.position?
So how can I do it without the rigidbody.velocity?
Provide your movement script, but I'm guessing just like you guessed are that you aren't using the unity physics system at all for horizontal movement.
Don't forget to Debug.log things to test why things are broken; you suspect that the velocity in your rigidbody isn't changing, if you suspect that then write try something like this in the future:
if(myRigidbody.velocity.x >= 0)
{
Debug.log(myRigidbody.velocity.x);
spriteRenderer.flipX = false;
}
else
{
spriteRenderer.flipX = true;
}
And if your suspicion is correct, then it would log the value if it greater than or equal to 0 (which should be true and 0 all the time).
Thanks for the tip about Debug.log I always see people use it in tutorials but never think to use it myself. durrr
Answer by visca_c · Aug 01, 2019 at 02:22 PM
If you are not using rigidbody velocity, you can just find the delta position of your character, then flip the sprite.
Vector2 lastPos;
void Update()
{
Vector2 currentPos = transform.position;
Vector2 deltaPos = currentPos - lastPos;
if(deltaPos.x>=0)
spriteRenderer.flipX=false;
else
spriteRenderer.flipX=true;
lastPos = transform.position;
}
Genius, love it! Excellent little check for side scrolling games, can't believe I have never seen something like this before!
I think this is kind of on the right track, but I don't see a reason to check this every frame. The only time we care about flipping, is when we need a new direction. So I would take out what you have and make a new method with it. Then they can call into it when they change directions. Then ins$$anonymous$$d of doing transform.position - lastPos, it would be (waypoint.position - transform.position). Waypoint being where they are going next.
I'm getting an error CS0034 Operator '-' is ambiguous on operands of type 'Vector3' and 'Vector2' could you help me?
I updated the answer, adding one more variable "currentPos" to handle the casting (Vector3 to Vector2), See if it solves your problem.
Your answer
Follow this Question
Related Questions
How to flip parent without flipping child game object? 0 Answers
Rigidbody2d.velocity making character stop in between 1 Answer
How to nine slice a 2D SpriteRenderer? 0 Answers
Collider not resizing with Sprite Shape by Script 2 Answers
Prefab of SpriteShapeRenderer not rendered if first point not visible ? 1 Answer