| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using DG.Tweening;
- /* 箭对象 */
- public class Arrow : MonoBehaviour
- {
- //飞行时间统计
- [NonSerialized] public float flyTime = 0;
- //标识—是否击中了什么
- [NonSerialized] public bool isHit = false;
- //箭的初速度(私用)
- [NonSerialized] public float mySpeed = 0;
- //箭的初速度(公用)
- public static float speed = GameMgr.RealSizeToGameSize(60);
- //箭射出时从弓传过来的参数
- #region
- //手臂弓
- [NonSerialized] public ArmBow armBow;
- //射出时的起始坐标
- [NonSerialized] public Vector3 shootOutPosition;
- //绝对射线
- [NonSerialized] public RaycastHit absoluteRay;
- //制作误差偏移角(强行制造误差,为了增加游戏难度,该偏移角的大小根据难度而定)
- [NonSerialized] public float offsetAngle;
- //误差偏移后的欧拉角
- [NonSerialized] public Vector3 finalAngleAfterOffset;
- #endregion
- //射线击中的靶子
- TargetBody rayHitTargetBody;
- //能够完美击中射线点
- bool canPerfectHit;
- //能否使用侧面镜头
- [NonSerialized] public bool canUseSideCamera;
- [NonSerialized] public ArrowCamera arrowCameraComp;
- public System.Action onDoNextShoot;
- public static HashSet<Arrow> arrowSet = new HashSet<Arrow>();
- void Awake()
- {
- arrowSet.Add(this);
- GameMgr.ins.gameMode.PauseTimeCounting(this);
- //箭模型平时属于ArmBow层,因为ArmBow层在飞行镜头中不被渲染,所以箭出去后要切换layer
- this.transform.Find("Head/_hunse_jian").gameObject.layer = 0;
- }
- void OnDestroy()
- {
- arrowSet.Remove(this);
- if (GameMgr.ins) GameMgr.ins.gameMode.ResumeTimeCounting(this);
- }
- void Start()
- {
- mySpeed = speed;
- Billboard.ins?.SetArrowSpeed(speed);
- if (GameAssistUI.ins && GlobalData.MyDeviceMode == DeviceMode.Archery)
- {
- int shootScaleValue = 5; //GameAssistUI.ins.shootScaleValue
- mySpeed *= shootScaleValue;
- Billboard.ins?.SetArrowSpeedScale(shootScaleValue);
- }
- Debug.Log("射箭基础速度:" + speed + ",射箭加倍后的速度:"+ mySpeed);
- Billboard.ins?.ShowSpeed();
- if (GlobalData.pkMatchType == PKMatchType.OnlinePK)
- {
- if (GameMgr.gameType == 9)
- {
- ((PKGameMode_OnlinePK)GameMgr.ins.gameMode).shootSpeedWillSend = Billboard.ins.GetShootSpeedText();
- }
- }
- if (absoluteRay.transform)
- {
- //记录射线有没有击中靶子
- rayHitTargetBody = absoluteRay.transform.GetComponent<TargetBody>();
- //把瞄准点画成红圈,渲染在靶子上
- if (rayHitTargetBody)
- {
- //string typeStr = GlobalData.MyDeviceMode == DeviceMode.Archery? "RedCircle":"BulletCircle";
- Transform redCircle = rayHitTargetBody.transform.Find("RedCircle");
- redCircle.gameObject.SetActive(true);
- redCircle.transform.position = -redCircle.transform.forward * 0.001f + absoluteRay.point;
- //渲染弹坑
- if (GlobalData.MyDeviceMode == DeviceMode.Gun)
- {
- Transform crater = transform.Find("Crater");
- crater.rotation = redCircle.rotation;
- }
- }
- }
- SetUpBeforFly();
- if (GlobalData.MyDeviceMode == DeviceMode.Archery)
- {
- Transform cameraTF = this.transform.Find("Camera");
- cameraTF.gameObject.SetActive(true);
- arrowCameraComp = cameraTF.gameObject.AddComponent<ArrowCamera>();
- arrowCameraComp.arrow = this;
- }
- this.activeEffectTrail(true);
- }
- /**在箭飞行前初始化&如果瞄准射线的落点在靶子上时,才调用该函数 */
- void SetUpBeforFly()
- {
- //基础角
- float baseAngleX = FormatAngleX(this.transform.eulerAngles.x);
- //最大可调整的角度差
- float maxDeltaAngleX = 5;
- //最终角
- float finalAngleX = baseAngleX;
- //额外偏移误差角
- float offsetAngleX = FormatAngleX(this.finalAngleAfterOffset.x) - baseAngleX;
- float offsetAngleY = FormatAngleY(this.finalAngleAfterOffset.y - this.transform.eulerAngles.y);
- if (DebugArrowOffsetAngle.ins)
- {
- offsetAngleX *= DebugArrowOffsetAngle.ins.GetOffsetScaleValue();
- offsetAngleY *= DebugArrowOffsetAngle.ins.GetOffsetScaleValue();
- }
- else
- {
- offsetAngleX *= this.armBow.shootOffsetAngleScale;
- offsetAngleY *= this.armBow.shootOffsetAngleScale;
- }
- DebugArrowOffsetAngle2.ins?.SetOffsetAngles(offsetAngleX, offsetAngleY);
- if (absoluteRay.transform)
- {
- bool plusOffsetAngleY = false;
- //看能否通过调整发射角让箭落在靶子的瞄准点上
- CalculateParabolaAngle(absoluteRay.point);
- //瞄准的是不是Target层
- bool isTargetLayer = IsTargetLayer(absoluteRay.transform.gameObject);
- //绝对发射角无解
- if (!hasParabolaAngle)
- {
- if (isTargetLayer) AimLoadChecker.ins?.ShowOutTip();
- }
- else
- {
- //来到这里,证明发射角有解,该解姑且叫它绝对角
- float absoluteAngleX = parabolaAngleInRadian / Mathf.PI * 180;
- //客户要求绝对角跟原本角度相差不能超过 maxDeltaAngleX
- float deltaAngleX = absoluteAngleX - baseAngleX;
- //如果绝对角跟原本角度相差不超过maxDeltaAngleX
- if (Mathf.Abs(deltaAngleX) < maxDeltaAngleX)
- {
- finalAngleX = Mathf.Clamp(absoluteAngleX + offsetAngleX, -89, 89);
- plusOffsetAngleY = true;
- if (Math.Abs(offsetAngle) < 0.001)
- {
- canPerfectHit = true;
- }
- if (rayHitTargetBody && Mathf.RoundToInt(rayHitTargetBody.GetDistance()) >= 50 && UnityEngine.Random.value < 0.5)
- {
- canUseSideCamera = true;
- }
- }
- else
- {
- finalAngleX = Mathf.Clamp(baseAngleX + maxDeltaAngleX, -89, 89);
- if (isTargetLayer) AimLoadChecker.ins?.ShowOutTip();
- }
- }
- finalPoint = absoluteRay.point;
- if (plusOffsetAngleY)
- {
- Vector3 myPos = this.transform.position;
- Vector3 pointer = finalPoint - myPos;
- pointer = Quaternion.AngleAxis(offsetAngleY, Vector3.up) * pointer;
- finalPoint = myPos + pointer;
- this.transform.LookAt(finalPoint);
- }
- }
- else
- {
- finalPoint = this.transform.position + this.transform.forward * 100;
- }
- parabolaAngleInRadian = finalAngleX / 180 * Mathf.PI;
- }
- /*
- 因为Unity引擎的规则,向上时359~270度,向下是0~90度
- 为了方便数学运算,换算成 向上时0~90度,向下是0~-90度
- */
- float FormatAngleX(float value)
- {
- if (value > 180) value = 360 - value;
- else value = -value;
- return value;
- }
- /**UnityY轴旋转只有0°~360°,两个Y轴旋转相减求得的夹角时会出现>180的情况,该函数就是为了解决这问题 */
- float FormatAngleY(float value)
- {
- if (Mathf.Abs(value) > 180)
- {
- if (value < 0)
- {
- return 360f + value;
- }
- if (value > 0)
- {
- return value - 360f;
- }
- }
- return value;
- }
- bool IsTargetLayer(GameObject gameObject)
- {
- return (1 << gameObject.layer) == LayerMask.GetMask("Target");
- }
- public Transform Head()
- {
- return this.transform.Find("Head");
- }
- /**发射角有无解 */
- bool hasParabolaAngle = false;
- /**发射角弧度解 */
- float parabolaAngleInRadian = 0;
- /**
- 求弓箭发射到指定坐标所需要的角度。
- 已知初速度大小V,重力g,起始坐标(a1,a2),目标坐标(b1,b2)。
- 解:
- 1、列出关系式
- Δx = b1 - a1;
- Δy = b2 - a2;
- Vx = V * cos(angle)
- Vy = V * sin(angle)
- Vy * t + 1/2 * g * t^2 = Δy
- Vx * t = Δx
- t = Δx / Vx
- 2、推导过程
- (V * sin(angle)) * Δx / (V * cos(angle)) + 1/2 * g * Δx^2 / (V^2*cos(angle)^2) = Δy
- tan(angle) * Δx + 1/2 * g * Δx^2 / (V^2*cos(angle)^2) = Δy
- tan(angle) * Δx + 1/2 * g * (Δx^2 / V^2) * (1 + tan(angle)^2) = Δy
- 3、根据求根公式得出结论
- a = 1/2 * g * Δx^2 / V^2
- b = Δx
- c = a - Δy
- d = tan(angle) = (-b ± (b^2 - 4*a*c)^0.5) / (2*a)
- angle = atan(d)
- 有无根的判别式,有根则b^2-4*a*c>=0
- */
- void CalculateParabolaAngle(Vector3 destination)
- {
- float deltaX = Vector2.Distance(
- new Vector2(destination.x, destination.z),
- new Vector2(this.transform.position.x, this.transform.position.z)
- );
- float deltaY = destination.y - this.transform.position.y;
- float a = 0.5f * Physics.gravity.y * Mathf.Pow(deltaX, 2) / Mathf.Pow(this.mySpeed, 2);
- float b = deltaX;
- float c = a - deltaY;
- hasParabolaAngle = Mathf.Pow(b, 2) - 4 * a * c >= 0;
- if (hasParabolaAngle)
- {
- float res1 = (-b + Mathf.Pow(Mathf.Pow(b, 2) - 4 * a * c, 0.5f)) / (2 * a);
- float res2 = (-b - Mathf.Pow(Mathf.Pow(b, 2) - 4 * a * c, 0.5f)) / (2 * a);
- parabolaAngleInRadian = Mathf.Min(Mathf.Atan(res1), Mathf.Atan(res2));
- }
- }
- void FixedUpdate()
- {
- if (!isHit && flyTime >= 0)
- {
- flyTime += Time.deltaTime;
- if (flyTime > 14)
- {
- FlyTimeOut();
- }
- // this.UpdateRotate();
- }
- }
- public ArrowSync.SyncData outputSyncData;
- void Update()
- {
- UpdateFlyLogic();
- if (GlobalData.pkMatchType == PKMatchType.OnlinePK)
- {
- if (outputSyncData == null) outputSyncData = new ArrowSync.SyncData();
- outputSyncData.SetData(this);
- }
- }
- IEnumerator delayFlyTimeOut() {
- yield return new WaitForSeconds(0.8f);//gun_shoot 音频长度
- FlyTimeOut();
- }
- void FlyTimeOut()
- {
- Destroy(gameObject);
- GameMgr.ins.gameMode.HitTarget(0);
- AudioMgr.ins.PlayCheer(false);
- nextShoot();
- }
- float logicFlyTime = 0;
- Vector3 finalPoint;
- /**飞行帧逻辑(运动学) */
- void UpdateFlyLogic()
- {
- if (isHit) return;
- logicFlyTime += Time.deltaTime;
- Vector3 destination = finalPoint;
- float vx = Mathf.Cos(parabolaAngleInRadian) * mySpeed;
- float t = logicFlyTime;
- float vy = Mathf.Sin(parabolaAngleInRadian) * mySpeed + Physics.gravity.y * t;
- float dy = Mathf.Sin(parabolaAngleInRadian) * mySpeed * t + 0.5f * Physics.gravity.y * Mathf.Pow(t, 2);
- float dx = vx * t;
- Vector3 nextPosition = new Vector3(destination.x - shootOutPosition.x, 0, destination.z - shootOutPosition.z);
- nextPosition = nextPosition.normalized * dx;
- nextPosition.y = dy;
- nextPosition = shootOutPosition + nextPosition;
- Vector3 oldPosition = this.transform.position;
- this.transform.position = nextPosition;
- Vector3 eulerAngles = this.transform.eulerAngles;
- float angleX = Mathf.Atan(vy / vx) / Mathf.PI * 180;
- eulerAngles.x = -angleX;
- this.transform.eulerAngles = eulerAngles;
- float deltaDistance = Vector3.Distance(oldPosition, nextPosition);
- Ray ray = new Ray(oldPosition, nextPosition - oldPosition);
- RaycastHit raycastHit;
- bool raycastResult = Physics.Raycast(ray, out raycastHit, deltaDistance);
- if (raycastResult)
- {
- this.transform.position = raycastHit.point;
- if (ArrowTraceDebug.ins) ArrowTraceDebug.ins.OnArrowUpdate(this);
- OnHitAnyInFlyLogic(raycastHit);
- }
- else
- {
- if (ArrowTraceDebug.ins) ArrowTraceDebug.ins.OnArrowUpdate(this);
- }
- }
- public class HitType
- {
- public static int None = 0;
- public static int TargetInRing = 1; //击中了靶子,且在得分环内
- public static int TargetOutRing = 2; //击中了靶子,但不在得分环内
- public static int NotTarget = 4; //击中非目标对象
- public static int Animal = 5; //击中动物
- }
- [NonSerialized] public int hitType = HitType.None;
- [NonSerialized] public Transform raycastHitTransform; //射线击中的目标变换
- [NonSerialized] public string[] hitTargetAnimalInfo;
- //飞行逻辑中检测到碰撞
- void OnHitAnyInFlyLogic(RaycastHit raycastHit)
- {
- this.Head().position = raycastHit.point;
- this.transform.SetParent(raycastHit.transform.parent);
- string targetName = raycastHit.transform.gameObject.name;
- this.raycastHitTransform = raycastHit.transform;
- if (targetName == "TargetBody")
- {
- Vector3 hitPoint = raycastHit.point;
- if (rayHitTargetBody && canPerfectHit)
- {
- hitPoint = absoluteRay.point;
- this.Head().position = hitPoint;
- }
- if (GlobalData.MyDeviceMode == DeviceMode.Archery)
- this.arrowCameraComp.arrowCameraTemplate?.beforeHit();
- else
- nextShootFromType();//子弹直接下一轮
- raycastHit.transform.GetComponent<TargetBody>().Hit(this, hitPoint);
- }
- else if (targetName.StartsWith("TargetAnimalPart"))
- {
- hitType = HitType.Animal;
- Vector3 hitPoint = raycastHit.point;
- string partName = targetName.Split(new char[] { '_' })[1];
- if (GlobalData.MyDeviceMode == DeviceMode.Archery)
- this.arrowCameraComp.arrowCameraTemplate?.beforeHit();
- else
- nextShootFromType();//子弹直接下一轮
- TargetAnimal targetAnimal = raycastHit.transform.GetComponentInParent<TargetAnimal>();
- targetAnimal.OnHit(this, hitPoint, partName);
- //箭击中的音效
- AudioMgr.ins.PlayArrowEnter();
- //记录击中的部位和动物ID
- hitTargetAnimalInfo = new string[] {
- targetAnimal.GetOnlineID().ToString(),
- targetAnimal.targetAnimalParts.IndexOf(raycastHitTransform).ToString(),
- SyncDataUtil.Vec3ToStr(transform.localPosition),
- SyncDataUtil.QuatToStr(transform.localRotation),
- SyncDataUtil.Vec3ToStr(transform.position),
- SyncDataUtil.QuatToStr(transform.rotation)
- };
- }
- else if (raycastHit.transform.GetComponent<TargetOutBound>())
- { //撞到空气墙当作超时处理
- if (GlobalData.MyDeviceMode == DeviceMode.Archery)
- FlyTimeOut();
- else
- StartCoroutine(delayFlyTimeOut());
- }
- else
- {
- if (GlobalData.MyDeviceMode == DeviceMode.Archery)
- this.arrowCameraComp.arrowCameraTemplate?.beforeHit();
- else
- nextShootFromType();//子弹直接下一轮
- Hit();
- GameMgr.ins.gameMode.HitTarget(0);
- //击中其它东西时的音效
- hitType = HitType.NotTarget;
- if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "Game")
- {
- AudioMgr.ins.PlayCheer(false);
- }
- else
- {
- if (CommonConfig.StandaloneModeOrPlatformB) {
- AudioMgr.ins.PlayCheer(false);
- } else {
- AudioMgr.ins.PlayArrowEnter();
- }
- }
- }
- }
- public void Hit()
- {
- isHit = true;
- if (GameDebug.ins) GameDebug.ins.ShowRes(absoluteRay.point, this.Head().position);
- //控制箭的特效显示
- this.activeEffectCyclone(false);
- this.activeEffectBomb(true);
- this.activeEffectTrail(false);
- //最新一箭击中后会发光标记
- ArrowLightSick.RecoveryAll();
- this.GetComponentInChildren<ArrowLightSick>().Hit();
- }
- //进入下一轮射击
- [NonSerialized] public bool hasDoneNextShoot = false;
- public void nextShootFromType() {
- // Debug.Log("nextShootFromType:" + GlobalDataTemp.pkMatchType);
- if (GlobalDataTemp.pkMatchType == PKMatchType.LocalPK || GlobalDataTemp.pkMatchType == PKMatchType.OnlinePK)
- {
- StartCoroutine(delayNectShoot());
- }
- else {
- nextShoot();
- }
- }
- IEnumerator delayNectShoot() {
- yield return new WaitForSeconds(1.0f);
- nextShoot();
- }
- public void nextShoot()
- {
- if (hasDoneNextShoot) return;
- hasDoneNextShoot = true;
- GameMgr.ins.gameMode.ResumeTimeCounting(this);
- onDoNextShoot?.Invoke();
- try
- {
- if (AimHandler.ins) AimHandler.ins.Ban9AxisCalculate(false);
- //把瞄准点画成红圈,渲染在靶子上(取消)
- if (rayHitTargetBody)
- {
- //string typeStr = GlobalData.MyDeviceMode == DeviceMode.Archery ? "RedCircle" : "BulletCircle";
- Transform redCircle = rayHitTargetBody.transform.Find("RedCircle");
- redCircle.gameObject.SetActive(false);
- }
- //最新一箭击中后会发光标记(取消)
- ArrowLightSick.RecoveryAll();
- }
- catch (System.Exception e) { Debug.LogError(e.Message + "\n" + e.StackTrace); }
- if (!GameMgr.ins.gameMode.DoNextShoot()) return;
- this.armBow.readyShoot();
- }
- //---------箭矢旋转--------
- Vector3 rotateV3 = new Vector3(0, 0, 1400);
- void UpdateRotate()
- {
- this.Head().Rotate(rotateV3 * Time.deltaTime, Space.Self);
- }
- //---------箭矢特效---------
- public void activeEffectCyclone(bool value)
- {
- this.transform.Find("Head/EF_kuosanquan").gameObject.SetActive(value);
- if (!value) return;
- ParticleSystemRenderer ps = this.transform.Find("Head/EF_kuosanquan/kuosan").GetComponent<ParticleSystemRenderer>();
- ParticleSystemRenderer ps1 = this.transform.Find("Head/EF_kuosanquan/kuosan (1)").GetComponent<ParticleSystemRenderer>();
- DOTween.To(() => ps.minParticleSize, value =>
- {
- ps.minParticleSize = value;
- ps.maxParticleSize = value;
- }, 0.4f, 0.6f);
- DOTween.To(() => ps1.minParticleSize, value =>
- {
- ps1.minParticleSize = value;
- ps1.maxParticleSize = value;
- }, 0.8f, 0.6f);
- }
- void activeEffectBomb(bool value)
- {
- this.transform.Find("Head/EF_baodian").gameObject.SetActive(value);
- }
- void activeEffectTrail(bool value)
- {
- if (GlobalData.MyDeviceMode == DeviceMode.Archery)
- {
- this.transform.Find("EF_tuowei").gameObject.SetActive(value);
- this.transform.Find("EF_tuowei/Trail").GetComponent<TrailRenderer>().time = 1.6f / mySpeed;
- }
- else {
- StartCoroutine(showTrail(value));
-
- }
-
- }
- IEnumerator showTrail(bool value) {
- this.transform.Find("EF_tuowei_bullet").gameObject.SetActive(value);
- //this.transform.Find("EF_tuowei_bullet/Trail").GetComponent<TrailRenderer>().time = 0;
- yield return new WaitForEndOfFrame();
- this.transform.Find("EF_tuowei_bullet/GB_flame_FX_1").gameObject.SetActive(true);
- //this.transform.Find("EF_tuowei_bullet/Trail").GetComponent<TrailRenderer>().time = 0.02f;
- //this.transform.Find("EF_tuowei_bullet/Trail").GetComponent<TrailRenderer>().time = 1.6f / mySpeed;
- }
- }
|