How can I set a bouncing ball's angle at any time?

Hi Folks.

I have spent too much time trying to get this to work without success. I have a ball bouncing around a level using physics but with gravity turned off, so it just bounces up and down and left and right and forward and backward. However, on a whim, at any time, I want to change it’s direction. I want to specify an angle and have the ball suddenly change whatever way it’s going, to the angle I specify. I can not get this to work and I’ve tried many different ideas without success. Can anyone tell me how to achieve this please?

I am not sure what do you mean about “angle”, but maybe you could use something like this:

using UnityEngine;

public class BouncingBall : MonoBehaviour
{
    public Rigidbody rb;
    public Vector3 targetAngle;
    public float rayScale = 1.0f;
    // Start is called before the first frame update
    void Start()
    {
        rb.velocity = Vector3.up;
    }

    private void FixedUpdate()
    {
        GoToAngle(targetAngle);
    }

    private void GoToAngle(Vector3 eulerAngle)
    {
        Quaternion targetRotation = Quaternion.Euler(eulerAngle);
        Vector3 targetDirection = targetRotation * Vector3.forward;
        float speed = rb.velocity.magnitude;
        rb.velocity = speed * targetDirection;
    }

    private void OnDrawGizmos()
    {
        Gizmos.DrawRay(this.transform.position, rayScale*rb.velocity);
    }
}

First, you create a rotation with the target angle. The ball is going to move in the direction of its velocity, so you create a velocity rotated by the target angle.

Thanks for this, much appreciated. Gives me some pointers to explore.

Glad to hear it :wink:

Okay, I’m still stuck on this. Surely it can’t be this difficult to achieve.

What I’m trying to do is at any given time, I want to specify a specific direction I want a bouncing ball to moving in. For example, on pressing a key, I want the ball to change whatever direction it is moving in, and for it to travel at a set angle, such as upwards at 60 degrees along the world Z axis, with 0 degrees in any other direction. I would assume rotating the ball to 60.0f, 0,0f, 0,0f, would achieve this but instead the ball just flies off right in a level straight line??? Very confusing. Maeslezo’s help above direct me to change the direction of the velocity of the ball, but I have spent ages trying to do that without success too.

Is it really this difficult to specify a set direction in the world that you want a physics moving ball to travel in? Any additional feedback much appreciated.