找回密码
 立即注册
查看: 335|回复: 0

用Unity做一个盯着你一段时间就会向你冲来的小怪

[复制链接]
发表于 2022-5-5 20:31 | 显示全部楼层 |阅读模式
前言

    由于我的 git失误,导致项目代码中的大眼怪被吞入了无尽虚空(它无了)。找不到办法,只能重新写它的代码。这使我充满了决心!我快速地回忆巩固了一下代码,并记录了下来。
最终效果


还没发现我


糟糕要被发现了


紧张... 被抓到了

动画及状态机部分


状态机


过渡箭头


动画时间轴

代码部分

using System.Collections;using System.Collections.Generic;using UnityEngine;public class BigEyeEnemy : MonoBehaviour{    [Range(0f,10f)]public float detectRadius;    [Range(0f,10f)]public float speed;    public Transform leftPoint, rightPoint;    private Vector2 leftPos, rightPos;    private Animator animator;    private Rigidbody2D rig;    private Transform detectedPlayer;    private bool youMustDie;    private Vector2 tmpVelocity;    void Start()    {        animator = this.GetComponent<Animator>();        rig = this.GetComponent<Rigidbody2D>();        leftPos = leftPoint.position;        rightPos = rightPoint.position;        Destroy(leftPoint.gameObject);        Destroy(rightPoint.gameObject);        rig.velocity = new Vector2(2, 0f);    }        void Update()    {        if (!youMustDie)        {            Move();            Detect();        }        else        {            FlyToPlayer();        }    }    void Move()    {        if(transform.position.x < leftPos.x)        {            rig.velocity = new Vector2(2f,rig.velocity.y);        }        else if (transform.position.x > rightPos.x)        {            rig.velocity = new Vector2(-2f,rig.velocity.y);        }    }    void Detect()    {        Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, detectRadius);        bool flag = false;        foreach (var collider in colliders)        {            if (collider.tag.Equals("Player"))            {                flag = true;                if (!animator.GetBool("humanHere")) //                {                    detectedPlayer = collider.transform;                    //动画逻辑                    animator.SetBool("humanHere", true);                    animator.SetFloat("animSpeed", 1);                    //运动逻辑                    tmpVelocity = rig.velocity;                    rig.velocity = Vector2.zero;                }            }        }        if (!flag && animator.GetFloat("animSpeed")>0.1f)        {            animator.SetFloat("animSpeed", -1);            Debug.Log("倒退了");        }    }    void BackToCloseEyeState()    {        animator.SetFloat("animSpeed",0);        animator.SetBool("humanHere", false);        rig.velocity = tmpVelocity;    }    void PauseEyeOpen()    {        animator.SetFloat("animSpeed", 0);        youMustDie = true;    }    void FlyToPlayer()    {        transform.position = Vector3.Lerp(transform.position, detectedPlayer.position, 0.02f);    }}

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-9-22 13:34 , Processed in 0.090399 second(s), 26 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表