ArrowNew2.cs 19 KB

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