Unity

[Unity2D] 캐릭터 픽셀단위로 이동하는 방법

usingsystem 2022. 11. 14. 21:55
728x90
public class PlayerController : MonoBehaviour
{
    public Grid _grid;  
    public float _speed = 5.0f;

    Vector3Int _cellPos = Vector3Int.zero;
    MoveDir _dir = MoveDir.None;
    bool _isMoveing = false;

    void Start()
    {
        Vector3 pos = _grid.CellToWorld(_cellPos) + new Vector3(0.5f, 0.5f);
        transform.position = pos;
    }

    void Update()
    {
        GetDirInput();
        UpdatePosition();
        UpdateIsMoveing();
    }

    void GetDirInput()
    {
        if (Input.GetKey(KeyCode.W))
        {
            _dir = MoveDir.Up;
            //transform.position += Vector3.up * Time.deltaTime * _speed;
        }
        else if (Input.GetKey(KeyCode.S))
        {
            _dir = MoveDir.Down;
            //transform.position += Vector3.down * Time.deltaTime * _speed;
        }
        else if (Input.GetKey(KeyCode.A))
        {
            _dir = MoveDir.Left;
            //transform.position += Vector3.left * Time.deltaTime * _speed;
        }
        else if (Input.GetKey(KeyCode.D))
        {
            _dir = MoveDir.Right;
            //transform.position += Vector3.right * Time.deltaTime * _speed;
        }
        else
        {
            _dir = MoveDir.None;
        }
    }
    void UpdatePosition()
    {
        if (_isMoveing == false)
            return;

        Vector3 destPos = _grid.CellToWorld(_cellPos) + new Vector3(0.5f, 0.5f);
        Vector3 moveDir = destPos - transform.position;

        //도착 여부 체크

        float dist = moveDir.magnitude;//어느정도 거리가 남았는지
        if(dist< _speed * Time.deltaTime)
        {
            transform.position = destPos;
            _isMoveing = false;
        }
        else
        {
            transform.position += moveDir.normalized * _speed * Time.deltaTime;
            _isMoveing = true;
        }
    }
    void UpdateIsMoveing()
    {
        if (_isMoveing == false)
        {
            switch (_dir)
            {
                case MoveDir.Up:
                    _cellPos += Vector3Int.up;
                    _isMoveing = true;
                    break;
                case MoveDir.Down:
                    _cellPos += Vector3Int.down;
                    _isMoveing = true;
                    break;
                case MoveDir.Left:
                    _cellPos += Vector3Int.left;
                    _isMoveing = true;
                    break;
                case MoveDir.Right:
                    _cellPos += Vector3Int.right;
                    _isMoveing = true;
                    break;
            }
        }
    }
}
728x90