码迷,mamicode.com
首页 > 其他好文 > 详细

2d平台怪物逻辑

时间:2019-09-01 16:39:56      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:thread   pos   net   tar   round   模式   时间   wait   次方   

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);
    }
}

 

2d平台怪物逻辑

标签:thread   pos   net   tar   round   模式   时间   wait   次方   

原文地址:https://www.cnblogs.com/sanyejun/p/11442445.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!