My character has a fairy that flies backwards

Hey guys, I’ve managed to make a little 2d sidekick fairy for my platforming character. I’ve achieved this by using a spring-join. The problem is the fairy flies backwards when the character runs in the opposite direction. Can anyone help me code this so the fairy turns around when it has to move in another direction?

Here’s a video that demonstrates the issue:

You could set the scale of the sprite based on the velocity of the fairy.

if(rigidbody2D.velocity.x != 0)
	{
	transform.localScale = new Vector2(new Vector2(rigidbody2D.velocity.x,0).normalized.x, transform.localScale.y);
	}

Basically, if velocity is not 0, then we check which direction the velocity is happening, we use the .normalized value to get either a 1 or a -1 depending on which direction, and thus set our scale with that direction. Or if you don’t want to use scale, then rotate the fairy 180 based on whether that .normalized value is 1 or -1.

Thank you mate, the fairy now turns around when I run in the opposite direction. The fairy is thinner than she use to be though, like her x size is suddenly less. Any idea how I can fix that?

There is a known bug regarding flipping on the X axis. It will be fixed in the next major release.

Is your sprite scaled more than 1? Because this code will scale it to 1 or -1, thus if you have a scale bigger than 1 already, it’s going to look thinner. Add a multiplication in for your starting scale if so:

private float startScaleX;

void Start()
{
startScaleX = transform.localScale.x;
}

void Update()
{
if(rigidbody2D.velocity.x != 0)
    {
    transform.localScale = new Vector2(new Vector2(rigidbody2D.velocity.x,0).normalized.x * startScaleX, transform.localScale.y);
    }
}

Oh my goodness thank you so much mate! That worked perfectly! Yes she was slightly bigger than 1.

I just found out that there is an issue with using .normalized though, at very low velocity values, it can result in it returning a 0 value, even though it has some velocity, this can result in your character becoming 0 scaled during those last moments that it’s reaching 0 velocity… If you’re not having that issue, you can ignore this, but the other way to do this without the issue would be:

if(rigidbody2D.velocity.x > 0)
{
    transform.localScale = new Vector2(startScaleX, transform.localScale.y);
}
else if(rigidbody2D.velocity.x < 0)
{
    transform.localScale = new Vector2(-startScaleX, transform.localScale.y);
}

edit: Actually, the old code could be made to work 100% properly by changing up the condition, though I think the new code I gave is probably a tad more efficient, not needing to do the normalize operations. But here is the other way reworked:

if(new Vector2(rigidbody2D.velocity.x,0).normalized.x != 0)
    {
    transform.localScale = new Vector2(new Vector2(rigidbody2D.velocity.x,0).normalized.x * startScaleX, transform.localScale.y);
    }