Arrow.cs 15 KB

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