Arrow.cs 16 KB

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