PhysicsUtils.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. 
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Runtime.InteropServices.ComTypes;
  6. using UnityEngine;
  7. public class PhysicsUtils : MonoBehaviour
  8. {
  9. public GameObject startPoint;
  10. public GameObject endPoint;
  11. /// <summary>
  12. /// 角度间隔
  13. /// </summary>
  14. public float angleInterval = 10.0f;
  15. /// <summary>
  16. /// 距离间隔
  17. /// </summary>
  18. public float distanceInterval = 0.1f;
  19. //private int[][] list;
  20. // Start is called before the first frame update
  21. void Start()
  22. {
  23. StartRaycast();
  24. }
  25. void StartRaycast()
  26. {
  27. float dis = Vector3.Distance(startPoint.transform.position, endPoint.transform.position);
  28. int disCount = (int)(dis / distanceInterval);
  29. int angleCount = (int)(360.0f / angleInterval);
  30. //list = new int[angleCount][];
  31. Vector3 pos = new Vector3();
  32. Vector3 direction = new Vector3();
  33. pos.Set(startPoint.transform.position.x, startPoint.transform.position.y, startPoint.transform.position.z);
  34. string data = "[";
  35. int rayState = 0;
  36. for (int zIndex = 0; zIndex < disCount; zIndex++)
  37. {
  38. //重置方向
  39. direction.Set(0, -1, 0);
  40. //list[xIndex] = new int[disCount];
  41. if (zIndex > 0)
  42. {
  43. data += ",[";
  44. }
  45. else
  46. {
  47. data += "[";
  48. }
  49. for (int xIndex = 0; xIndex < angleCount; xIndex++)
  50. {
  51. pos.z = startPoint.transform.position.z + zIndex * distanceInterval;
  52. //旋转向量
  53. direction = Quaternion.Euler(0, 0, xIndex * distanceInterval) * direction;
  54. if (Physics.Raycast(pos, direction))
  55. {
  56. rayState = 1;
  57. }
  58. else
  59. {
  60. rayState = 0;
  61. }
  62. //list[xIndex][zIndex] = rayState;
  63. data += rayState.ToString();
  64. }
  65. data += "]";
  66. }
  67. data += "]";
  68. WriteFile("D:/cocos/StarRacing/LevelTools/Raycast.json", data);
  69. }
  70. /// <summary>
  71. /// path需要包含文件的后缀名
  72. /// </summary>
  73. /// <param name="path">路径</param>
  74. /// <param name="con">需要写入的数据</param>
  75. public void WriteFile(string path, string con = "")
  76. {
  77. string str = con;
  78. //若是直接在文件里添加数据,则采用重写方法,将append设置为true
  79. var file = new StreamWriter(path, true);
  80. //var file = new StreamWriter(path);
  81. //file.WriteLine(str);
  82. file.Write(str);
  83. file.Close();
  84. }
  85. // Update is called once per frame
  86. void Update()
  87. {
  88. }
  89. }