Search Unity

How to get a ball to go up at random angles?

Discussion in 'Getting Started' started by kmo86, May 30, 2021.

  1. kmo86

    kmo86

    Joined:
    Dec 15, 2020
    Posts:
    104
    I'm trying to make a simple ball game where the player has to keep tapping or clicking on a ball to avoid it hitting the ground. I've got it so the ball goes up when clicked but I want it to go up when clicked more like a ball would go up in real life rather than in a straight line up so the player can't just keep clicking in same place to keep scoring.

    This is my script so far
    Code (CSharp):
    1. public class Ball : MonoBehaviour
    2. {
    3.     public Rigidbody RB;
    4.     private float maxTorque = 10;
    5.     private float zBounds = 0;
    6.     private float xBounds = 7;
    7.  
    8.     // Start is called before the first frame update
    9.     void Start()
    10.     {
    11.        
    12.     }
    13.  
    14.     // Update is called once per frame
    15.     void Update()
    16.     {
    17.         if(transform.position.z < zBounds)
    18.         {
    19.             transform.position = new Vector3(transform.position.x, transform.position.y, zBounds);
    20.         }
    21.         if (transform.position.x < -xBounds)
    22.         {
    23.             transform.position = new Vector3(-xBounds, transform.position.y, transform.position.z);
    24.         }
    25.         if (transform.position.x > xBounds)
    26.         {
    27.             transform.position = new Vector3(xBounds, transform.position.y, transform.position.z);
    28.         }
    29.     }
    30.  
    31.     private void OnMouseDown()
    32.     {
    33.         RB.AddForce(Vector3.up * 10, ForceMode.Impulse);
    34.         RB.AddTorque(Random.Range(-maxTorque, maxTorque), Random.Range(-maxTorque, maxTorque), 0, ForceMode.Impulse);
    35.        
    36.     }
    37. }
    38.  
     
  2. Tarodev

    Tarodev

    Joined:
    Jul 30, 2015
    Posts:
    190
    Instead of just adding Vextor3.Up force, change It to new Vector3(1,Random.Range(-1,1)).

    On phone so not sure if syntax is right.