用Unity做一个盯着你一段时间就会向你冲来的小怪
前言由于我的 git失误,导致项目代码中的大眼怪被吞入了无尽虚空(它无了)。找不到办法,只能重新写它的代码。这使我充满了决心!我快速地回忆巩固了一下代码,并记录了下来。
最终效果
还没发现我
糟糕要被发现了
紧张... 被抓到了
动画及状态机部分
状态机
过渡箭头
动画时间轴
代码部分
using System.Collections;using System.Collections.Generic;using UnityEngine;public class BigEyeEnemy : MonoBehaviour{ public float detectRadius; 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); }}
页:
[1]