zoukankan      html  css  js  c++  java
  • 2d平台怪物逻辑

    2d来回巡逻

    遇到坑会自动转向

    可配置单次方向行走的时间,转向等待时间等

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using UnityEngine;
    using UnityEngine.Serialization;
    
    [RequireComponent(typeof(Rigidbody2D))]
    public class AI2dPatrol : MonoBehaviour
    {
        public Rigidbody2D body2D;
        public Transform rayPoint;//射线发射点
        public float rayLength = 3;//射线长度
        public float speed = 4;//怪物速度
        public int turnWaitTime;//转向时间
        public float oneTime;//走一个方向的时间
        public bool autoTurn = true;//遇坑自动转向
    
        private float nowTime = 0;
        private int moveDir = 1;//移动方向 1为左
        public Vector3 curSpeed;
        private bool isPause = false;
    
        private void FixedUpdate()
        {
            if (isPause)
            {
                return;
            }
            
            Move();
            if (oneTime > 0)
            {
                if (nowTime >= oneTime)
                {
                    nowTime = 0;
                    TurnFace();
                }
                nowTime += Time.deltaTime;
            }
            if (autoTurn)
            {
                RaycastHit2D groundInfo = Physics2D.Raycast(rayPoint.position, Vector2.down, rayLength);
                if (groundInfo.collider == false)
                {
                    TurnFace();
                }
                //scene模式下显示射线
                Debug.DrawRay(rayPoint.position, Vector2.down * rayLength, Color.blue);
            }
        }
    
        //转向
        async void TurnFace()
        {
            isPause = true;
            await Task.Delay(turnWaitTime * 1000);
            moveDir = -moveDir;
            var origin = transform.localScale;
            transform.localScale = new Vector3(-origin.x, origin.y, origin.z);
            isPause = false;
        }
        
        //移动
        void Move()
        {
            //transform.Translate(Vector2.left * speed * Time.deltaTime * moveDir);
            Vector3 targetVelocity = new Vector2(-moveDir * speed, body2D.velocity.y);
            body2D.velocity = Vector3.SmoothDamp(body2D.velocity, targetVelocity, ref curSpeed, 0.1f);
        }
    }
  • 相关阅读:
    记录操作日志
    sql优化【转】
    JS事件
    MFC电子词典
    控制台电子词典---链表
    控制台电子词典
    贪吃蛇
    十六进制转化
    进程线程
    面试体复习
  • 原文地址:https://www.cnblogs.com/sanyejun/p/11442445.html
Copyright © 2011-2022 走看看