需要协同协程 - 有限状态机

时间:2018-06-06 01:39:42

标签: coroutine

我是Unity和C#的新手,并且一直试图获得某种协程 - State Machine为我的敌人AI工作。我在网上看了很多很多视频,在Unity页面和StackOVerflow上阅读了无数的论坛,而且还没有能够

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AI_Test: MonoBehaviour {
  private EnemyActionType eCurState=EnemyActionType.Idle;
  private bool dirRight=true;
  public float speed=2.0f;
  bool turning=false;
  bool facingRight=true;
  public enum EnemyActionType {
    Idle,
    Moving,
    AvoidingObstacle,
    Attacking
  }
  IEnumerator MoveLeft() {
    yield return new WaitForSeconds(1.0f);
    dirRight=false;
    if (dirRight==false) transform.Translate(Vector2.left * speed * Time.deltaTime);
    turning=true;
    Debug.Log("Moving Left");
    yield return new WaitForSeconds(1.5f); //The longer I make this the further the enemy goes, but doesnt stop him from 'twitching'
    StartCoroutine(MoveRight());
  }
  IEnumerator MoveRight() {
    yield return new WaitForSeconds(1.0f);
    dirRight=true;
    if (dirRight) transform.Translate(Vector2.right * speed * Time.deltaTime);
    turning=false;
    Debug.Log("Moving Right");
    yield return new WaitForSeconds(1.5f); //The longer I make this the further the enemy goes, but doesnt stop him from 'twitching'
    StartCoroutine(MoveLeft());
  }
  void Update () {
    switch(eCurState) {
      case EnemyActionType.Idle: if (dirRight) transform.Translate(Vector2.right * speed * Time.deltaTime);
      turning=true;
      StartCoroutine(MoveLeft());
      //HandleIdleState();  <---No idea what should be in this function
      break;
      case EnemyActionType.Moving: if (dirRight==false && transform.position.x >=1.0f) //Took out the 2nd half of the argument and nothing happened, not sure what the 2nd part does 
      transform.Translate(Vector2.right * speed * Time.deltaTime);
      //HandleMovingState(); <---No idea what should be in this function
      break;
      case EnemyActionType.Attacking: //Eventually going to add this, trying to get moving left and right correct first.
      break;
    }
  }
  private void FixedUpdate() {
    if (turning==true && !facingRight) Flip();
    else if (turning==false && facingRight) Flip();
  }
  void Flip() {
    facingRight=!facingRight;
    Vector3 theScale=transform.localScale;
    theScale.x *=-1;
    transform.localScale=theScale;
  }
}

o让这个工作正常。我正在尝试使用C#在我的2D平台游戏中创建一个类似Zelda或类似Megaman的老板。我有4种状态:空闲,移动,避免障碍(甚至尚未触及)和攻击。目前,我有一个MoveLeft协程和一个MoveRight协程,它们处于Moving状态。我的敌人可以向左和向右移动,他开始向左走,一旦他开始向右走,他便开始“抽搐”并来回翻转一吨,但他仍然做了一些巡逻。我无法让他完全离开,然后完全向右走,并重复直到他需要进入攻击状态。在我的代码的某处,MoveRight和MoveLeft在他到达正确的目的地或他应该移动的时间之前被多次调用,我对任何阻止他的方式持开放态度。

这是我能找到的最好的论坛,它很容易理解,对我来说很有意义,但它已经过时了,一些更有用的链接不起作用。 https://forum.unity.com/threads/where-to-start-learning-ai-cpu-and-boss-scripting.266498/

到目前为止,这是我的代码:

0 个答案:

没有答案