Enemy AI Unity2D-小怪在固定范围类进行巡逻

Enemy AI Unity2D-小怪在固定范围类进行巡逻

  • 前言
  • 一、场景准备
  • 二、编写代码
  • 总结


前言

本次单纯是巡逻移动代码,可自行添加攻击等行为


一、场景准备

准备如下一个固定场景
Enemy AI Unity2D-小怪在固定范围类进行巡逻_第1张图片

二、编写代码

代码如下:

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

public class EnemyFlyAI_2 : MonoBehaviour
{
    public float flySpeed = 5.0f;
    public float circleRadius;
    private Rigidbody2D rb;

    public GameObject topCheck, wallCheck, rootCheck;
    public LayerMask whatIsGround;

    public bool facingRight = true, isToucingWall, isToucingTop, isTouchingRoot;

    public float dirX = 1.0f, dirY = 0.25f;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    
    void Update()
    {
        CheckSurrounding();
        HitLogic();
        ApplyMovement();
    }

    private void CheckSurrounding()
    {
        isToucingWall = Physics2D.OverlapCircle(wallCheck.transform.position, circleRadius, whatIsGround);
        isTouchingRoot = Physics2D.OverlapCircle(rootCheck.transform.position, circleRadius, whatIsGround);
        isToucingTop = Physics2D.OverlapCircle(topCheck.transform.position, circleRadius, whatIsGround);

    }

    private void HitLogic()
    {
        if (isToucingWall && facingRight)
        {
            Flip();
        }else if (isToucingWall && !facingRight)
        {
            Flip();
        }
        if (isTouchingRoot)
        {
            dirY = 0.25f;
        }else if (isToucingTop)
        {
            dirY = -0.25f;
        }
    }

    private void ApplyMovement()
    {
        rb.velocity = new Vector2(dirX, dirY) * flySpeed;
    }

    private void Flip()
    {
        facingRight = !facingRight;
        transform.Rotate(new Vector3(0.0f, 180.0f, 0.0f));
        dirX = -dirX;
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.blue;
        Gizmos.DrawWireSphere(wallCheck.transform.position, circleRadius);
        Gizmos.DrawWireSphere(topCheck.transform.position, circleRadius);
        Gizmos.DrawWireSphere(rootCheck.transform.position, circleRadius);
    }
}

设置如下:
Enemy AI Unity2D-小怪在固定范围类进行巡逻_第2张图片

总结

最后完成能使一个怪物能在被墙体包裹的范围内进行移动,后续攻击行为等可以自行添加。欢迎各位小伙伴进行分享更好的方法,例如怎么把它固定在不是墙的范围内移动等等。

你可能感兴趣的:(学习Unity,人工智能,unity,游戏引擎,c#)