Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Converve gravity action when overriding velocity

Discussion in 'Physics' started by georgenda182, Nov 14, 2023.

  1. georgenda182

    georgenda182

    Joined:
    May 20, 2017
    Posts:
    8
    Hi everyone.

    I have a GameObject with a Rigidbody attached. I'm moving it overriding directly its velocity, which works great. The Y velocity is conserved to work as expected. But with angled walls, the applied horizontal velocity forces it to climb the wall and gravity's action won't take any effect. With 90 angled walls it works fine.

    Is there any alternative to move the object without having to change directly its Rigidbody's velocity?
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,105
    Yes, use physics queries to determine if you can move rather than blindly changing the velocity. The solver has no idea about your custom behaviour because, well, it’s custom so you need to control that.
     
  3. georgenda182

    georgenda182

    Joined:
    May 20, 2017
    Posts:
    8
    Thank you so much, @MelvMay. Could you provide an example, please?
     
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,105
    Example of what specifically? How to use physics queries? That would be a tutorial really. ;)
     
  5. georgenda182

    georgenda182

    Joined:
    May 20, 2017
    Posts:
    8
    My apologize, I failed to specify. Having this method that changes the velocity of a rigidbody and tries to maintain without any success the gravity effect over it inheriting the vertical velocity and while the body is moving against an angled wall, how could you conserve both forizontal and vertical velocity using physics queries?

    Code (CSharp):
    1. private void SetBodyVelocity()
    2. {
    3.     float verticalVelocity = _playerRigidbody.velocity.y;
    4.     Vector3 newVelocity = _playerTransform.forward * _velocity;
    5.     newVelocity.y = verticalVelocity;
    6.     _playerRigidbody.velocity = newVelocity;
    7. }
     
    Last edited: Nov 16, 2023