前言
简单编写一个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需要自行创建和设置。
总结
如上便简单实现了小怪到了平台边界自动回头