본문 바로가기
게임프로젝트/애니팡 모작

블럭 드래그 해서 이동하기

by pudding81 2024. 5. 13.

 

러프를 사용해서 부드럽게 이동하기 

    // 블록 이동

    private void MoveBlock(int currentRow, int currentCol, int newRow, int newCol)
    {
        isdragging = true;
        
        // 두 지점의 블록 가져오기
        GameObject currentBlock = blocks[currentRow, currentCol];
        GameObject newBlock = blocks[newRow, newCol];

            // 블록 위치 갱신
            Vector3 currentCellPosition = cells[currentRow, currentCol].transform.position;
            Vector3 newCellPosition = cells[newRow, newCol].transform.position;

       
        


           
            // 두 지점의 블럭의 자리를 교체한다.
            blocks[currentRow, currentCol] = newBlock;
            blocks[newRow, newCol] = currentBlock;

            StartCoroutine(MoveBlockCoroutine(currentBlock, newCellPosition));
           StartCoroutine(MoveBlockCoroutine(newBlock, currentCellPosition));



    }



    private IEnumerator MoveBlockCoroutine(GameObject block, Vector3 targetPosition)
    {
        float duration = 1f; // 이동에 걸리는 시간
        float elapsedTime = 0f;
        Vector3 startPosition = block.transform.position;
        bool blockDestroyed = false;

        while (elapsedTime < duration)
        {
            elapsedTime += Time.deltaTime * blockFallSpeed;
            // 블록이 파괴되지 않았다면 이동 처리
            if (!blockDestroyed)
            {
                if (block == null)
                {
                    // 블록이 파괴되었음을 표시
                    blockDestroyed = true;
                }
                else
                {
                    // Lerp 함수를 사용하여 부드럽게 이동
                    float t = Mathf.Clamp01(elapsedTime / duration); // 보정된 시간

                    block.transform.position = Vector3.Lerp(startPosition, targetPosition, t);

                }


            }

            yield return null;
        }

        // 블록이 파괴되지 않았다면 최종 위치로 설정
        if (!blockDestroyed && block != null && matchFound)
        {
            block.transform.position = targetPosition;
        }



    }