2D游戏入门——小狐狸系列(十五)为敌人添加简单的AI

Session15:AI敌人移动

为敌人添加一个移动效果,通过添加左右的子object来设定移动的距离:

image-20211103191929356

public class Enemy_Frog : MonoBehaviour
{
    public Rigidbody2D rb;
    public Transform leftpoint, rightpoint;
    public float speed;
    //控制转向,默认向左
    private bool faceLeft = true;
    private float leftx, rightx;
    
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        transform.DetachChildren();
        //获取子物体坐标
        leftx = leftpoint.position.x;
        rightx = rightpoint.position.x;
        //销毁子物体
        Destroy(leftpoint.gameObject);
        Destroy(rightpoint.gameObject);
    }

    // Update is called once per frame
    void Update()
    {
        Movement();
    }

    void Movement()
    {
        if(faceLeft)
        {
            rb.velocity = new Vector2(-speed, rb.velocity.y);
            if(transform.position.x < leftx)
            {
                transform.localScale = new Vector3(-1, 1, 1);
                faceLeft = false;
            }
        }
        else
        {
            rb.velocity = new Vector2(speed, rb.velocity.y);
            if(transform.position.x > rightx)
            {
                transform.localScale = new Vector3(1, 1, 1);
                faceLeft = true;
            }
        }
        
    }
}

设置好这些之后,将敌人变成预制体,放到场景中,就可以分别调整每一个敌人各自子物体的位置来调整各自的移动范围。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值