user4331901
user4331901

Reputation:

Push player away from the enemy

I've made my own controller for the game I'm trying to make but I've ran into some issues with it. Whenever the enemy is approaching me and I don't stop my character in time, he teleports on top of the enemy's head.

Push away:

void OnControllerColliderHit(ControllerColliderHit hit)
{
    if (hit.gameObject.GetComponent<EnemyController>())
    {
        Debug.Log("!");
        float pushPower = 0.05f;
        Vector3 pushDir = hit.transform.forward;
        characterController.Move(pushDir * pushPower);
    }
}

Movement:

void FixedUpdate()
{
    RaycastHit hitInfo;
    Physics.SphereCast(transform.position, characterController.radius, Vector3.down, out hitInfo, characterController.height / 2f);
    desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;

    desiredMove = (transform.forward * Input.GetAxis("Vertical") + transform.right * Input.GetAxis("Horizontal")).normalized;

    if(characterController.isGrounded)
    {
        moveDir.x = desiredMove.x * speed;
        moveDir.z = desiredMove.z * speed;
        isJumping = false;

        if(Input.GetButtonDown("Jump"))
        {
            moveDir.y = jumpPower;
            isWalking = false;
            isJumping = true;
            canRun = false;
        }

        if(Input.GetButton("Sprint") && canRun)
        {
            isWalking = false;
            isRunning = true;
            moveDir.x = desiredMove.x * runSpeed;
            moveDir.z = desiredMove.z * runSpeed;
        }
        else
        {
            isRunning = false;
        }


    }
    else
    {
        Falling();
    }
    characterController.Move(moveDir * Time.fixedDeltaTime);
}

I've decided to add a function to push player away if he's too close to the enemy but I can't really get it to work right. Right now it pushes player in the forward direction of the enemy so it works fine when you're approaching the enemy from the front, in other cases my player just teleports in front of the enemy. I wanted to push the player away to the direction he came from but I can't really think of any way to do it. Could anyone help me out with it?

Upvotes: 2

Views: 1650

Answers (1)

Clay Fowler
Clay Fowler

Reputation: 2078

To push away from the enemy, you would do something like:

Vector3 direction = (enemy.transform.position - player.transform.position).normalized;
player.transform.position += direction * DISTANCE_YOU_WANT_TO_PUSH;

In your case, since you're already dealing with a collision inside of OnControllerColliderHit, it would be more like:

Vector3 direction = (hit.point - transform.position).normalized

In both cases, you might want to set direction.y = 0 before normalizing it (if you only want to be pushed away along the ground plane, for example).

Upvotes: 1

Related Questions