- Home /
sprite always flip to left,Sprite always flip to left
I am learning to make 2D platform games and I am using the scripts of the Video Recorded Session: Character Controller of the 2D platform game and whenever I stop moving my character, the sprite is flipped to the left regardless if it was not the last dirrecion that I take, i cant see the problem. here the code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerPlatformerController : PhysicsObject {
public float maxSpeed = 7;
public float jumpTakeOffSpeed = 7;
private SpriteRenderer spriteRenderer;
private Animator animator;
// Use this for initialization
void Awake ()
{
spriteRenderer = GetComponent<SpriteRenderer> ();
animator = GetComponent<Animator> ();
}
protected override void ComputeVelocity()
{
Vector2 move = Vector2.zero;
move.x = Input.GetAxis ("Horizontal");
if (Input.GetButtonDown ("Jump") && grounded) {
velocity.y = jumpTakeOffSpeed;
} else if (Input.GetButtonUp ("Jump"))
{
if (velocity.y > 0) {
velocity.y = velocity.y * 0.5f;
}
}
bool flipSprite = (spriteRenderer.flipX ? (move.x > 0.01f) : (move.x < 0.01f));
if (flipSprite)
{
spriteRenderer.flipX = !spriteRenderer.flipX;
}
animator.SetBool ("grounded", grounded);
animator.SetFloat ("velocityX", Mathf.Abs (velocity.x) / maxSpeed);
targetVelocity = move * maxSpeed;
}
},
Comment
Answer by SirPaddow · Jun 05, 2019 at 06:34 AM
The problem is that you check if you need to flip even when your character is not moving. What about checking if it is moving first?
if (move.x != 0)
{
bool flipSprite = (spriteRenderer.flipX ? (move.x > 0.01f) : (move.x < 0.01f));
if (flipSprite)
{
spriteRenderer.flipX = !spriteRenderer.flipX;
}
}
or better (I think your ternary of bools is very hard to read):
if (move.x < 0)
{
spriteRenderer.flipX = true;
}
else if (move.x > 0)
{
spriteRenderer.flipX = false;
}