Arrow.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using DG.Tweening;
  6. /* 箭对象 */
  7. public class Arrow : MonoBehaviour
  8. {
  9. //飞行时间统计
  10. [NonSerialized] public float flyTime = 0;
  11. //标识—是否击中了什么
  12. [NonSerialized] public bool isHit = false;
  13. //箭的初速度(私用)
  14. [NonSerialized] public float mySpeed = 0;
  15. //箭的初速度(公用)
  16. public static float speed = GameMgr.RealSizeToGameSize(60);
  17. //箭射出时从弓传过来的参数
  18. #region
  19. //手臂弓
  20. [NonSerialized] public ArmBow armBow;
  21. //射出时的起始坐标
  22. [NonSerialized] public Vector3 shootOutPosition;
  23. //绝对射线
  24. [NonSerialized] public RaycastHit absoluteRay;
  25. //制作误差偏移角(强行制造误差,为了增加游戏难度,该偏移角的大小根据难度而定)
  26. [NonSerialized] public float offsetAngle;
  27. //误差偏移后的欧拉角
  28. [NonSerialized] public Vector3 finalAngleAfterOffset;
  29. #endregion
  30. //射线击中的靶子
  31. TargetBody rayHitTargetBody;
  32. //能够完美击中射线点
  33. bool canPerfectHit;
  34. //能否使用侧面镜头
  35. [NonSerialized] public bool canUseSideCamera;
  36. [NonSerialized] public ArrowCamera arrowCameraComp;
  37. public System.Action onDoNextShoot;
  38. public static HashSet<Arrow> arrowSet = new HashSet<Arrow>();
  39. void Awake()
  40. {
  41. arrowSet.Add(this);
  42. GameMgr.ins.gameMode.PauseTimeCounting(this);
  43. //箭模型平时属于ArmBow层,因为ArmBow层在飞行镜头中不被渲染,所以箭出去后要切换layer
  44. this.transform.Find("Head/_hunse_jian").gameObject.layer = 0;
  45. }
  46. void OnDestroy()
  47. {
  48. arrowSet.Remove(this);
  49. if (GameMgr.ins) GameMgr.ins.gameMode.ResumeTimeCounting(this);
  50. }
  51. void Start()
  52. {
  53. mySpeed = speed;
  54. Billboard.ins?.SetArrowSpeed(speed);
  55. //Debug.Log("speed:"+ speed);
  56. if (GameAssistUI.ins && GlobalData.MyDeviceMode == DeviceMode.Archery)
  57. {
  58. mySpeed *= GameAssistUI.ins.shootScaleValue;
  59. Billboard.ins?.SetArrowSpeedScale(GameAssistUI.ins.shootScaleValue);
  60. }
  61. Billboard.ins?.ShowSpeed();
  62. if (GlobalData.pkMatchType == PKMatchType.OnlinePK)
  63. {
  64. if (GameMgr.gameType == 9)
  65. {
  66. ((PKGameMode_OnlinePK)GameMgr.ins.gameMode).shootSpeedWillSend = Billboard.ins.GetShootSpeedText();
  67. }
  68. }
  69. if (absoluteRay.transform)
  70. {
  71. //记录射线有没有击中靶子
  72. rayHitTargetBody = absoluteRay.transform.GetComponent<TargetBody>();
  73. //把瞄准点画成红圈,渲染在靶子上
  74. if (rayHitTargetBody)
  75. {
  76. //string typeStr = GlobalData.MyDeviceMode == DeviceMode.Archery? "RedCircle":"BulletCircle";
  77. Transform redCircle = rayHitTargetBody.transform.Find("RedCircle");
  78. redCircle.gameObject.SetActive(true);
  79. redCircle.transform.position = -redCircle.transform.forward * 0.001f + absoluteRay.point;
  80. //渲染弹坑
  81. if (GlobalData.MyDeviceMode == DeviceMode.Gun)
  82. {
  83. Transform crater = transform.Find("Crater");
  84. crater.rotation = redCircle.rotation;
  85. }
  86. }
  87. }
  88. SetUpBeforFly();
  89. if (GlobalData.MyDeviceMode == DeviceMode.Archery)
  90. {
  91. Transform cameraTF = this.transform.Find("Camera");
  92. cameraTF.gameObject.SetActive(true);
  93. arrowCameraComp = cameraTF.gameObject.AddComponent<ArrowCamera>();
  94. arrowCameraComp.arrow = this;
  95. }
  96. this.activeEffectTrail(true);
  97. }
  98. /**在箭飞行前初始化&如果瞄准射线的落点在靶子上时,才调用该函数 */
  99. void SetUpBeforFly()
  100. {
  101. //基础角
  102. float baseAngleX = FormatAngleX(this.transform.eulerAngles.x);
  103. //最大可调整的角度差
  104. float maxDeltaAngleX = 5;
  105. //最终角
  106. float finalAngleX = baseAngleX;
  107. //额外偏移误差角
  108. float offsetAngleX = FormatAngleX(this.finalAngleAfterOffset.x) - baseAngleX;
  109. float offsetAngleY = FormatAngleY(this.finalAngleAfterOffset.y - this.transform.eulerAngles.y);
  110. if (DebugArrowOffsetAngle.ins)
  111. {
  112. offsetAngleX *= DebugArrowOffsetAngle.ins.GetOffsetScaleValue();
  113. offsetAngleY *= DebugArrowOffsetAngle.ins.GetOffsetScaleValue();
  114. }
  115. else
  116. {
  117. offsetAngleX *= this.armBow.shootOffsetAngleScale;
  118. offsetAngleY *= this.armBow.shootOffsetAngleScale;
  119. }
  120. DebugArrowOffsetAngle2.ins?.SetOffsetAngles(offsetAngleX, offsetAngleY);
  121. if (absoluteRay.transform)
  122. {
  123. bool plusOffsetAngleY = false;
  124. //看能否通过调整发射角让箭落在靶子的瞄准点上
  125. CalculateParabolaAngle(absoluteRay.point);
  126. //瞄准的是不是Target层
  127. bool isTargetLayer = IsTargetLayer(absoluteRay.transform.gameObject);
  128. //绝对发射角无解
  129. if (!hasParabolaAngle)
  130. {
  131. if (isTargetLayer) AimLoadChecker.ins?.ShowOutTip();
  132. }
  133. else
  134. {
  135. //来到这里,证明发射角有解,该解姑且叫它绝对角
  136. float absoluteAngleX = parabolaAngleInRadian / Mathf.PI * 180;
  137. //客户要求绝对角跟原本角度相差不能超过 maxDeltaAngleX
  138. float deltaAngleX = absoluteAngleX - baseAngleX;
  139. //如果绝对角跟原本角度相差不超过maxDeltaAngleX
  140. if (Mathf.Abs(deltaAngleX) < maxDeltaAngleX)
  141. {
  142. finalAngleX = Mathf.Clamp(absoluteAngleX + offsetAngleX, -89, 89);
  143. plusOffsetAngleY = true;
  144. if (Math.Abs(offsetAngle) < 0.001)
  145. {
  146. canPerfectHit = true;
  147. }
  148. if (rayHitTargetBody && Mathf.RoundToInt(rayHitTargetBody.GetDistance()) >= 50 && UnityEngine.Random.value < 0.5)
  149. {
  150. canUseSideCamera = true;
  151. }
  152. }
  153. else
  154. {
  155. finalAngleX = Mathf.Clamp(baseAngleX + maxDeltaAngleX, -89, 89);
  156. if (isTargetLayer) AimLoadChecker.ins?.ShowOutTip();
  157. }
  158. }
  159. finalPoint = absoluteRay.point;
  160. if (plusOffsetAngleY)
  161. {
  162. Vector3 myPos = this.transform.position;
  163. Vector3 pointer = finalPoint - myPos;
  164. pointer = Quaternion.AngleAxis(offsetAngleY, Vector3.up) * pointer;
  165. finalPoint = myPos + pointer;
  166. this.transform.LookAt(finalPoint);
  167. }
  168. }
  169. else
  170. {
  171. finalPoint = this.transform.position + this.transform.forward * 100;
  172. }
  173. parabolaAngleInRadian = finalAngleX / 180 * Mathf.PI;
  174. }
  175. /*
  176. 因为Unity引擎的规则,向上时359~270度,向下是0~90度
  177. 为了方便数学运算,换算成 向上时0~90度,向下是0~-90度
  178. */
  179. float FormatAngleX(float value)
  180. {
  181. if (value > 180) value = 360 - value;
  182. else value = -value;
  183. return value;
  184. }
  185. /**UnityY轴旋转只有0°~360°,两个Y轴旋转相减求得的夹角时会出现>180的情况,该函数就是为了解决这问题 */
  186. float FormatAngleY(float value)
  187. {
  188. if (Mathf.Abs(value) > 180)
  189. {
  190. if (value < 0)
  191. {
  192. return 360f + value;
  193. }
  194. if (value > 0)
  195. {
  196. return value - 360f;
  197. }
  198. }
  199. return value;
  200. }
  201. bool IsTargetLayer(GameObject gameObject)
  202. {
  203. return (1 << gameObject.layer) == LayerMask.GetMask("Target");
  204. }
  205. public Transform Head()
  206. {
  207. return this.transform.Find("Head");
  208. }
  209. /**发射角有无解 */
  210. bool hasParabolaAngle = false;
  211. /**发射角弧度解 */
  212. float parabolaAngleInRadian = 0;
  213. /**
  214. 求弓箭发射到指定坐标所需要的角度。
  215. 已知初速度大小V,重力g,起始坐标(a1,a2),目标坐标(b1,b2)。
  216. 解:
  217. 1、列出关系式
  218. Δx = b1 - a1;
  219. Δy = b2 - a2;
  220. Vx = V * cos(angle)
  221. Vy = V * sin(angle)
  222. Vy * t + 1/2 * g * t^2 = Δy
  223. Vx * t = Δx
  224. t = Δx / Vx
  225. 2、推导过程
  226. (V * sin(angle)) * Δx / (V * cos(angle)) + 1/2 * g * Δx^2 / (V^2*cos(angle)^2) = Δy
  227. tan(angle) * Δx + 1/2 * g * Δx^2 / (V^2*cos(angle)^2) = Δy
  228. tan(angle) * Δx + 1/2 * g * (Δx^2 / V^2) * (1 + tan(angle)^2) = Δy
  229. 3、根据求根公式得出结论
  230. a = 1/2 * g * Δx^2 / V^2
  231. b = Δx
  232. c = a - Δy
  233. d = tan(angle) = (-b ± (b^2 - 4*a*c)^0.5) / (2*a)
  234. angle = atan(d)
  235. 有无根的判别式,有根则b^2-4*a*c>=0
  236. */
  237. void CalculateParabolaAngle(Vector3 destination)
  238. {
  239. float deltaX = Vector2.Distance(
  240. new Vector2(destination.x, destination.z),
  241. new Vector2(this.transform.position.x, this.transform.position.z)
  242. );
  243. float deltaY = destination.y - this.transform.position.y;
  244. float a = 0.5f * Physics.gravity.y * Mathf.Pow(deltaX, 2) / Mathf.Pow(this.mySpeed, 2);
  245. float b = deltaX;
  246. float c = a - deltaY;
  247. hasParabolaAngle = Mathf.Pow(b, 2) - 4 * a * c >= 0;
  248. if (hasParabolaAngle)
  249. {
  250. float res1 = (-b + Mathf.Pow(Mathf.Pow(b, 2) - 4 * a * c, 0.5f)) / (2 * a);
  251. float res2 = (-b - Mathf.Pow(Mathf.Pow(b, 2) - 4 * a * c, 0.5f)) / (2 * a);
  252. parabolaAngleInRadian = Mathf.Min(Mathf.Atan(res1), Mathf.Atan(res2));
  253. }
  254. }
  255. void FixedUpdate()
  256. {
  257. if (!isHit && flyTime >= 0)
  258. {
  259. flyTime += Time.deltaTime;
  260. if (flyTime > 14)
  261. {
  262. FlyTimeOut();
  263. }
  264. // this.UpdateRotate();
  265. }
  266. }
  267. public ArrowSync.SyncData outputSyncData;
  268. void Update()
  269. {
  270. UpdateFlyLogic();
  271. if (GlobalData.pkMatchType == PKMatchType.OnlinePK)
  272. {
  273. if (outputSyncData == null) outputSyncData = new ArrowSync.SyncData();
  274. outputSyncData.SetData(this);
  275. }
  276. }
  277. IEnumerator delayFlyTimeOut() {
  278. yield return new WaitForSeconds(0.8f);//gun_shoot 音频长度
  279. FlyTimeOut();
  280. }
  281. void FlyTimeOut()
  282. {
  283. Destroy(gameObject);
  284. GameMgr.ins.gameMode.HitTarget(0);
  285. AudioMgr.ins.PlayCheer(false);
  286. nextShoot();
  287. }
  288. float logicFlyTime = 0;
  289. Vector3 finalPoint;
  290. /**飞行帧逻辑(运动学) */
  291. void UpdateFlyLogic()
  292. {
  293. if (isHit) return;
  294. logicFlyTime += Time.deltaTime;
  295. Vector3 destination = finalPoint;
  296. float vx = Mathf.Cos(parabolaAngleInRadian) * mySpeed;
  297. float t = logicFlyTime;
  298. float vy = Mathf.Sin(parabolaAngleInRadian) * mySpeed + Physics.gravity.y * t;
  299. float dy = Mathf.Sin(parabolaAngleInRadian) * mySpeed * t + 0.5f * Physics.gravity.y * Mathf.Pow(t, 2);
  300. float dx = vx * t;
  301. Vector3 nextPosition = new Vector3(destination.x - shootOutPosition.x, 0, destination.z - shootOutPosition.z);
  302. nextPosition = nextPosition.normalized * dx;
  303. nextPosition.y = dy;
  304. nextPosition = shootOutPosition + nextPosition;
  305. Vector3 oldPosition = this.transform.position;
  306. this.transform.position = nextPosition;
  307. Vector3 eulerAngles = this.transform.eulerAngles;
  308. float angleX = Mathf.Atan(vy / vx) / Mathf.PI * 180;
  309. eulerAngles.x = -angleX;
  310. this.transform.eulerAngles = eulerAngles;
  311. float deltaDistance = Vector3.Distance(oldPosition, nextPosition);
  312. Ray ray = new Ray(oldPosition, nextPosition - oldPosition);
  313. RaycastHit raycastHit;
  314. bool raycastResult = Physics.Raycast(ray, out raycastHit, deltaDistance);
  315. if (raycastResult)
  316. {
  317. this.transform.position = raycastHit.point;
  318. if (ArrowTraceDebug.ins) ArrowTraceDebug.ins.OnArrowUpdate(this);
  319. OnHitAnyInFlyLogic(raycastHit);
  320. }
  321. else
  322. {
  323. if (ArrowTraceDebug.ins) ArrowTraceDebug.ins.OnArrowUpdate(this);
  324. }
  325. }
  326. public class HitType
  327. {
  328. public static int None = 0;
  329. public static int TargetInRing = 1; //击中了靶子,且在得分环内
  330. public static int TargetOutRing = 2; //击中了靶子,但不在得分环内
  331. public static int NotTarget = 4; //击中非目标对象
  332. public static int Animal = 5; //击中动物
  333. }
  334. [NonSerialized] public int hitType = HitType.None;
  335. [NonSerialized] public Transform raycastHitTransform; //射线击中的目标变换
  336. [NonSerialized] public string[] hitTargetAnimalInfo;
  337. //飞行逻辑中检测到碰撞
  338. void OnHitAnyInFlyLogic(RaycastHit raycastHit)
  339. {
  340. this.Head().position = raycastHit.point;
  341. this.transform.SetParent(raycastHit.transform.parent);
  342. string targetName = raycastHit.transform.gameObject.name;
  343. this.raycastHitTransform = raycastHit.transform;
  344. if (targetName == "TargetBody")
  345. {
  346. Vector3 hitPoint = raycastHit.point;
  347. if (rayHitTargetBody && canPerfectHit)
  348. {
  349. hitPoint = absoluteRay.point;
  350. this.Head().position = hitPoint;
  351. }
  352. if (GlobalData.MyDeviceMode == DeviceMode.Archery)
  353. this.arrowCameraComp.arrowCameraTemplate?.beforeHit();
  354. else
  355. nextShootFromType();//子弹直接下一轮
  356. raycastHit.transform.GetComponent<TargetBody>().Hit(this, hitPoint);
  357. }
  358. else if (targetName.StartsWith("TargetAnimalPart"))
  359. {
  360. hitType = HitType.Animal;
  361. Vector3 hitPoint = raycastHit.point;
  362. string partName = targetName.Split(new char[] { '_' })[1];
  363. if (GlobalData.MyDeviceMode == DeviceMode.Archery)
  364. this.arrowCameraComp.arrowCameraTemplate?.beforeHit();
  365. else
  366. nextShootFromType();//子弹直接下一轮
  367. TargetAnimal targetAnimal = raycastHit.transform.GetComponentInParent<TargetAnimal>();
  368. targetAnimal.OnHit(this, hitPoint, partName);
  369. //箭击中的音效
  370. AudioMgr.ins.PlayArrowEnter();
  371. //记录击中的部位和动物ID
  372. hitTargetAnimalInfo = new string[] {
  373. targetAnimal.GetOnlineID().ToString(),
  374. targetAnimal.targetAnimalParts.IndexOf(raycastHitTransform).ToString(),
  375. SyncDataUtil.Vec3ToStr(transform.localPosition),
  376. SyncDataUtil.QuatToStr(transform.localRotation),
  377. SyncDataUtil.Vec3ToStr(transform.position),
  378. SyncDataUtil.QuatToStr(transform.rotation)
  379. };
  380. }
  381. else if (raycastHit.transform.GetComponent<TargetOutBound>())
  382. { //撞到空气墙当作超时处理
  383. if (GlobalData.MyDeviceMode == DeviceMode.Archery)
  384. FlyTimeOut();
  385. else
  386. StartCoroutine(delayFlyTimeOut());
  387. }
  388. else
  389. {
  390. if (GlobalData.MyDeviceMode == DeviceMode.Archery)
  391. this.arrowCameraComp.arrowCameraTemplate?.beforeHit();
  392. else
  393. nextShootFromType();//子弹直接下一轮
  394. Hit();
  395. GameMgr.ins.gameMode.HitTarget(0);
  396. //击中其它东西时的音效
  397. hitType = HitType.NotTarget;
  398. if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "Game")
  399. {
  400. AudioMgr.ins.PlayCheer(false);
  401. }
  402. else
  403. {
  404. AudioMgr.ins.PlayArrowEnter();
  405. }
  406. }
  407. }
  408. public void Hit()
  409. {
  410. isHit = true;
  411. if (GameDebug.ins) GameDebug.ins.ShowRes(absoluteRay.point, this.Head().position);
  412. //控制箭的特效显示
  413. this.activeEffectCyclone(false);
  414. this.activeEffectBomb(true);
  415. this.activeEffectTrail(false);
  416. //最新一箭击中后会发光标记
  417. ArrowLightSick.RecoveryAll();
  418. this.GetComponentInChildren<ArrowLightSick>().Hit();
  419. }
  420. //进入下一轮射击
  421. [NonSerialized] public bool hasDoneNextShoot = false;
  422. public void nextShootFromType() {
  423. // Debug.Log("nextShootFromType:" + GlobalDataTemp.pkMatchType);
  424. if (GlobalDataTemp.pkMatchType == PKMatchType.LocalPK || GlobalDataTemp.pkMatchType == PKMatchType.OnlinePK)
  425. {
  426. StartCoroutine(delayNectShoot());
  427. }
  428. else {
  429. nextShoot();
  430. }
  431. }
  432. IEnumerator delayNectShoot() {
  433. yield return new WaitForSeconds(1.0f);
  434. nextShoot();
  435. }
  436. public void nextShoot()
  437. {
  438. if (hasDoneNextShoot) return;
  439. hasDoneNextShoot = true;
  440. GameMgr.ins.gameMode.ResumeTimeCounting(this);
  441. onDoNextShoot?.Invoke();
  442. try
  443. {
  444. if (AimHandler.ins) AimHandler.ins.Ban9AxisCalculate(false);
  445. //把瞄准点画成红圈,渲染在靶子上(取消)
  446. if (rayHitTargetBody)
  447. {
  448. //string typeStr = GlobalData.MyDeviceMode == DeviceMode.Archery ? "RedCircle" : "BulletCircle";
  449. Transform redCircle = rayHitTargetBody.transform.Find("RedCircle");
  450. redCircle.gameObject.SetActive(false);
  451. }
  452. //最新一箭击中后会发光标记(取消)
  453. ArrowLightSick.RecoveryAll();
  454. }
  455. catch (System.Exception e) { Debug.LogError(e.Message + "\n" + e.StackTrace); }
  456. if (!GameMgr.ins.gameMode.DoNextShoot()) return;
  457. this.armBow.readyShoot();
  458. }
  459. //---------箭矢旋转--------
  460. Vector3 rotateV3 = new Vector3(0, 0, 1400);
  461. void UpdateRotate()
  462. {
  463. this.Head().Rotate(rotateV3 * Time.deltaTime, Space.Self);
  464. }
  465. //---------箭矢特效---------
  466. public void activeEffectCyclone(bool value)
  467. {
  468. this.transform.Find("Head/EF_kuosanquan").gameObject.SetActive(value);
  469. if (!value) return;
  470. ParticleSystemRenderer ps = this.transform.Find("Head/EF_kuosanquan/kuosan").GetComponent<ParticleSystemRenderer>();
  471. ParticleSystemRenderer ps1 = this.transform.Find("Head/EF_kuosanquan/kuosan (1)").GetComponent<ParticleSystemRenderer>();
  472. DOTween.To(() => ps.minParticleSize, value =>
  473. {
  474. ps.minParticleSize = value;
  475. ps.maxParticleSize = value;
  476. }, 0.4f, 0.6f);
  477. DOTween.To(() => ps1.minParticleSize, value =>
  478. {
  479. ps1.minParticleSize = value;
  480. ps1.maxParticleSize = value;
  481. }, 0.8f, 0.6f);
  482. }
  483. void activeEffectBomb(bool value)
  484. {
  485. this.transform.Find("Head/EF_baodian").gameObject.SetActive(value);
  486. }
  487. void activeEffectTrail(bool value)
  488. {
  489. if (GlobalData.MyDeviceMode == DeviceMode.Archery)
  490. {
  491. this.transform.Find("EF_tuowei").gameObject.SetActive(value);
  492. this.transform.Find("EF_tuowei/Trail").GetComponent<TrailRenderer>().time = 1.6f / mySpeed;
  493. }
  494. else {
  495. StartCoroutine(showTrail(value));
  496. }
  497. }
  498. IEnumerator showTrail(bool value) {
  499. this.transform.Find("EF_tuowei_bullet").gameObject.SetActive(value);
  500. //this.transform.Find("EF_tuowei_bullet/Trail").GetComponent<TrailRenderer>().time = 0;
  501. yield return new WaitForEndOfFrame();
  502. this.transform.Find("EF_tuowei_bullet/GB_flame_FX_1").gameObject.SetActive(true);
  503. //this.transform.Find("EF_tuowei_bullet/Trail").GetComponent<TrailRenderer>().time = 0.02f;
  504. //this.transform.Find("EF_tuowei_bullet/Trail").GetComponent<TrailRenderer>().time = 1.6f / mySpeed;
  505. }
  506. }