본문 바로가기
TIL

[멋쟁이사자처럼 부트캠프 TIL 회고] 유니티 게임개발 3기 17일차 유니티 활용

by HYttt 2024. 12. 12.

BoxCollider bounds

  • 특정 콜라이더 안에 포함되어 있는지 확인

Mathf.Clamp( )

  • 최소 최대값을 설정하여 float값이 그 범위를 넘지 않도록 함
BoxCollider boxCollider = cube.GetComponent<BoxCollider>();
        
        transform.position =
            new Vector3(Mathf.Clamp(transform.position.x, boxCollider.bounds.min.x,
                boxCollider.bounds.max.x), 0, Mathf.Clamp(transform.position.z, boxCollider.bounds.min.z,
                boxCollider.bounds.max.z));
                
 // x 와 z의 위치를 박스크기만큼 제한하여 벗어나지 못하도록 함

 

대포게임 만들기

슬라이더 UI

  • Space를 누르고 있으면 게이지가 차고 끝까지 차면 다시 내려가도록 함
public Slider slider;

void Update()
{
	if (Input.GetKey(KeyCode.Space))
        {
            
            if (isMax)
            {
                currentPower += -1 * fillSpeed * Time.deltaTime;
            }
            else
            {
                currentPower += fillSpeed * Time.deltaTime;
            }
            currentPower = Mathf.Clamp(currentPower, 0, maxPower);
            slider.value = currentPower/maxPower;
            
            isMax = slider.value switch
            {
                1 => true,
                0 => false,
                _ => isMax
            };
        }
 }

 

대포알

  • Layer를 설정하여 지면이나 적과 닿으면 파편이 튀도록 함
private void OnTriggerEnter(Collider other)
    {
        Vector3 hitDirection = GetComponent<Rigidbody>().velocity * -1;     // 발사한 방향의 반대 (속도 포함)

        int count = Random.Range(minPieceCount, maxPieceCount + 1);

        for (int i = 0; i < count; ++i)
        {
            Vector3 randomDirection = Random.insideUnitSphere;
            Vector3 finalDirection = Quaternion.LookRotation(randomDirection) 
                                   * hitDirection;
        
            GameObject instance = Instantiate(piece, transform.position,
                Quaternion.LookRotation(finalDirection));	// 랜덤한 방향 설정

            instance.GetComponent<Rigidbody>().AddForce(finalDirection, ForceMode.Impulse);
            Destroy(this.gameObject);
        }
    }

 

 

일정 범위 안에 3초마다 적 생성

IEnumerator CreateEnemies()
    {
        while (true)
        {
            SpawnEnemy();
            yield return new WaitForSeconds(3f);
        }
        
    }

    private void SpawnEnemy()
    {
        BoxCollider boxCollider = cube.GetComponent<BoxCollider>();
        float xPos = Random.Range(boxCollider.bounds.min.x, boxCollider.bounds.max.x);
        float zPos = Random.Range(boxCollider.bounds.min.z, boxCollider.bounds.max.z);
        createPos = new Vector3(xPos, 1, zPos);
        
        GameObject e = Instantiate(enemy);
        e.transform.position = createPos;
    }