Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question move player away from enemy on collision. no rigidbody

Discussion in 'Scripting' started by pswstephen, May 2, 2024.

  1. pswstephen

    pswstephen

    Joined:
    Mar 18, 2024
    Posts:
    7
    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

    Code (CSharp):
    1. private void OnCollisionEnter(Collision other)
    2. {
    3.  
    4.     if (other.gameObject.tag == "Player")
    5.     {
    6.         Vector3 PushDirection = other.gameObject.transform.position - transform.position;
    7.  
    8.  
    9.         other.transform.position = PushDirection * playerPush * Time.deltaTime;
    10.     }
    11. }
     
  2. dstears

    dstears

    Joined:
    Sep 6, 2021
    Posts:
    165
    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.
     
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,594
    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. ;)
     
    Bunny83 likes this.
  4. pswstephen

    pswstephen

    Joined:
    Mar 18, 2024
    Posts:
    7
    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

    Code (CSharp):
    1. public class Heavycharge : MonoBehaviour
    2.  
    3.  
    4. private Vector3 PushDirection;
    5.  
    6.  
    7.  
    8. private void OnCollisionEnter(Collision other)
    9. {
    10.  
    11.     if (other.gameObject.tag == "Player")
    12.     {
    13.         PushDirection.x = player.transform.position.x - transform.position.x;
    14.         PushDirection.z = player.transform.position.z - transform.position.z;
    15.  
    16.  
    17.  
    18.         player.transform.Translate(PushDirection * playerPush);
    19.     }
    20. }