Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Push player back in -z direction regardless of contact point

Discussion in 'Scripting' started by Alien_J, Jun 25, 2023.

  1. Alien_J

    Alien_J

    Joined:
    May 29, 2019
    Posts:
    67
    I'm creating a simple game where you guide the player through lanes. The player moves automatically in the z direction (forward). It does have a rigidbody.

    I'm trying to get the player to bounce back in the -z direction when it comes in contact with a square obstacle, regardless of which part of the player comes in contact with the obstacle.

    Every example I have looked at uses contact points. Which bounces the player in different directions.

    Any tips or info or what to look for would be greatly appreciated.
     
  2. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    510
    Code (CSharp):
    1.     void OnCollisionEnter(Collision collision)
    2.     {
    3.         if (collision.gameObject.CompareTag("square"))
    4.             GetComponent<Rigidbody>().velocity=new Vector3(0,0,-4);
    5.     }
     
  3. Alien_J

    Alien_J

    Joined:
    May 29, 2019
    Posts:
    67

    Oh my gawd. Thank you so much. Works perfect. And....ummm...my brain must have been shut off, I forgot about the square obstacle being tagged "Obstacle".

    I know, I know.

    Aagain, huge thanks.
     
  4. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,503
    Another approach is to set the obstacle colliders to be triggers. This way you can still detect collision with the trigger, but the collision won't generate forces or move the body at all, and you can do your own AddForce(new Vector3(0,0,bounceForce)).

    This could be useful if, for instance, you already have other forces acting on the body which you don't want to override.
     
  5. Alien_J

    Alien_J

    Joined:
    May 29, 2019
    Posts:
    67
    Yes, thank you. I was just thinking about the AddForce. Since the player can speed up if he hits boosters, I can add different levels of force depending on how fast or slow he is going.

    Thank you again.