Arrow.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. Vector3 ls = this.transform.localScale;
  47. ls.x *= 2;
  48. ls.y *= 2;
  49. this.transform.localScale = ls;
  50. }
  51. void OnDestroy() {
  52. arrowSet.Remove(this);
  53. if (GameMgr.ins) GameMgr.ins.gameMode.ResumeTimeCounting(this);
  54. }
  55. void Start()
  56. {
  57. mySpeed = speed;
  58. Billboard.ins?.SetArrowSpeed(speed);
  59. if (GameAssistUI.ins) {
  60. mySpeed *= GameAssistUI.ins.shootScaleValue;
  61. Billboard.ins?.SetArrowSpeedScale(GameAssistUI.ins.shootScaleValue);
  62. }
  63. Billboard.ins?.ShowSpeed();
  64. if (GlobalData.pkMatchType == PKMatchType.OnlinePK) {
  65. if (GameMgr.gameType == 9) {
  66. ((PKGameMode_OnlinePK)GameMgr.ins.gameMode).shootSpeedWillSend = Billboard.ins.GetShootSpeedText();
  67. }
  68. }
  69. if (absoluteRay.transform) {
  70. //记录射线有没有击中靶子
  71. rayHitTargetBody = absoluteRay.transform.GetComponent<TargetBody>();
  72. //把瞄准点画成红圈,渲染在靶子上
  73. if (rayHitTargetBody) {
  74. Transform redCircle = rayHitTargetBody.transform.Find("RedCircle");
  75. redCircle.gameObject.SetActive(true);
  76. redCircle.transform.position = -redCircle.transform.forward * 0.001f + absoluteRay.point;
  77. }
  78. }
  79. SetUpBeforFly();
  80. Transform cameraTF = this.transform.Find("Camera");
  81. cameraTF.gameObject.SetActive(true);
  82. arrowCameraComp = cameraTF.gameObject.AddComponent<ArrowCamera>();
  83. arrowCameraComp.arrow = this;
  84. this.activeEffectTrail(true);
  85. }
  86. /**在箭飞行前初始化&如果瞄准射线的落点在靶子上时,才调用该函数 */
  87. void SetUpBeforFly()
  88. {
  89. //基础角
  90. float baseAngleX = FormatAngleX(this.transform.eulerAngles.x);
  91. //最大可调整的角度差
  92. float maxDeltaAngleX = 5;
  93. //最终角
  94. float finalAngleX = baseAngleX;
  95. //额外偏移误差角
  96. float offsetAngleX = FormatAngleX(this.finalAngleAfterOffset.x) - baseAngleX;
  97. float offsetAngleY = FormatAngleY(this.finalAngleAfterOffset.y - this.transform.eulerAngles.y);
  98. if (DebugArrowOffsetAngle.ins) {
  99. offsetAngleX *= DebugArrowOffsetAngle.ins.GetOffsetScaleValue();
  100. offsetAngleY *= DebugArrowOffsetAngle.ins.GetOffsetScaleValue();
  101. } else {
  102. offsetAngleX *= this.armBow.shootOffsetAngleScale;
  103. offsetAngleY *= this.armBow.shootOffsetAngleScale;
  104. }
  105. if (absoluteRay.transform) {
  106. bool plusOffsetAngleY = false;
  107. //看能否通过调整发射角让箭落在靶子的瞄准点上
  108. CalculateParabolaAngle(absoluteRay.point);
  109. //瞄准的是不是Target层
  110. bool isTargetLayer = IsTargetLayer(absoluteRay.transform.gameObject);
  111. //绝对发射角无解
  112. if (!hasParabolaAngle) {
  113. if (isTargetLayer) AimLoadChecker.ins?.ShowOutTip();
  114. } else {
  115. //来到这里,证明发射角有解,该解姑且叫它绝对角
  116. float absoluteAngleX = parabolaAngleInRadian / Mathf.PI * 180;
  117. //客户要求绝对角跟原本角度相差不能超过 maxDeltaAngleX
  118. float deltaAngleX = absoluteAngleX - baseAngleX;
  119. //如果绝对角跟原本角度相差不超过maxDeltaAngleX
  120. if (Mathf.Abs(deltaAngleX) < maxDeltaAngleX) {
  121. finalAngleX = Mathf.Clamp(absoluteAngleX + offsetAngleX, -89, 89);
  122. plusOffsetAngleY = true;
  123. if (Math.Abs(offsetAngle) < 0.001) {
  124. canPerfectHit = true;
  125. }
  126. if (rayHitTargetBody && Mathf.RoundToInt(rayHitTargetBody.GetDistance()) >= 50 && UnityEngine.Random.value < 0.5) {
  127. canUseSideCamera = true;
  128. }
  129. } else {
  130. finalAngleX = Mathf.Clamp(baseAngleX + maxDeltaAngleX, -89, 89);
  131. if (isTargetLayer) AimLoadChecker.ins?.ShowOutTip();
  132. }
  133. }
  134. finalPoint = absoluteRay.point;
  135. if (plusOffsetAngleY) {
  136. Vector3 myPos = this.transform.position;
  137. Vector3 pointer = finalPoint - myPos;
  138. pointer = Quaternion.AngleAxis(offsetAngleY, Vector3.up) * pointer;
  139. finalPoint = myPos + pointer;
  140. this.transform.LookAt(finalPoint);
  141. }
  142. } else {
  143. finalPoint = this.transform.position + this.transform.forward * 100;
  144. }
  145. parabolaAngleInRadian = finalAngleX / 180 * Mathf.PI;
  146. }
  147. /*
  148. 因为Unity引擎的规则,向上时359~270度,向下是0~90度
  149. 为了方便数学运算,换算成 向上时0~90度,向下是0~-90度
  150. */
  151. float FormatAngleX(float value)
  152. {
  153. if (value > 180) value = 360 - value;
  154. else value = -value;
  155. return value;
  156. }
  157. /**UnityY轴旋转只有0°~360°,两个Y轴旋转相减求得的夹角时会出现>180的情况,该函数就是为了解决这问题 */
  158. float FormatAngleY(float value)
  159. {
  160. if (Mathf.Abs(value) > 180) {
  161. if (value < 0) {
  162. return 360f + value;
  163. }
  164. if (value > 0) {
  165. return value - 360f;
  166. }
  167. }
  168. return value;
  169. }
  170. bool IsTargetLayer(GameObject gameObject) {
  171. return (1 << gameObject.layer) == LayerMask.GetMask("Target");
  172. }
  173. public Transform Head()
  174. {
  175. return this.transform.Find("Head");
  176. }
  177. /**发射角有无解 */
  178. bool hasParabolaAngle = false;
  179. /**发射角弧度解 */
  180. float parabolaAngleInRadian = 0;
  181. /**
  182. 求弓箭发射到指定坐标所需要的角度。
  183. 已知初速度大小V,重力g,起始坐标(a1,a2),目标坐标(b1,b2)。
  184. 解:
  185. 1、列出关系式
  186. Δx = b1 - a1;
  187. Δy = b2 - a2;
  188. Vx = V * cos(angle)
  189. Vy = V * sin(angle)
  190. Vy * t + 1/2 * g * t^2 = Δy
  191. Vx * t = Δx
  192. t = Δx / Vx
  193. 2、推导过程
  194. (V * sin(angle)) * Δx / (V * cos(angle)) + 1/2 * g * Δx^2 / (V^2*cos(angle)^2) = Δy
  195. tan(angle) * Δx + 1/2 * g * Δx^2 / (V^2*cos(angle)^2) = Δy
  196. tan(angle) * Δx + 1/2 * g * (Δx^2 / V^2) * (1 + tan(angle)^2) = Δy
  197. 3、根据求根公式得出结论
  198. a = 1/2 * g * Δx^2 / V^2
  199. b = Δx
  200. c = a - Δy
  201. d = tan(angle) = (-b ± (b^2 - 4*a*c)^0.5) / (2*a)
  202. angle = atan(d)
  203. 有无根的判别式,有根则b^2-4*a*c>=0
  204. */
  205. void CalculateParabolaAngle(Vector3 destination)
  206. {
  207. float deltaX = Vector2.Distance(
  208. new Vector2(destination.x, destination.z),
  209. new Vector2(this.transform.position.x, this.transform.position.z)
  210. );
  211. float deltaY = destination.y - this.transform.position.y;
  212. float a = 0.5f * Physics.gravity.y * Mathf.Pow(deltaX, 2) / Mathf.Pow(this.mySpeed, 2);
  213. float b = deltaX;
  214. float c = a - deltaY;
  215. hasParabolaAngle = Mathf.Pow(b, 2) - 4 * a * c >= 0;
  216. if (hasParabolaAngle) {
  217. float res1 = (-b + Mathf.Pow(Mathf.Pow(b, 2) - 4*a*c, 0.5f)) / (2 * a);
  218. float res2 = (-b - Mathf.Pow(Mathf.Pow(b, 2) - 4*a*c, 0.5f)) / (2 * a);
  219. parabolaAngleInRadian = Mathf.Min(Mathf.Atan(res1), Mathf.Atan(res2));
  220. }
  221. }
  222. void FixedUpdate()
  223. {
  224. if (!isHit && flyTime >= 0) {
  225. flyTime += Time.deltaTime;
  226. if (flyTime > 14) {
  227. FlyTimeOut();
  228. }
  229. // this.UpdateRotate();
  230. }
  231. }
  232. public ArrowSync.SyncData outputSyncData;
  233. void Update() {
  234. UpdateFlyLogic();
  235. if (GlobalData.pkMatchType == PKMatchType.OnlinePK) {
  236. if (outputSyncData == null) outputSyncData = new ArrowSync.SyncData();
  237. outputSyncData.SetData(this);
  238. }
  239. }
  240. void FlyTimeOut() {
  241. Destroy(gameObject);
  242. GameMgr.ins.gameMode.HitTarget(0);
  243. AudioMgr.ins.PlayCheer(false);
  244. nextShoot();
  245. }
  246. float logicFlyTime = 0;
  247. Vector3 finalPoint;
  248. /**飞行帧逻辑(运动学) */
  249. void UpdateFlyLogic() {
  250. if (isHit) return;
  251. logicFlyTime += Time.deltaTime;
  252. Vector3 destination = finalPoint;
  253. float vx = Mathf.Cos(parabolaAngleInRadian) * mySpeed;
  254. float t = logicFlyTime;
  255. float vy = Mathf.Sin(parabolaAngleInRadian) * mySpeed + Physics.gravity.y * t;
  256. float dy = Mathf.Sin(parabolaAngleInRadian) * mySpeed * t + 0.5f * Physics.gravity.y * Mathf.Pow(t, 2);
  257. float dx = vx * t;
  258. Vector3 nextPosition = new Vector3(destination.x - shootOutPosition.x, 0, destination.z - shootOutPosition.z);
  259. nextPosition = nextPosition.normalized * dx;
  260. nextPosition.y = dy;
  261. nextPosition = shootOutPosition + nextPosition;
  262. Vector3 oldPosition = this.transform.position;
  263. this.transform.position = nextPosition;
  264. Vector3 eulerAngles = this.transform.eulerAngles;
  265. float angleX = Mathf.Atan(vy / vx) / Mathf.PI * 180;
  266. eulerAngles.x = -angleX;
  267. this.transform.eulerAngles = eulerAngles;
  268. float deltaDistance = Vector3.Distance(oldPosition, nextPosition);
  269. Ray ray = new Ray(oldPosition, nextPosition - oldPosition);
  270. RaycastHit raycastHit;
  271. bool raycastResult = Physics.Raycast(ray, out raycastHit, deltaDistance);
  272. if (raycastResult) {
  273. this.transform.position = raycastHit.point;
  274. if (ArrowTraceDebug.ins) ArrowTraceDebug.ins.OnArrowUpdate(this);
  275. OnHitAnyInFlyLogic(raycastHit);
  276. } else {
  277. if (ArrowTraceDebug.ins) ArrowTraceDebug.ins.OnArrowUpdate(this);
  278. }
  279. }
  280. public class HitType
  281. {
  282. public static int None = 0;
  283. public static int TargetInRing = 1; //击中了靶子,且在得分环内
  284. public static int TargetOutRing = 2; //击中了靶子,但不在得分环内
  285. public static int NotTarget = 4; //击中非目标对象
  286. public static int Animal = 5; //击中动物
  287. }
  288. [NonSerialized] public int hitType = HitType.None;
  289. [NonSerialized] public Transform raycastHitTransform; //射线击中的目标变换
  290. [NonSerialized] public string[] hitTargetAnimalInfo;
  291. //飞行逻辑中检测到碰撞
  292. void OnHitAnyInFlyLogic(RaycastHit raycastHit) {
  293. this.Head().position = raycastHit.point;
  294. this.transform.SetParent(raycastHit.transform.parent);
  295. string targetName = raycastHit.transform.gameObject.name;
  296. this.raycastHitTransform = raycastHit.transform;
  297. if (targetName == "TargetBody") {
  298. Vector3 hitPoint = raycastHit.point;
  299. if (rayHitTargetBody && canPerfectHit) {
  300. hitPoint = absoluteRay.point;
  301. this.Head().position = hitPoint;
  302. }
  303. this.arrowCameraComp.arrowCameraTemplate?.beforeHit();
  304. raycastHit.transform.GetComponent<TargetBody>().Hit(this, hitPoint);
  305. } else if (targetName.StartsWith("TargetAnimalPart")) {
  306. hitType = HitType.Animal;
  307. Vector3 hitPoint = raycastHit.point;
  308. string partName = targetName.Split(new char[]{'_'})[1];
  309. this.arrowCameraComp.arrowCameraTemplate?.beforeHit();
  310. TargetAnimal targetAnimal = raycastHit.transform.GetComponentInParent<TargetAnimal>();
  311. targetAnimal.OnHit(this, hitPoint, partName);
  312. //箭击中的音效
  313. AudioMgr.ins.PlayArrowEnter();
  314. //记录击中的部位和动物ID
  315. hitTargetAnimalInfo = new string[] {
  316. targetAnimal.GetOnlineID().ToString(),
  317. targetAnimal.targetAnimalParts.IndexOf(raycastHitTransform).ToString(),
  318. SyncDataUtil.Vec3ToStr(transform.localPosition),
  319. SyncDataUtil.QuatToStr(transform.localRotation),
  320. SyncDataUtil.Vec3ToStr(transform.position),
  321. SyncDataUtil.QuatToStr(transform.rotation)
  322. };
  323. } else if (raycastHit.transform.GetComponent<TargetOutBound>()) { //撞到空气墙当作超时处理
  324. FlyTimeOut();
  325. } else {
  326. this.arrowCameraComp.arrowCameraTemplate?.beforeHit();
  327. Hit();
  328. GameMgr.ins.gameMode.HitTarget(0);
  329. //击中其它东西时的音效
  330. hitType = HitType.NotTarget;
  331. if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "Game")
  332. {
  333. AudioMgr.ins.PlayCheer(false);
  334. }
  335. else
  336. {
  337. AudioMgr.ins.PlayArrowEnter();
  338. }
  339. }
  340. }
  341. public void Hit() {
  342. isHit = true;
  343. if (GameDebug.ins) GameDebug.ins.ShowRes(absoluteRay.point, this.Head().position);
  344. //控制箭的特效显示
  345. this.activeEffectCyclone(false);
  346. this.activeEffectBomb(true);
  347. this.activeEffectTrail(false);
  348. //最新一箭击中后会发光标记
  349. // ArrowLightSick.RecoveryAll();
  350. // this.GetComponentInChildren<ArrowLightSick>().Hit();
  351. }
  352. //进入下一轮射击
  353. [NonSerialized] public bool hasDoneNextShoot = false;
  354. public void nextShoot() {
  355. if (hasDoneNextShoot) return;
  356. hasDoneNextShoot = true;
  357. GameMgr.ins.gameMode.ResumeTimeCounting(this);
  358. onDoNextShoot?.Invoke();
  359. try {
  360. if (AimHandler.ins) AimHandler.ins.Ban9AxisCalculate(false);
  361. //把瞄准点画成红圈,渲染在靶子上(取消)
  362. if (rayHitTargetBody) {
  363. Transform redCircle = rayHitTargetBody.transform.Find("RedCircle");
  364. redCircle.gameObject.SetActive(false);
  365. }
  366. //最新一箭击中后会发光标记(取消)
  367. ArrowLightSick.RecoveryAll();
  368. } catch (System.Exception e) { Debug.LogError(e.Message + "\n" + e.StackTrace); }
  369. if (!GameMgr.ins.gameMode.DoNextShoot()) return;
  370. this.armBow.readyShoot();
  371. }
  372. //---------箭矢旋转--------
  373. Vector3 rotateV3 = new Vector3(0, 0, 1400);
  374. void UpdateRotate() {
  375. this.Head().Rotate(rotateV3 * Time.deltaTime, Space.Self);
  376. }
  377. //---------箭矢特效---------
  378. public void activeEffectCyclone(bool value)
  379. {
  380. this.transform.Find("Head/EF_kuosanquan").gameObject.SetActive(value);
  381. if (!value) return;
  382. ParticleSystemRenderer ps = this.transform.Find("Head/EF_kuosanquan/kuosan").GetComponent<ParticleSystemRenderer>();
  383. ParticleSystemRenderer ps1 = this.transform.Find("Head/EF_kuosanquan/kuosan (1)").GetComponent<ParticleSystemRenderer>();
  384. DOTween.To(() => ps.minParticleSize, value => {
  385. ps.minParticleSize = value;
  386. ps.maxParticleSize = value;
  387. }, 0.4f, 0.6f);
  388. DOTween.To(() => ps1.minParticleSize, value => {
  389. ps1.minParticleSize = value;
  390. ps1.maxParticleSize = value;
  391. }, 0.8f, 0.6f);
  392. }
  393. void activeEffectBomb(bool value)
  394. {
  395. this.transform.Find("Head/EF_baodian").gameObject.SetActive(value);
  396. }
  397. void activeEffectTrail(bool value)
  398. {
  399. this.transform.Find("EF_tuowei").gameObject.SetActive(value);
  400. this.transform.Find("EF_tuowei/Trail").GetComponent<TrailRenderer>().time = 1.6f / mySpeed;
  401. }
  402. }