Arrow.cs 17 KB

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