Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question How to limit rigidbody movements on X coordinate without isKinematic?

Discussion in 'Physics' started by piscopancer, Aug 23, 2021.

  1. piscopancer

    piscopancer

    Joined:
    Jul 24, 2021
    Posts:
    15
    upload_2021-8-23_15-25-15.png
    So here imagine a Traffic Racer game. Played it? car hits the barrier and doesn't go beyond it. My car moves with `setVelocity` and I need it to stop moving on X coordinate to left when hits left barrier and right when hits right barrier. And keep in mind that it must not lose its Z value velocity so it continues moving forward
     
  2. mustafacomert00

    mustafacomert00

    Joined:
    Feb 17, 2020
    Posts:
    5
    You can add colliders(isTrigger unchecked) to left and right barriers,

    if you don't want that,
    you can clamp car's x position between -7 and 7 like this:

    Code (CSharp):
    1. void Update()
    2. {
    3.     Vector3 pos = transform.position;
    4.     pos.x = Mathf.Clamp(pos.x, -7, 7);
    5.     transform.position = pos;
    6. }
     
    piscopancer likes this.
  3. theCyberStallion

    theCyberStallion

    Joined:
    Oct 3, 2020
    Posts:
    29
    another thing you might want in addition to clamping the x position:
    Code (CSharp):
    1. //instead of:
    2. rb.velocity = new Vector3(0, rb.velocity.y, rb.velocity.z); //stop x velocity
    3. //do this:
    4. float energyLoss = some reasonable value, maybe 10f;
    5. rb.velocity = new Vector3(-rb.velocity.x/energyLoss, rb.velocity.y, rb.velocity.z); // or bounce the x velocity(with energy loss to make sure you cant gain infinite x axis speed)
     
    Last edited: Jan 19, 2022
    piscopancer likes this.