Arrow.cs 15 KB

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