- Home /
Flip Sprite with SpriteRenderer.flipX Issue
I have done around 40 hours of research and code tinkering and have posted in several forums, but still cannot get my sprite to flip according to the touch position (or drag direction). I have tried several other approaches and recently found this SpriteRenderer.flipX approach which almost works, but it's still not quite there and only flips the head one time when a touch is made on the opposite side. After this the head stays in the same position. I am new to unity and coding, but am confused on what issue would be causing this. Please help!
Here's my code:
public class FlipHead : MonoBehaviour {
public float speed;
private SpriteRenderer mySpriteRenderer;
//private float someScale;
//private float direction, _posX;
void Awake ()
{
mySpriteRenderer = GetComponent<SpriteRenderer>();
//direction = 1;
//someScale = transform.localScale.x;
}
void Update()
{
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Moved) {
Vector2 touchDeltaPosition = Input.GetTouch (0).deltaPosition;
transform.Translate (touchDeltaPosition.x * speed, touchDeltaPosition.y * speed, 0);
}
if(mySpriteRenderer != null)
{
// if the A key was pressed this frame
if(Input.GetTouch (0).position.x<0)
{
// flip the sprite
mySpriteRenderer.flipX = true;
}
if(Input.GetTouch (0).position.x >0)
{
// flip the sprite
mySpriteRenderer.flipX = false;
}
}
}
}
Just figured out my problem: I needed to change the - if(Input.GetTouch (0).position.x<0) to if(Input.GetTouch (0).deltaPosition.x<0) for both if functions. Finally got it working!! For any future viewers this script allows for touch and drag controls as well as sprite flipping.