2d platform logic monster

2d patrol back and forth

Pit encountered will automatically turn

Configurable single direction of travel time, waiting time steering

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;//Monster speed 
    public  int turnWaitTime; // steering time 
    public  a float OneTime; // go one direction for 
    public  BOOL AutoTurn = to true ; // in case the automatic steering pit 

    Private  a float nowtime = 0 ;
     Private  int Movedir = 1 ; // moving direction 1 left 
    public Vector3 curSpeed;
     Private  BOOL isPause = to 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);
    }
}

 

Guess you like

Origin www.cnblogs.com/sanyejun/p/11442445.html