iT邦幫忙

2025 iThome 鐵人賽

0
自我挑戰組

從零開始做出我的第一款 Unity 遊戲系列 第 14

DAY14-讓貪吃蛇吃東西吧!(2)

  • 分享至 

  • xImage
  •  

為了要讓蘋果被蛇吃掉後,隨機生成在遊戲畫面內,我們要在hierarcky中創立新的物件foodarea,也要幫foodarea加上collider,不過這次是選box collider,不是circle collider,然後要記得調整大小
https://ithelp.ithome.com.tw/upload/images/20251020/20178853k9lVYdmra7.png

打開先前創好的apple腳本,並輸入這段程式碼:

using UnityEngine;

public class Apple : MonoBehaviour
{
    public Collider2D foodarea;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {

    }
    private void OnEnter2D(Collider2D collision)
    {
        Debug.Log(collision);
    }
}

回到unity後,把左邊hierarcky的foodarea拉到剛剛在apple inspector裡的foodarea中
https://ithelp.ithome.com.tw/upload/images/20251020/201788533ipljdM9Lu.png
接著又要回到前面的apple腳本,並輸入這段程式碼:

using System.ComponentModel;
using UnityEngine;

public class Apple : MonoBehaviour
{
    public Collider2D foodarea;
    void Start()
    {
        RandomPosition();
    }

    // Update is called once per frame
    void Update()
    {

    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.Log(collision);

        Debug.Log(foodarea.bounds.min.x);
        Debug.Log(foodarea.bounds.max.x);
        Debug.Log(foodarea.bounds.min.y);
        Debug.Log(foodarea.bounds.max.y);


        RandomPosition();
    }
    
    void RandomPosition()
    {
        transform.position = new Vector3(
            Random.Range(foodarea.bounds.min.x, foodarea.bounds.max.x),
            Random.Range(foodarea.bounds.min.y, foodarea.bounds.max.y),
            0);
    }
}

這樣蘋果被貪吃蛇吃掉以後還會在場景範圍內生成了!


上一篇
DAY13-讓貪吃蛇吃東西吧!
下一篇
DAY15-讓貪吃蛇變長
系列文
從零開始做出我的第一款 Unity 遊戲21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言