Enemy AI Unity2D-平台巡逻移动小怪

Enemy AI Unity2D-平台巡逻移动小怪


前言

简单编写一个unity2D循环移动小怪(纯移动)


场景

下图为一个简单测试场景:
在这里插入图片描述

二、编写代码

代码如下(示例):

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

public class EnemyAI_1 : MonoBehaviour
{
    public float moveSpeed = 10.0f;
    public float circleRadius;
    public bool facingRight;

    private bool isGround;

    public GameObject groundCheck;

    public LayerMask WhatIsGround;

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

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


    private void ApplyMovement()
    {
        rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
    }

    private void CheckIsFlip()
    {
        if (!isGround && facingRight)
        {
            Flip();
        }
        else if (!isGround && !facingRight)
        {
            Flip();
        }
    }

    private void CheckSurrounding()
    {
        isGround = Physics2D.OverlapCircle(groundCheck.transform.position, circleRadius, WhatIsGround);
    }

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

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.green;
        Gizmos.DrawWireSphere(groundCheck.transform.position, circleRadius);
    }
}

该处代码所使用的Ground碰撞图层需要自行添加,还有groundCheck需要自行创建和设置。


总结

如上便简单实现了小怪到了平台边界自动回头

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值