Заставить NPC идти вверх и вниз в UNITY - PullRequest
0 голосов
/ 08 марта 2019

Итак, у меня есть этот код, он состоит в том, чтобы заставить врага подниматься и опускаться, используя путевые точки, он действительно работает, но по странной причине после некоторого зацикливания между путевыми точками он проходит до бесконечности, проходя верхнюю путевую точку.(wp0), почему это происходит ???Я играю с кодом, но ничего не получаю подходящего поведения.

Код для NPC, у которого есть кинематическое твердое тело, он "плавает" в воздухе и склонен летать вверх и вниз, каклетающие купы в игре Mario Bros ...

public GameObject[] myWaypoints;
float direction = 1f; //1 up, 0 stop. -1 down.
int _myWaypointIndex = 0; // used as index for My_Waypoints
float _moveTime;
float _vx = 0f;
bool _moving = true;
public float waitAtWaypointTime = 1f;   // how long to wait at a waypoint
public bool loopWaypoints = true; // should it loop through the waypoints

void EnemyMovement()
{
    // if there isn't anything in My_Waypoints
    if ((myWaypoints.Length != 0) && (_moving))
    {

        // make sure the enemy is facing the waypoint (based on previous movement)
        Flip(_vx);

        // determine distance between waypoint and enemy
        _vx = myWaypoints[_myWaypointIndex].transform.position.y - _transform.position.y;

        direction = Mathf.Sign(myWaypoints[_myWaypointIndex].transform.position.y);
        Debug.Log("Direction = " + direction);

        // if the enemy is close enough to waypoint, make it's new target the next waypoint
        if (Mathf.Abs(_vx) <= 0.05f)
        {
            Debug.Log("changin to the next waypoint");

            // At waypoint so stop moving
            _rigidbody.velocity = new Vector2(0, 0);

            // increment to next index in array
            _myWaypointIndex++;

            Debug.Log("_myWaypointIndex = " + _myWaypointIndex);
            Debug.Log("Length = " + myWaypoints.Length);
            direction *= -1;
            Debug.Log("New Direction = " + direction);

            // reset waypoint back to 0 for looping
            if (_myWaypointIndex >= myWaypoints.Length)
            {
                Debug.Log("True");
                if (loopWaypoints)
                {
                    _myWaypointIndex = 0;
                }
                else
                {
                    _moving = false;
                }
            }

            // setup wait time at current waypoint
            _moveTime = Time.time + waitAtWaypointTime;
        }
        else
        {
            // enemy is moving
            _animator.SetBool("Moving", true);

            // Set the enemy's velocity to moveSpeed in the y direction.
            _rigidbody.velocity = new Vector2(0.0f, _transform.localScale.y * moveSpeed * direction);

        }

    }
}

Ответы [ 3 ]

0 голосов
/ 08 марта 2019

Может быть: что произойдет, если враг пройдет последнюю путевую точку и _vx> 0.05f?

это не будет поймано в:

if (Mathf.Abs(_vx) <= 0.05f)
0 голосов
/ 08 марта 2019

Проблема в том, что в Mathf.abs (_vx) <= 0,05f значение _vx никогда не достигает значения ниже 0,05f. </p>

Что вы должны сделать, это прикрепить триггер к путевой точке и изменить координаты путевой точки, когда игрок вступит в контакт с этим триггером.

Или сделай это.

_vx =   Mathf.Abs(myWaypoints 
[_myWaypointIndex].  
transform.position.y) - 
Mathf.Abs(_transform.position.y);

//And then write.

if (_vx <= 0.5f)
   // change coordinate.'''
0 голосов
/ 08 марта 2019

Я думаю, что проблема в том, что когда вы сбрасываете _myWaypointIndex в 0, loopWaypoints находится в какой-то другой функции, но в противном случае NPC не останавливается, поэтому, возможно, продолжает двигаться к следующей путевой точке, которую он не может найти, потому что индекс не был сброшен, поэтому расстояние _vx никогда не будет равно 0, попробуйте проверить, изменяют ли значения loopWaypoints, когда вы хотите, возможно, ошибка там.

        if (loopWaypoints)
        {
            _myWaypointIndex = 0;
        }
        else
        {
            _moving = false;
            //Stop the movment 
            moveSpeed = 0;
        }
...