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, my character 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?