Example #1
0
        IEnumerator Move()
        {
            while (true)
            {
                yield return(new WaitForSeconds(config.StepCooldown));

                Segment tailSegment = segments.First();

                if (hasAppleToEat)
                {
                    hasAppleToEat = false;

                    SetRandomDirectionCoroutine = StartCoroutine(SetRandomDirection());
                    tailSegment = Instantiate(segmentPrefab, transform);
                }
                else
                {
                    field[tailSegment.PositionOnField.X, tailSegment.PositionOnField.Y, tailSegment.PositionOnField.Z] = null;
                    segments.Remove(tailSegment);
                }

                CheckDirection();


                tailSegment.PositionOnField = new PositionOnField(headSegment.PositionOnField.X, headSegment.PositionOnField.Y, headSegment.PositionOnField.Z);

                switch (currentDirection)
                {
                case Direction.Up:
                    tailSegment.PositionOnField.Y++;
                    break;

                case Direction.Down:
                    tailSegment.PositionOnField.Y--;
                    break;

                case Direction.Left:
                    tailSegment.PositionOnField.X--;
                    break;

                case Direction.Right:
                    tailSegment.PositionOnField.X++;
                    break;

                case Direction.Forward:
                    tailSegment.PositionOnField.Z++;
                    break;

                case Direction.Backward:
                    tailSegment.PositionOnField.Z--;
                    break;
                }

                tailSegment.transform.position = new Vector3(tailSegment.PositionOnField.X, tailSegment.PositionOnField.Y, tailSegment.PositionOnField.Z) * config.Step;

                headSegment.SetMaterial(tailMaterial);
                tailSegment.SetMaterial(headMaterial);
                segments.Add(tailSegment);

                LevelObject newHeadFieldPoint = field[tailSegment.PositionOnField.X, tailSegment.PositionOnField.Y, tailSegment.PositionOnField.Z];

                if (newHeadFieldPoint != null && newHeadFieldPoint.Type == LevelObjectTypes.Segment)
                {
                    OnCollision(this);
                    segments.Clear();
                    Destroy(gameObject);
                }

                if (newHeadFieldPoint != null && newHeadFieldPoint.Type == LevelObjectTypes.Apple)
                {
                    OnAppleEaten(tailSegment.PositionOnField);
                    hasAppleToEat = true;
                }

                field[tailSegment.PositionOnField.X, tailSegment.PositionOnField.Y, tailSegment.PositionOnField.Z] = tailSegment;

                headSegment = tailSegment;
            }
        }