본문 바로가기

메모장/스네이크 게임

스네이크 게임 - 음식 랜덤 생성

음식 이미지와 기본적인 코드는 아래 링크를 참고하여 작성하였다.
https://noobtuts.com/unity/2d-snake-game

위 링크에 있는 코드를 토대로 작성하였더니
시간이 지날수록 음식의 개수가 무작위로 생성되는 문제가 발생하였다.
이는 유튜버 "고박사의 유니티 노트"님의 영상을 참고하여
Instantiate() 함수를 이해하고 Object 추가 작업을 함으로써 해결하였다.
https://www.youtube.com/watch?v=IlQ1vLT2tPA&t=145s

FoodSpawner Inspector

 

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

public class SpawnFood : MonoBehaviour
{
    // Food Prefab
    public GameObject foodPrefab;

    // Border
    public Transform borderTop;
    public Transform borderBottom;
    public Transform borderLeft;
    public Transform borderRight;

    void Start()
    {
        // Repeat Function (function name, first delay time, repeat delay time)
        InvokeRepeating("Spawn", 3, 4);
    }

    // Spawn Food
    void Spawn()
    {
        // Food Position in Range of Border
        int x = (int)Random.Range(borderLeft.position.x, borderRight.position.x);
        int y = (int)Random.Range(borderBottom.position.y, borderTop.position.y);

        // Copy Food
        Instantiate(foodPrefab, new Vector2(x, y), Quaternion.identity);
    }
}

 

궁금하신 점은 밑에 댓글 바랍니다