Arrow.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. using System;
  2. using UnityEngine;
  3. using DG.Tweening;
  4. /* 箭对象 */
  5. public class Arrow : MonoBehaviour
  6. {
  7. //飞行时间统计
  8. [NonSerialized] public float flyTime = 0;
  9. //标识—是否击中了什么
  10. [NonSerialized] public bool isHit = false;
  11. //箭的初速度(私用)
  12. private float mySpeed = 0;
  13. //箭的初速度(公用)
  14. public static float speed = GameMgr.RealSizeToGameSize(60);
  15. //箭射出时从弓传过来的参数
  16. #region
  17. //手臂弓
  18. [NonSerialized] public ArmBow armBow;
  19. //射出时的起始坐标
  20. [NonSerialized] public Vector3 shootOutPosition;
  21. //绝对射线
  22. [NonSerialized] public RaycastHit absoluteRay;
  23. //制作误差偏移角(强行制造误差,为了增加游戏难度,该偏移角的大小根据难度而定)
  24. [NonSerialized] public float offsetAngle;
  25. //误差偏移后的欧拉角
  26. [NonSerialized] public Vector3 finalAngleAfterOffset;
  27. #endregion
  28. //射线击中的靶子
  29. TargetBody rayHitTargetBody;
  30. //能够完美击中射线点
  31. bool canPerfectHit;
  32. //能否使用侧面镜头
  33. [NonSerialized] public bool canUseSideCamera;
  34. [NonSerialized] public ArrowCamera arrowCameraComp;
  35. public System.Action onDoNextShoot;
  36. void Awake()
  37. {
  38. GameMgr.ins.gameMode.PauseTimeCounting(this);
  39. }
  40. void OnDestroy() {
  41. GameMgr.ins.gameMode.ResumeTimeCounting(this);
  42. }
  43. void Start()
  44. {
  45. Destroy(gameObject.GetComponent<BoxCollider>());
  46. mySpeed = speed;
  47. Billboard.ins?.SetArrowSpeed(speed);
  48. if (GameAssistUI.ins) {
  49. mySpeed *= GameAssistUI.ins.shootScaleValue;
  50. Billboard.ins?.SetArrowSpeedScale(GameAssistUI.ins.shootScaleValue);
  51. }
  52. Billboard.ins?.ShowSpeed();
  53. if (absoluteRay.transform) {
  54. //记录射线有没有击中靶子
  55. rayHitTargetBody = absoluteRay.transform.GetComponent<TargetBody>();
  56. //把瞄准点画成红圈,渲染在靶子上
  57. if (rayHitTargetBody) {
  58. Transform redCircle = rayHitTargetBody.transform.Find("RedCircle");
  59. redCircle.gameObject.SetActive(true);
  60. redCircle.transform.position = -redCircle.transform.forward * 0.001f + absoluteRay.point;
  61. }
  62. }
  63. SetUpBeforFly();
  64. Transform cameraTF = this.transform.Find("Camera");
  65. cameraTF.gameObject.SetActive(true);
  66. arrowCameraComp = cameraTF.gameObject.AddComponent<ArrowCamera>();
  67. arrowCameraComp.arrow = this;
  68. this.activeEffectTrail(true);
  69. }
  70. /**在箭飞行前初始化&如果瞄准射线的落点在靶子上时,才调用该函数 */
  71. void SetUpBeforFly()
  72. {
  73. //基础角
  74. float baseAngleX = FormatAngleX(this.transform.eulerAngles.x);
  75. //最大可调整的角度差
  76. float maxDeltaAngleX = 5;
  77. //最终角
  78. float finalAngleX = baseAngleX;
  79. //额外偏移误差角
  80. float offsetAngleX = FormatAngleX(this.finalAngleAfterOffset.x) - baseAngleX;
  81. float offsetAngleY = FormatAngleY(this.finalAngleAfterOffset.y - this.transform.eulerAngles.y);
  82. if (DebugArrowOffsetAngle.ins) {
  83. offsetAngleX *= DebugArrowOffsetAngle.ins.GetOffsetScaleValue();
  84. offsetAngleY *= DebugArrowOffsetAngle.ins.GetOffsetScaleValue();
  85. } else {
  86. offsetAngleX *= this.armBow.shootOffsetAngleScale;
  87. offsetAngleY *= this.armBow.shootOffsetAngleScale;
  88. }
  89. if (absoluteRay.transform) {
  90. bool plusOffsetAngleY = false;
  91. //看能否通过调整发射角让箭落在靶子的瞄准点上
  92. CalculateParabolaAngle(absoluteRay.point);
  93. //瞄准的是不是Target层
  94. bool isTargetLayer = IsTargetLayer(absoluteRay.transform.gameObject);
  95. //绝对发射角无解
  96. if (!hasParabolaAngle) {
  97. if (isTargetLayer) AimLoadChecker.ins?.ShowOutTip();
  98. } else {
  99. //来到这里,证明发射角有解,该解姑且叫它绝对角
  100. float absoluteAngleX = parabolaAngleInRadian / Mathf.PI * 180;
  101. //客户要求绝对角跟原本角度相差不能超过 maxDeltaAngleX
  102. float deltaAngleX = absoluteAngleX - baseAngleX;
  103. //如果绝对角跟原本角度相差不超过maxDeltaAngleX
  104. if (Mathf.Abs(deltaAngleX) < maxDeltaAngleX) {
  105. finalAngleX = Mathf.Clamp(absoluteAngleX + offsetAngleX, -89, 89);
  106. plusOffsetAngleY = true;
  107. if (Math.Abs(offsetAngle) < 0.001) {
  108. canPerfectHit = true;
  109. }
  110. if (rayHitTargetBody && Mathf.RoundToInt(rayHitTargetBody.GetDistance()) >= 50 && UnityEngine.Random.value < 0.5) {
  111. canUseSideCamera = true;
  112. }
  113. } else {
  114. finalAngleX = Mathf.Clamp(baseAngleX + maxDeltaAngleX, -89, 89);
  115. if (isTargetLayer) AimLoadChecker.ins?.ShowOutTip();
  116. }
  117. }
  118. finalPoint = absoluteRay.point;
  119. if (plusOffsetAngleY) {
  120. Vector3 myPos = this.transform.position;
  121. Vector3 pointer = finalPoint - myPos;
  122. pointer = Quaternion.AngleAxis(offsetAngleY, Vector3.up) * pointer;
  123. finalPoint = myPos + pointer;
  124. this.transform.LookAt(finalPoint);
  125. }
  126. } else {
  127. finalPoint = this.transform.position + this.transform.forward * 100;
  128. }
  129. parabolaAngleInRadian = finalAngleX / 180 * Mathf.PI;
  130. }
  131. /*
  132. 因为Unity引擎的规则,向上时359~270度,向下是0~90度
  133. 为了方便数学运算,换算成 向上时0~90度,向下是0~-90度
  134. */
  135. float FormatAngleX(float value)
  136. {
  137. if (value > 180) value = 360 - value;
  138. else value = -value;
  139. return value;
  140. }
  141. /**UnityY轴旋转只有0°~360°,两个Y轴旋转相减求得的夹角时会出现>180的情况,该函数就是为了解决这问题 */
  142. float FormatAngleY(float value)
  143. {
  144. if (Mathf.Abs(value) > 180) {
  145. if (value < 0) {
  146. return 360f + value;
  147. }
  148. if (value > 0) {
  149. return value - 360f;
  150. }
  151. }
  152. return value;
  153. }
  154. bool IsTargetLayer(GameObject gameObject) {
  155. return (1 << gameObject.layer) == LayerMask.GetMask("Target");
  156. }
  157. public Transform Head()
  158. {
  159. return this.transform.Find("Head");
  160. }
  161. /**发射角有无解 */
  162. bool hasParabolaAngle = false;
  163. /**发射角弧度解 */
  164. float parabolaAngleInRadian = 0;
  165. /**
  166. 求弓箭发射到指定坐标所需要的角度。
  167. 已知初速度大小V,重力g,起始坐标(a1,a2),目标坐标(b1,b2)。
  168. 解:
  169. 1、列出关系式
  170. Δx = b1 - a1;
  171. Δy = b2 - a2;
  172. Vx = V * cos(angle)
  173. Vy = V * sin(angle)
  174. Vy * t + 1/2 * g * t^2 = Δy
  175. Vx * t = Δx
  176. t = Δx / Vx
  177. 2、推导过程
  178. (V * sin(angle)) * Δx / (V * cos(angle)) + 1/2 * g * Δx^2 / (V^2*cos(angle)^2) = Δy
  179. tan(angle) * Δx + 1/2 * g * Δx^2 / (V^2*cos(angle)^2) = Δy
  180. tan(angle) * Δx + 1/2 * g * (Δx^2 / V^2) * (1 + tan(angle)^2) = Δy
  181. 3、根据求根公式得出结论
  182. a = 1/2 * g * Δx^2 / V^2
  183. b = Δx
  184. c = a - Δy
  185. d = tan(angle) = (-b ± (b^2 - 4*a*c)^0.5) / (2*a)
  186. angle = atan(d)
  187. 有无根的判别式,有根则b^2-4*a*c>=0
  188. */
  189. void CalculateParabolaAngle(Vector3 destination)
  190. {
  191. float deltaX = Vector2.Distance(
  192. new Vector2(destination.x, destination.z),
  193. new Vector2(this.transform.position.x, this.transform.position.z)
  194. );
  195. float deltaY = destination.y - this.transform.position.y;
  196. float a = 0.5f * Physics.gravity.y * Mathf.Pow(deltaX, 2) / Mathf.Pow(this.mySpeed, 2);
  197. float b = deltaX;
  198. float c = a - deltaY;
  199. hasParabolaAngle = Mathf.Pow(b, 2) - 4 * a * c >= 0;
  200. if (hasParabolaAngle) {
  201. float res1 = (-b + Mathf.Pow(Mathf.Pow(b, 2) - 4*a*c, 0.5f)) / (2 * a);
  202. float res2 = (-b - Mathf.Pow(Mathf.Pow(b, 2) - 4*a*c, 0.5f)) / (2 * a);
  203. parabolaAngleInRadian = Mathf.Min(Mathf.Atan(res1), Mathf.Atan(res2));
  204. }
  205. }
  206. void FixedUpdate()
  207. {
  208. if (!isHit && flyTime >= 0) {
  209. flyTime += Time.deltaTime;
  210. if (flyTime > 14) {
  211. FlyTimeOut();
  212. }
  213. this.UpdateRotate();
  214. }
  215. }
  216. void Update() {
  217. UpdateFlyLogic();
  218. }
  219. void FlyTimeOut() {
  220. Destroy(gameObject);
  221. GameMgr.ins.gameMode.HitTarget(0);
  222. AudioMgr.ins.PlayCheer(false);
  223. nextShoot();
  224. }
  225. float logicFlyTime = 0;
  226. Vector3 finalPoint;
  227. /**飞行帧逻辑(运动学) */
  228. void UpdateFlyLogic() {
  229. if (isHit) return;
  230. logicFlyTime += Time.deltaTime;
  231. Vector3 destination = finalPoint;
  232. float vx = Mathf.Cos(parabolaAngleInRadian) * mySpeed;
  233. float t = logicFlyTime;
  234. float vy = Mathf.Sin(parabolaAngleInRadian) * mySpeed + Physics.gravity.y * t;
  235. float dy = Mathf.Sin(parabolaAngleInRadian) * mySpeed * t + 0.5f * Physics.gravity.y * Mathf.Pow(t, 2);
  236. float dx = vx * t;
  237. Vector3 nextPosition = new Vector3(destination.x - shootOutPosition.x, 0, destination.z - shootOutPosition.z);
  238. nextPosition = nextPosition.normalized * dx;
  239. nextPosition.y = dy;
  240. nextPosition = shootOutPosition + nextPosition;
  241. Vector3 oldPosition = this.transform.position;
  242. this.transform.position = nextPosition;
  243. Vector3 eulerAngles = this.transform.eulerAngles;
  244. float angleX = Mathf.Atan(vy / vx) / Mathf.PI * 180;
  245. eulerAngles.x = -angleX;
  246. this.transform.eulerAngles = eulerAngles;
  247. float deltaDistance = Vector3.Distance(oldPosition, nextPosition);
  248. Ray ray = new Ray(oldPosition, nextPosition - oldPosition);
  249. RaycastHit raycastHit;
  250. bool raycastResult = Physics.Raycast(ray, out raycastHit, deltaDistance);
  251. if (raycastResult) {
  252. this.transform.position = raycastHit.point;
  253. OnHitAnyInFlyLogic(raycastHit);
  254. }
  255. }
  256. //飞行逻辑中检测到碰撞
  257. void OnHitAnyInFlyLogic(RaycastHit raycastHit) {
  258. this.Head().position = raycastHit.point;
  259. this.transform.SetParent(raycastHit.transform.parent);
  260. string targetName = raycastHit.transform.gameObject.name;
  261. if (targetName == "TargetBody") {
  262. Vector3 hitPoint = raycastHit.point;
  263. if (rayHitTargetBody && canPerfectHit) {
  264. hitPoint = absoluteRay.point;
  265. this.Head().position = hitPoint;
  266. }
  267. this.arrowCameraComp.arrowCameraTemplate?.beforeHit();
  268. raycastHit.transform.GetComponent<TargetBody>().Hit(this, hitPoint);
  269. } else if (targetName.StartsWith("TargetAnimalPart")) {
  270. Vector3 hitPoint = raycastHit.point;
  271. string partName = targetName.Split(new char[]{'_'})[1];
  272. this.arrowCameraComp.arrowCameraTemplate?.beforeHit();
  273. raycastHit.transform.GetComponentInParent<TargetAnimal>().OnHit(this, hitPoint, partName);
  274. //箭击中的音效
  275. AudioMgr.ins.PlayArrowEnter();
  276. } else if (raycastHit.transform.GetComponent<TargetOutBound>()) { //撞到空气墙当作超时处理
  277. FlyTimeOut();
  278. } else {
  279. this.arrowCameraComp.arrowCameraTemplate?.beforeHit();
  280. Hit();
  281. GameMgr.ins.gameMode.HitTarget(0);
  282. //击中其它东西时的音效
  283. if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "GameChallenge") {
  284. AudioMgr.ins.PlayArrowEnter();
  285. } else {
  286. AudioMgr.ins.PlayCheer(false);
  287. }
  288. }
  289. }
  290. public void Hit() {
  291. isHit = true;
  292. if (GameDebug.ins) GameDebug.ins.ShowRes(absoluteRay.point, this.Head().position);
  293. //控制箭的特效显示
  294. this.activeEffectCyclone(false);
  295. this.activeEffectBomb(true);
  296. this.activeEffectTrail(false);
  297. //最新一箭击中后会发光标记
  298. ArrowLightSick.RecoveryAll();
  299. this.GetComponentInChildren<ArrowLightSick>().Hit();
  300. }
  301. //进入下一轮射击
  302. public bool hasDoneNextShoot = false;
  303. public void nextShoot() {
  304. if (hasDoneNextShoot) return;
  305. hasDoneNextShoot = true;
  306. GameMgr.ins.gameMode.ResumeTimeCounting(this);
  307. onDoNextShoot?.Invoke();
  308. if (!GameMgr.ins.gameMode.DoNextShoot()) return;
  309. if (AimHandler.ins) AimHandler.ins.BanControlObjRotate(false);
  310. this.armBow.readyShoot();
  311. //把瞄准点画成红圈,渲染在靶子上(取消)
  312. if (rayHitTargetBody) {
  313. Transform redCircle = rayHitTargetBody.transform.Find("RedCircle");
  314. redCircle.gameObject.SetActive(false);
  315. }
  316. //最新一箭击中后会发光标记(取消)
  317. ArrowLightSick.RecoveryAll();
  318. }
  319. //---------箭矢旋转--------
  320. Vector3 rotateV3 = new Vector3(0, 0, 1400);
  321. void UpdateRotate() {
  322. this.Head().Rotate(rotateV3 * Time.deltaTime, Space.Self);
  323. }
  324. //---------箭矢特效---------
  325. public void activeEffectCyclone(bool value)
  326. {
  327. this.transform.Find("Head/EF_kuosanquan").gameObject.SetActive(value);
  328. if (!value) return;
  329. ParticleSystemRenderer ps = this.transform.Find("Head/EF_kuosanquan/kuosan").GetComponent<ParticleSystemRenderer>();
  330. ParticleSystemRenderer ps1 = this.transform.Find("Head/EF_kuosanquan/kuosan (1)").GetComponent<ParticleSystemRenderer>();
  331. DOTween.To(() => ps.minParticleSize, value => {
  332. ps.minParticleSize = value;
  333. ps.maxParticleSize = value;
  334. }, 0.4f, 0.6f);
  335. DOTween.To(() => ps1.minParticleSize, value => {
  336. ps1.minParticleSize = value;
  337. ps1.maxParticleSize = value;
  338. }, 0.8f, 0.6f);
  339. }
  340. void activeEffectBomb(bool value)
  341. {
  342. this.transform.Find("Head/EF_baodian").gameObject.SetActive(value);
  343. }
  344. void activeEffectTrail(bool value)
  345. {
  346. this.transform.Find("EF_tuowei").gameObject.SetActive(value);
  347. this.transform.Find("EF_tuowei/Trail").GetComponent<TrailRenderer>().time = 1.6f / mySpeed;
  348. }
  349. }