Example #1
0
    /*enum MeleeFighterState
     * {
     *  TooFar,
     *  TooNear,
     *  InMeleeDistance
     * }
     *
     * MeleeFighterState state;*/

    protected override void Update()
    {
        if (Time.time > nextDistanceCheckTime)
        {
            nextDistanceCheckTime = Time.time + distanceCheckingInterval;

            myWidth    = entity.width;
            enemyWidth = enemySensing.nearestEnemy.width;

            Vector3 nearestEnemyPosition = enemySensing.nearestEnemy.transform.position;
            Vector3 myPosition           = entity.transform.position;

            float   widthFactor    = myWidth + enemyWidth; //multiply the resulting distanceVectorBythisFactor to also use width
            Vector3 distanceVector = nearestEnemyPosition - myPosition;
            //float distanceToEnemySquared = (distanceVector - distanceVector.normalized * widthFactor).sqrMagnitude;
            float distanceToEnemy = (distanceVector - distanceVector.normalized * widthFactor).magnitude;

            //if the enemy is moving, we move to the position he will be at the time we arrive
            EC_Movement enemyMovement = enemySensing.nearestEnemy.GetComponent <EC_Movement>();


            if (enemyMovement.IsMoving())
            {
                //heuristically calculae future position
                //1. how long will it take for me to reach the enemy?
                float timeToReachEnemy = distanceToEnemy / movement.GetMaxSpeed();
                //2. where will the enemy be after this time
                Vector3 futurePosition = nearestEnemyPosition + enemyMovement.GetCurrentVelocity() * timeToReachEnemy;


                movement.MoveTo(futurePosition);
            }
            else
            {
                movement.MoveTo(nearestEnemyPosition + (myPosition - nearestEnemyPosition).normalized * (perfectMeleeDistance + myWidth + enemyWidth));
            }

            if ((nearestEnemyPosition - myPosition).sqrMagnitude > maxMeleeDistance)
            {
                inRange = false;
                movement.StopLookAt();
            }
            else
            {
                inRange = true;
                movement.LookAt(enemySensing.nearestEnemy.transform);
            }
        }

        if (inRange)
        {
            if (weapon.CanAttack())
            {
                weapon.Attack();
            }
        }
    }