24.02.25 TIL - Unity : 좌, 우 이동 시 2D 이미지 반전

JJwoo·2024년 2월 25일

테스트용 플레이어 오브젝트이다.

하위에 스프라이트 렌더러 오브젝트가 존재하고 있다.

오른쪽으로 이동 할 때는 그대로, 왼쪽으로 이동할 때는 왼쪽을 바라보도록 x축을 기준으로 반전하고 싶다.

일단 임시로 구현해둔 Input Action(Unity Event 기반) 이동 관련 코드에 두 가지의 방법을 써보았다.

1. transform.localScale 조절 방법

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class Player : MonoBehaviour
{
    private Vector2 moveDirection;
    [SerializeField]
    private float moveSpeed = 4f;

    void Update()
    {
        if (moveDirection.x > 0)
        {
            transform.localScale = new Vector3(1, 1, 1);
        }
        else if (moveDirection.x < 0)
        {
            transform.localScale = new Vector3(-1, 1, 1);
        }

        transform.Translate(new Vector3(moveDirection.x, moveDirection.y, 0) * moveSpeed * Time.deltaTime);
    }

    public void OnMove(InputAction.CallbackContext context)
    {
        moveDirection = context.ReadValue<Vector2>();
        if (moveDirection != Vector2.zero)
        {
            Debug.Log($"UNITY_EVENTS : {moveDirection.magnitude}");
        }
    }

    public void OnInteraction(InputAction.CallbackContext context)
    {
        if (context.performed)
        {
            // 상호작용 로직
            Debug.Log("상호작용");
        }
    }
}
  • 캐릭터가 왼쪽으로 이동할 때는 x축의 스케일을 -1로, 오른쪽으로 이동할 때는 1로 설정하여 캐릭터 이미지가 바라보는 방향을 전환하는 것을 구현.

2. Sprite Renderer의 X축을 flip 하는 방법

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class Player : MonoBehaviour
{
    private Vector2 moveDirection;
    [SerializeField]
    private float moveSpeed = 4f;
    private SpriteRenderer spriteRenderer; // Sprite Renderer 참조 저장


    void Start()
    {
        // 하위 오브젝트에 있는 Sprite Renderer 컴포넌트를 호출
        spriteRenderer = GetComponentInChildren<SpriteRenderer>();
    }

    void Update()
    { // x축 flip을 통한 이미지 방향 전환
        if (moveDirection.x > 0)
        {
            spriteRenderer.flipX = false; 
        }
        else if (moveDirection.x < 0)
        {
            spriteRenderer.flipX = true;
        }

        transform.Translate(new Vector3(moveDirection.x, moveDirection.y, 0) * moveSpeed * Time.deltaTime);
    }

    public void OnMove(InputAction.CallbackContext context)
    {
        moveDirection = context.ReadValue<Vector2>();
        if (moveDirection != Vector2.zero)
        {
            Debug.Log($"UNITY_EVENTS : {moveDirection.magnitude}");
        }
    }

    public void OnInteraction(InputAction.CallbackContext context)
    {
        if (context.performed)
        {
            // 상호작용 로직
            Debug.Log("상호작용");
        }
    }
}

캐릭터의 하위 오브젝트에게서 Sprite Renderer 컴포넌트에 대해 참조를 하고 방향에 따른 flipX로 이미지 방향을 전환.

profile
개발 모코코

0개의 댓글