Hello Guest

Author Topic: Flipping the Sprite image in C# code  (Read 4630 times)

Fosforus

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 2
    • View Profile
Flipping the Sprite image in C# code
« on: November 01, 2013, 12:42:45 am »
I'm having trouble figuring out how to flip a sprite image in C# code. Take for example a character that moves left and right. At the moment I can't get the image to flip so when he is facing right or left, he is actually facing the corresponding direction. 

Here's the code I'm using so far.

Code: [Select]
using UnityEngine;
using System.Collections;

public class Movements : MonoBehaviour {

Vector3 movement;
private float moveSpeed = 15f;
private float moveDirX = 0f;
private float moveDirY = 0f;
private bool leftArrow;
private bool rightArrow;

private tk2dSpriteAnimator anim;
private bool walking = false;
private bool facingLeft = true;
private bool facingRight = false;


// Use this for initialization
void Start () {
anim = GetComponent<tk2dSpriteAnimator>();
}

// Update is called once per frame
void Update () {

bool leftArrow = Input.GetKey(KeyCode.LeftArrow);
bool rightArrow = Input.GetKey(KeyCode.RightArrow);
bool space = Input.GetKey(KeyCode.Space);

if(!leftArrow && !rightArrow)
{
if(moveDirX > 0)
moveDirX--;

if(moveDirX < 0)
moveDirX++;
anim.Play("Standing");
}

if(leftArrow) {
facingRight = false; facingLeft = true;

anim.Play ("Walk");
if(moveDirX > -moveSpeed)
  moveDirX -= 1f;
    }

    if(rightArrow) {
facingLeft = false; facingRight = true;
anim.Play ("Walk");

if(moveDirX < moveSpeed)
  moveDirX+= 1f;
    }

if(space){

}

movement = new Vector3(moveDirX, moveDirY, 0);
movement *= Time.deltaTime;
  transform.Translate(movement);
}
}
Also, is this the right place to post a question like this?

ohad11

  • Newbie
  • *
  • Posts: 3
    • View Profile
Re: Flipping the Sprite image in C# code
« Reply #1 on: November 01, 2013, 12:59:34 am »
use the FlipX property on the sprite to tell it if its flipped or not: anim.Sprite.FlipX = true; will flip the sprite and setting it to false will flip it back to its original state.

Fosforus

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: Flipping the Sprite image in C# code
« Reply #2 on: November 01, 2013, 02:36:48 am »
Ok thanks, that worked perfectly. I spent a really long time on the internet trying to figure that out.