Functions of the EnemyBaseClass

PHOTO EMBED

Mon Sep 25 2023 09:08:33 GMT+0000 (Coordinated Universal Time)

Saved by @BenjiSt #c#

protected void UpdateSortingOrder()
    {
        enemySr.sortingOrder = Mathf.RoundToInt((1-Mathf.Lerp(0, 1, _mainCamera.WorldToViewportPoint(transform.position).y))*100);
    }

    
    protected void Move()
    {
        var currPosition = transform.position;
        Vector2 desiredVelocity = (player.position - currPosition).normalized * enemyStats.movementSpeed;
        Vector2 velocity = enemyRb.velocity;
        
        // Has no effect, statement is never true
        if (velocity.magnitude > 1.05 * enemyStats.movementSpeed)
        {
            StartCoroutine(FixMovementSpeed());
            Debug.Log("Fixed MovementSpeed!");
        }
        else
        {
            //calculate a steering value:
            var steering = (desiredVelocity * Time.fixedDeltaTime - velocity);

            //ensure the steering isn't too strong
            steering = Vector2.ClampMagnitude(steering, maxSteeringForce);

            //apply the steering force by setting the velocity
            velocity = velocity + steering;
        
            //set animator parameters
            Vector2 facing = velocity.normalized;
            enemyAnimator.SetFloat("XFacing", facing.x);
            enemyAnimator.SetFloat("YFacing", facing.y);

            if (debug)
            {
                Debug.DrawLine(currPosition, (Vector2)currPosition + velocity * 60, Color.white);
                Debug.DrawLine(currPosition, (Vector2)currPosition + desiredVelocity * 60, Color.red);
                Debug.DrawLine((Vector2)currPosition + velocity * 60, (Vector2)currPosition + velocity * 60 + steering * 600, Color.green);
            }

            //Rigidbody moveposition function is used here, as it resolves collisions. As such, this function is written in FixedUpdate
            enemyRb.MovePosition(transform.position + (Vector3)velocity);

            //make the sprite face the direction it is travelling (unless we said not to, in the case of the player object)
            if (rotateSprite) transform.rotation = Quaternion.LookRotation (Vector3.forward, (Vector2)(transform.position - prevPosition));

            //calculate the velocity (for others to read)
            velocity = (Vector2)(transform.position - prevPosition);
            prevPosition = currPosition;
        }
    }


    private IEnumerator FixMovementSpeed()
    {
        enemyRb.constraints = RigidbodyConstraints2D.FreezeAll;
        yield return new WaitForSeconds(0.05f);
        enemyRb.constraints = RigidbodyConstraints2D.FreezeRotation;
    }
content_copyCOPY