iT邦幫忙

2023 iThome 鐵人賽

DAY 17
0
Software Development

Unity遊戲開發系列 第 17

DAY17 Unity敵人AI(3)

  • 分享至 

  • xImage
  •  

繼續敵人AI的製作,接下做攻擊的部分

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

public class EnemyControl : MonoBehaviour
{
    public enum EnemyBehavior {patrol,battle};
    public EnemyBehavior EnemyNow;
    public enum Battle { follow, attack, dodge };
    public Battle BatChoose;
    public enum checkface { Lelf,Right};
    public checkface face;
    
    //宣告一個射擊武器物件
    public GameObject SpearAttack;    
    public static bool SpearSpr;
    ...
    
    private void FixedUpdate() ...
}

這樣在Inspector的腳本就會出現可以放射擊武器物件的欄位
https://ithelp.ithome.com.tw/upload/images/20231002/20162530wPt2nPunuN.png

 private void FixedUpdate()
    {
        //敵人狀態
        if (!LookForP)
        {
            StartCoroutine(DoCheck());
        }
        switch (EnemyNow) 
        {
            case EnemyBehavior.patrol:
                if (playertransform)
                {
                //巡邏
                    Domove();
                }
                break;
            case EnemyBehavior.battle:
                switch (BatChoose)
                {
                    case Battle.follow:
                        followPlayer();
                        break;
                    case Battle.attack:
                        DoAttack();
                        break;
                }
                break;
        }
    }
void DoAttack()
    {
         if (spr.flipX == true)
         {
                SpearSpr = false;
         }
         esle
         {
                SpearSpr = true
         }
        Instantiate(SpearAttack, this.transform.position, Quaternion.identity);
    }

射擊武器腳本

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

public class SpearControl : MonoBehaviour
{
    public float timer=0;
    public int a = 0;
    public bool direction;
    void Start()
    {
        direction = EnemyControl.SpearSpr;  
    }
    void Update()
    {
        if (direction)
       {
         this.gameObject.transform.position += new Vector3(-1f * Time.deltaTime * 60, 0, 0);
        }
       else 
     {
            this.gameObject.transform.position += new Vector3(1f * Time.deltaTime * 60, 0, 0);
       }
        timer -= Time.deltaTime;
        if (timer <= 0)
        {
            Destroy(this.gameObject);
        }
    }
}

攻擊間隔改好之後再更新

待更


參考資料:


上一篇
DAY16 Unity敵人AI(2)
下一篇
DAY18 Unity敵人AI(4)
系列文
Unity遊戲開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言