유니티 C# 간단한 뱀서라이크 게임 만들기 간단 구현 코드 예시

반응형

코드 작성

using UnityEngine;
using System.Collections.Generic;

public class SnakeController : MonoBehaviour
{
    public float moveSpeed = 0.1f;
    public Vector2 direction = Vector2.right;
    public List<Transform> bodyParts = new List<Transform>();
    public GameObject bodyPrefab;

    void Start()
    {
        InvokeRepeating("Move", 0.1f, moveSpeed);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            direction = Vector2.up;
        }
        else if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            direction = Vector2.down;
        }
        else if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            direction = Vector2.left;
        }
        else if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            direction = Vector2.right;
        }
    }

    void Move()
    {
        Vector2 currentPos = transform.position;
        transform.Translate(direction);

        if (bodyParts.Count > 0)
        {
            bodyParts[bodyParts.Count - 1].position = currentPos;
            bodyParts.Insert(0, bodyParts[bodyParts.Count - 1]);
            bodyParts.RemoveAt(bodyParts.Count - 1);
        }
    }

    void Grow()
    {
        GameObject newPart = Instantiate(bodyPrefab, bodyParts[bodyParts.Count - 1].position, Quaternion.identity);
        bodyParts.Add(newPart.transform);
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Food")
        {
            Grow();
            Destroy(other.gameObject);
        }
    }
}
반응형