유니티_unity

(유니티) 오브젝트 좌우 반전 transform.localScale GetComponent<SpriteRenderer>

코딩ABC 2024. 2. 28. 13:20
반응형

유니티에서 오브젝트를 좌우 또는 상하로 반전하는 코드입니다.

여기서는 좌우 화살표키로 자동차를 움직이고, 자동차가 이동하는 방향을 보도록 작성해 보겠습니다.

 

1. 2D를 선택해서 프로젝트를 생성합니다.

 

2. 아래의 자동차 이미지를 Asset으로 가져옵니다.

자동차 이미지

 

3. C# 스크립트를 생성하고, 다음 코드를 작성합니다.

private Vector3 direction = Vector3.zero;   // 이동 방향
public int speed = 1;

void Update()
{
    float x = Input.GetAxisRaw("Horizontal");   // 좌우 이동
    float y = Input.GetAxisRaw("Vertical");     // 상하 이동

    if (x < 0) {
        this.GetComponent<SpriteRenderer>().flipX = true;
    }
    else if (x > 0)
    {
        this.GetComponent<SpriteRenderer>().flipX = false;
    }
    direction = new Vector3(x, y, 0);
    transform.position += direction * speed * Time.deltaTime;
}

4. 자동차와 C# 스크립트를 연결합니다.

 

5. 실행합니다.

(유니티) 오브젝트 좌우 반전

 

 

transform.localScale

위 3번의 스크립트는 transform.localScale 속성을 이용해서 아래와 같이 작성할 수 있습니다.

private Vector3 direction = Vector3.zero;   // 이동 방향
public int speed = 1;

void Update()
{
    float x = Input.GetAxisRaw("Horizontal");   // 좌우 이동
    float y = Input.GetAxisRaw("Vertical");     // 상하 이동
    Vector3 direction = Vector3.zero;

    if (x < 0) {
        //this.GetComponent<SpriteRenderer>().flipX = true;
        //direction = Vector3.left;
        transform.localScale=new Vector3(-1f, 1, 1); 
    }
    else if (x > 0) 
    {
        //this.GetComponent<SpriteRenderer>().flipX = false;
        //direction = Vector3.right;
        transform.localScale = new Vector3(1f, 1, 1);
    }
    direction = new Vector3(x, y, 0);
    transform.position += direction * speed * Time.deltaTime;
}

 

상하로 이동하지는 않고 좌우로만 이동하고자 할 때는 다음과 같이 수정하면 됩니다.

 private Vector3 direction = Vector3.zero;   // 이동 방향
 public int speed = 1;

 void Update()
 {
     float x = Input.GetAxisRaw("Horizontal");   // 좌우 이동
     float y = Input.GetAxisRaw("Vertical");     // 상하 이동
     Vector3 direction = Vector3.zero;

     if (x < 0) {
         //this.GetComponent<SpriteRenderer>().flipX = true;
         direction = Vector3.left;
         transform.localScale=new Vector3(-1f, 1, 1); 
     }
     else if (x > 0) 
     {
         //this.GetComponent<SpriteRenderer>().flipX = false;
         direction = Vector3.right;
         transform.localScale = new Vector3(1f, 1, 1);
     }
     //direction = new Vector3(x, y, 0);
     transform.position += direction * speed * Time.deltaTime;
 }
반응형