CollisionDetector.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using UnityEngine;
  2. using System.Collections;
  3. public class CollisionDetector : MonoBehaviour
  4. {
  5. public float MovingForce;
  6. Vector3 StartPoint;
  7. Vector3 Origin;
  8. public int NoOfRays = 10;
  9. int i;
  10. RaycastHit HitInfo;
  11. float LengthOfRay, DistanceBetweenRays, DirectionFactor;
  12. float margin = 0.015f;
  13. Ray ray;
  14. void Start()
  15. {
  16. //Length of the Ray is distance from center to edge
  17. LengthOfRay = GetComponent<Collider>().bounds.extents.y;
  18. //Initialize DirectionFactor for upward direction
  19. DirectionFactor = Mathf.Sign(Vector3.up.y);
  20. }
  21. void Update()
  22. {
  23. // First ray origin point for this frame
  24. StartPoint = new Vector3(GetComponent<Collider>().bounds.min.x + margin, transform.position.y, transform.position.z);
  25. if (!IsCollidingVertically())
  26. {
  27. transform.Translate(Vector3.up * MovingForce * Time.deltaTime * DirectionFactor);
  28. }
  29. }
  30. bool IsCollidingVertically()
  31. {
  32. Origin = StartPoint;
  33. DistanceBetweenRays = (GetComponent<Collider>().bounds.size.x - 2 * margin) / (NoOfRays - 1);
  34. for (i = 0; i < NoOfRays; i++)
  35. {
  36. // Ray to be casted.
  37. ray = new Ray(Origin, Vector3.up * DirectionFactor);
  38. //Draw ray on screen to see visually. Remember visual length is not actual length.
  39. Debug.DrawRay(Origin, Vector3.up * DirectionFactor, Color.yellow);
  40. if (Physics.Raycast(ray, out HitInfo, LengthOfRay))
  41. {
  42. print("Collided With " + HitInfo.collider.gameObject.name);
  43. // Negate the Directionfactor to reverse the moving direction of colliding cube(here cube2)
  44. DirectionFactor = -DirectionFactor;
  45. return true;
  46. }
  47. Origin += new Vector3(DistanceBetweenRays, 0, 0);
  48. }
  49. return false;
  50. }
  51. }