Search Unity

[C#] Wall Bounce While Setting Velocity for a Racing Game?

Discussion in 'Physics' started by BodaciousP, Dec 12, 2018.

  1. BodaciousP

    BodaciousP

    Joined:
    Jan 16, 2015
    Posts:
    3
    I'm trying to get my player vehicle to bounce slightly off the walls of the course when collision occurs. It would be simple, but my problem is I'm setting velocity every frame to accommodate for increases/decreases in speed tied to the press of a button. I can't have the velocity being applied through AddForce because when I turn the vehicle doesn't turn right away if I don't have the drag turned up high, and then when I have the drag up high wall bounces don't work either. Attached is a snippet of the vehicle script that I've been using. Any help is much appreciated.



    if (Input.GetButton("Move") && timeHold < maxSpeed) {
    timeHold += Time.deltaTime;
    } else if (timeHold > 0f) {
    timeHold -= Time.deltaTime * 2;
    }

    if (timeHold > maxSpeed) {
    timeHold = maxSpeed;
    }

    if (timeHold > 0f) {
    rb.velocity = (timeHold * accelleration) * transform.forward;
    } else {
    rb.velocity = 0 * transform.forward;
    }

    transform.Rotate(transform.up, handling * Input.GetAxis("Horizontal") * Time.deltaTime, Space.World);
     
  2. JuozasK

    JuozasK

    Unity Technologies

    Joined:
    Mar 23, 2017
    Posts:
    84
    Well first off all, what physicsMaterials are your car and the wall using? Not the direct solution, but something to look at first.
    If you want bounciness, you should have a physicsMaterial that has the bounciness property set to a higher value
     
  3. BodaciousP

    BodaciousP

    Joined:
    Jan 16, 2015
    Posts:
    3
    I have a material that has bounciness set to the maximum on the walls. I've tried it on the player and on both too and that doesn't work either.
     
  4. JuozasK

    JuozasK

    Unity Technologies

    Joined:
    Mar 23, 2017
    Posts:
    84
    Well yeah, with the drag set up high, the objects will not have a lot of freedom to react accordingly. My guess would be that you'd then need to get the angle and the point of collision and add velocity to your object in an opposite angle.

    But that'd be pretty difficult to achieve.
    I think you'd be better off keeping the drag low to have bounciness solved by the physics engine and then figuring out a way to control your vehicle from there.