Search Unity

Resolved Platform that tosses/launches ball when it goes on it

Discussion in 'Physics' started by christoszal, Oct 17, 2021.

  1. christoszal

    christoszal

    Joined:
    Jun 6, 2021
    Posts:
    12
    Hello,
    So im trying to create this code for a platform that will turn 90 degrees when a ball goes on top of it and it will get launched in the direction when the platform is at 45 degrees for example.
    I've created this simple code that will turn the platform over time to a 90 degree angle.
    The ball only launches up, with a lot of speed even if i decrease the bounciness and it waits for the fling to go false so it stops bouncing. So is there a way to change the direction of the added force to the ball?
    Code (CSharp):
    1. public float speed = 0.2f;
    2.     public float bounciness = 0.1f;
    3.     public bool fling = false;
    4.     public GameObject player;
    5.  
    6.     void Update()
    7.     {
    8.         if (fling == true)
    9.         {
    10.             gameObject.transform.rotation = Quaternion.RotateTowards(gameObject.transform.rotation, Quaternion.Euler(0, 0, 90),  speed);
    11.  
    12.             player.GetComponent<Rigidbody2D>().AddForce(new Vector2(-player.GetComponent<Rigidbody2D>().velocity.x, player.GetComponent<Rigidbody2D>().velocity.y) * bounciness, ForceMode2D.Impulse);
    13.  
    14.         }
    15.         else
    16.         {
    17.             gameObject.transform.rotation = Quaternion.RotateTowards(gameObject.transform.rotation, Quaternion.Euler(0, 0, 0), speed);
    18.  
    19.         }
    20.     }
    21.  
    22.     void OnCollisionEnter2D(Collision2D coll)
    23.     {
    24.  
    25.         if (coll.collider.CompareTag("Player"))
    26.         {
    27.             fling = true;
    28.          
    29.         }
    30.     }
    31.  
    32.     void OnCollisionExit2D(Collision2D coll)
    33.     {
    34.         if (coll.collider.CompareTag("Player"))
    35.         {
    36.             StartCoroutine(ReturnToNormal());
    37.        
    38.          
    39.  
    40.         }
    41.     }
    42.  
    43.     IEnumerator ReturnToNormal()
    44.     {
    45.         yield return new WaitForSeconds(1f);
    46.         fling = false;
    47.     }
     
    Last edited: Oct 17, 2021