Advertisement
hCollider

Unity Ball bouncing code

Mar 19th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.29 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class gravity : MonoBehaviour {
  6.  
  7.     public float _gravity;
  8.     public float mass;
  9.     public bool noAirResistance = false;
  10.  
  11.     private Rigidbody rb;
  12.     private float startingPos;
  13.     private bool grounded = false;
  14.     private float denisty = 1.29f;
  15.  
  16.     [SerializeField]private float border;
  17.     [SerializeField]private float fallingVelocity;
  18.  
  19.     private void Start()
  20.     {
  21.         border = 2 * (mass * _gravity) / (0.4f * 1 * 3.14f * denisty);
  22.         startingPos = this.transform.position.y;
  23.         _gravity = (_gravity > 0) ? _gravity : _gravity * (-1);
  24.         rb = this.gameObject.GetComponent<Rigidbody>();
  25.     }
  26.  
  27.     private void Update()
  28.     {
  29.         if(noAirResistance)
  30.         {
  31.             if (fallingVelocity < 0.5) grounded = false;
  32.             fallingVelocity = calculateFallingVelocity();
  33.             if (!grounded)
  34.                 rb.velocity = new Vector3(0, (-1) * fallingVelocity, 0);
  35.             else rb.velocity = new Vector3(0, 1 * fallingVelocity, 0);
  36.             //Debug.Log(fallingVelocity);
  37.         }
  38.         else
  39.         {
  40.             if (!grounded)
  41.             {
  42.                 fallingVelocity = calculateFallingVelocity();
  43.                 //Debug.Log(fallingVelocity);
  44.                 //if (fallingVelocity < border) fallingVelocity = border;
  45.                 rb.velocity = new Vector3(0, (-1) * fallingVelocity, 0);
  46.             }
  47.             else
  48.             {
  49.                 fallingVelocity = calculateFallingVelocity();
  50.                
  51.                 rb.velocity = new Vector3(0, (1) * fallingVelocity, 0);
  52.                 if (fallingVelocity < 1)
  53.                 {
  54.                     grounded = false;
  55.                     startingPos = this.transform.position.y;
  56.                 }
  57.             }
  58.            
  59.         }
  60.     }
  61.  
  62.     private float calculateFallingVelocity()
  63.     {
  64.         float velocity = startingPos + (_gravity * (calculateTime())) / 2;
  65.         return velocity;
  66.     }
  67.  
  68.     private float calculateTime()
  69.     {
  70.         float time = (2 * (startingPos - this.transform.position.y)) / _gravity;
  71.         Debug.Log(time);
  72.         return time;
  73.     }
  74.  
  75.     void OnCollisionEnter(Collision c)
  76.     {
  77.         grounded = true;
  78.     }
  79.  
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement