move player away from enemy on collision. no rigidbody

im using transform.translate for movement and need help with a script that pushes the player back on the x and z axis if the enemy collides with them. issue is that it pushes the player down on the y and they get stuck.

changing to addforce with rigidbody is not an option

private void OnCollisionEnter(Collision other)
{

    if (other.gameObject.tag == "Player")
    {
        Vector3 PushDirection = other.gameObject.transform.position - transform.position;


        other.transform.position = PushDirection * playerPush * Time.deltaTime;
    }
}

You can set PushDirection.y = 0 before you apply it to the other transform.

I’m not sure if Time.deltaTime really applies here. Time.detlaTime varies based on the render time of every frame, but this collision event only happens once per collision. This means the amount of motion you get will vary based on the time it took to render that specific frame.

If you’re not using a Rigidbody then you’ve got a Static (non-moving) collider. If you want to explicitly move a collider then you use a Rigidbody set to Kinematic. Of course, as always, feel free to ignore this and bypass physics by modifying the Transform in the hope of making it better. :wink:

1 Like

thank you a bunch for the help i needed to 1 classify the pushDirection at the top of the code and call it using transform.Translate. you were right the Time.deltaTime wasnt doing anything.

heres the code i ended with

public class Heavycharge : MonoBehaviour


private Vector3 PushDirection;



private void OnCollisionEnter(Collision other)
{

    if (other.gameObject.tag == "Player")
    {
        PushDirection.x = player.transform.position.x - transform.position.x;
        PushDirection.z = player.transform.position.z - transform.position.z;



        player.transform.Translate(PushDirection * playerPush);
    }
}