Arrow.cs 17 KB

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