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

How to keep a ball bouncing around at a fixed speed?

Discussion in 'Scripting' started by Paul-Boland, Aug 21, 2018.

  1. Paul-Boland

    Paul-Boland

    Joined:
    Jun 28, 2013
    Posts:
    50
    Hi Folks.

    I am creating a bat & ball game. I have an arena walled on three sides. a bat down on the unwalled forth side, and a ball and lots of bricks. My ball bounces around fine, destroying bricks it hits, but it slows down as it does so until eventually it comes to a complete stop. I know about physics materials and I have a super bouncy frictionless material on the bat and walls, but I can't put it on the blocks because it causes them to bounce around like mad when they fall.

    What I need is a way to access the velocity of the ball and keep it set at a specific speed. I have tried numerous code ideas but without any success, or weird results! Can anyone please give me some idea on how to constantly set and keep a balls velocity at a set number?
     
  2. kru

    kru

    Joined:
    Jan 19, 2013
    Posts:
    452
    You can force a rigidbody to have a fixed velocity by setting its velocity's length every frame, without changing its direction.
    Code (csharp):
    1. float speed = some speed
    2. rigidbody.velocity = rigidbody.velocity.normalized * speed;
     
  3. Paul-Boland

    Paul-Boland

    Joined:
    Jun 28, 2013
    Posts:
    50
    That works great, thank you very much!
     
  4. TobiasString

    TobiasString

    Joined:
    Dec 14, 2020
    Posts:
    1
    This helped me out a ton as well, thank you!