| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692 |
- using System.Collections;
- using System.Collections.Generic;
- using TMPro;
- using UnityEngine;
- using UnityEngine.EventSystems;
- using UnityEngine.UI;
- using UnityEngine.SceneManagement;
- using SmartBowSDK;
- using System;
- using HyperspaceGame;
- using MathNet.Numerics;
- public class GeneratingTarget : MonoBehaviour
- {
- // 最小时间间隔(秒)
- float _minTimeBetweenEvents = 1.0f;
- public float minTimeBetweenEvents { get { return _minTimeBetweenEvents; } set { _minTimeBetweenEvents = value; } }
- float _maxTimeBetweenEvents = 3.0f;// 最大时间间隔(秒)
- public float maxTimeBetweenEvents { get { return _maxTimeBetweenEvents; } set { _maxTimeBetweenEvents = value; } }
- public GameObject target;
- public Transform UI;
- public TextMeshProUGUI scoreUI;
- public TextMeshProUGUI scoreUI1;
- public Text countDownUI;
- public TextMeshProUGUI clipsizeUI;
- public TextMeshProUGUI hitCountUI;
- public TextMeshProUGUI shootRate;
- public GameObject GameOver;
- public Score scoreCom;
- public Score scoreCom1;
- public GameObject Miss;
- public Image grade;
- public Sprite[] gradeSprites;
- public Transform tp;
- public GameObject bulletNull;//子弹不足UI
- public GameObject[] bulletImages;//子弹图片数组
- public GameObject SelectLv;
- public Image imgSlider;
- public Text TopScore;
- public Text CurLvTxt;
- public Text MaxLvTxt;
- public int bulletCount;//子弹数量
- public int hitCount;//击中数量
- private float rate;//命中率
- public Button BtnRestart;
- public Button BtnNext;
- public Button BtnLast;
- int _score;
- public bool stop = false;
- public int score { get { return _score; }
- set {
- _score = value;
- ShowScore();
- }
- }
- /// <summary>
- /// 游戏时间
- /// </summary>
- private float countDownTime;
- int countDownTimeCache;
- /// <summary>
- /// 子弹数量
- /// </summary>
- private int clipsize;
- const int BulletCount = 15;
- /// <summary>
- /// 靶子存在最长时间
- /// </summary>
- float _targetExistenceTimeMax = 5;
- public float TargetExistenceTimeMax { get { return _targetExistenceTimeMax; } set { _targetExistenceTimeMax = value; } }
- /// <summary>
- /// 靶子存在最短时间
- /// </summary>
- float _targetExistenceTimeMin = 3;
- public float TargetExistenceTimeMin { get { return _targetExistenceTimeMin; } set { _targetExistenceTimeMin = value; } }
- float _scaleMin = 1.3f;
- public float ScaleMin { get { return _scaleMin; } set { _scaleMin = value; } }
- float _scaleMax = 1.8f;
- public float ScaleMax { get { return _scaleMax; } set { _scaleMax = value; } }
- public HyperspaceGame.Font font;
- public AudioSource ShootingSound;
- public AudioSource gameSatrtSound;
- public AudioClip[] gameSatrtClips;
- //public GameObject perfect;
- //public GameObject gaeat;
- //public GameObject good;
- //public Image goodImage;
- //public Image greatImage;
- public static GeneratingTarget gm { get; set; }
- public ShootingEvent shootingEvent;
- /// <summary>
- /// 记录当前射箭是否记录分数
- /// </summary>
- private bool bAddCountScore { get; set; } = false;
- [HideInInspector] public bool getAddCountScore => bAddCountScore;
- //分数统计
- [HideInInspector] public UserGameAnalyse1 userGameAnalyse1;
- public int Index = 0;
- private bool unload = false;
- /// <summary>
- /// 当前难度的配置
- /// </summary>
- public Level LvCfg = null;
- /// <summary>
- /// 当前序列的配置
- /// </summary>
- public Order orderCfg = null;
- float nextOrderWaitTime;
- int curOrderIdx;
- bool canEnterNextOrder = true;
- bool isbegin = false;
- int tragetLeftNum;
- /// <summary>
- /// 当前序列
- /// </summary>
- public int CurOrder = 0;
- public static int MaxLevel = 3;
- [SerializeField]
- RectTransform _canvasRectTransform;
- private void Awake()
- {
- gm = this;
- var scene = SceneManager.GetActiveScene();
- if(scene.name == "Hyperspace01")
- Index = 0;
- else if (scene.name == "Hyperspace02")
- Index = 1;
- else if(scene.name == "Hyperspace03")
- Index = 2;
- //初始化关卡配置
- LvCfg = Config.levels[Index];
- countDownTime = LvCfg.TotalTime;
- curOrderIdx = 0;
- UpdateCountDown(LvCfg.TotalTime);
- CurLvTxt.text = $"{Index + 1}";
- MaxLvTxt.text = $"/<color=#0F92D4>{MaxLevel}</color>";
- shootingEvent = FindObjectOfType<ShootingEvent>();
- scoreCom.gameObject.SetActive(false);
- scoreCom1.gameObject.SetActive(false);
- Miss.SetActive(false);
- stop = false;
- imgSlider.fillAmount = 1;
- ShowScore();
- bulletNull.SetActive(false);
- BtnRestart.onClick.AddListener(OnRestart);
- BtnNext.onClick.AddListener(OnBtnNext);
- BtnNext.gameObject.SetActive(Index + 1 < MaxLevel);
- BtnLast.onClick.AddListener(OnBtnLast);
- BtnLast.gameObject.SetActive(true);
- GameOver.SetActive(false);
-
- CreateUIManager();
- CreateTargetObject2D();
- }
- public void OnRestart()
- {
- Restart(Index);
- }
- public void OnBtnNext()
- {
- Restart(Index + 1);
- }
- public void OnBtnLast()
- {
- //Restart(Index - 1);
- gm = null;
- onUploadScore();
- ////结束游戏页面
- //userGameAnalyse1.UploadData(true);
- //userGameAnalyse1.onResetOverlayData();
- //SceneManager.LoadScene("Home", LoadSceneMode.Single);
- //结束游戏页面
- userGameAnalyse1.showResultView(() =>
- {
- SceneManager.LoadScene("Home", LoadSceneMode.Single);
- });
- }
- void Start()
- {
- if (ShootCheck.ins.bluetoothDeviceStatus == BluetoothDeviceStatus.MagazineLoading)
- OnLoading();
- else
- OnSeparation();
- //Screen.SetResolution(1280, 720, false); // 设置分辨率为1920x1080,并设置为全屏模式
- Invoke("GameStart", 4);
- Game1();
- Invoke("Game2", 1);
- Invoke("Game3", 2);
- var canvases = FindObjectsByType<Canvas>(FindObjectsSortMode.InstanceID);
- foreach (var canvas in canvases)
- {
- if (canvas.name == "Canvas")
- {
- _canvasRectTransform = canvas.GetComponent<RectTransform>();
- break;
- }
- }
- //靶子默认状态
- var show = UIManager._ins.GetArrowBtnState();
- var arrow = shootingEvent.GetComponent<Image>();
- var color = arrow.color;
- if (show)
- color.a = 1;
- else
- color.a = 0;
- arrow.color = color;
- UIManager._ins.ShowQuit();
- }
- public void OpenSelectLevel()
- {
- SelectLv.SetActive(true);
- }
- public Vector2 GetCanvasSize()
- {
- return _canvasRectTransform.sizeDelta;
- }
- void Game1()
- {
- gameSatrtSound.clip = gameSatrtClips[0];
- gameSatrtSound.Play();
- }
- void Game2()
- {
- gameSatrtSound.clip = gameSatrtClips[1];
- gameSatrtSound.Play();
- }
- void Game3()
- {
- gameSatrtSound.clip = gameSatrtClips[2];
- gameSatrtSound.Play();
- }
- void GameStart()
- {
- isbegin = true;
- }
- private float reloadTime = 0;
-
- private void Reload(bool delay = false)
- {
- if (delay)
- {
- reloadTime = 3f;
- }
- else
- {
- clipsize = BulletCount;
- bulletCount -= font.Clip;
- bulletCount += clipsize;
- font.Clip = clipsize;
- bulletNull.SetActive(false);
- for (int i = 0; i < bulletImages.Length; i++)
- {
- bulletImages[i].SetActive(true);
- }
- }
- }
- public bool Reloading()
- {
- return unload;
- //return reloadTime > 0;
- }
- float _lastShootTime = 0;
- /// <summary>
- /// 射击
- /// </summary>
- /// <param name="bAddCount">是否是有效射箭</param>
- public void Shooting(bool bAddCount = false)
- {
- //加个间隔
- if (Time.realtimeSinceStartup - _lastShootTime < 0.5f) return;
- _lastShootTime = Time.realtimeSinceStartup;
- bAddCountScore = bAddCount;
- DoShoot();
- }
- private void DoShoot()
- {
- if (shootingEvent.ShootUIBtn())
- return;
- if (unload || clipsize <= 0)
- {
- Debug.Log("卸了弹夹 或者 没子弹了!");
- //没有子弹的声音
- //ShootingSound.Play();
- bulletImages[0].SetActive(false);
- bulletNull.SetActive(true);
- return;
- }
- else
- //正常发射的声音
- ShootingSound.Play();
- clipsize--;
- if (clipsize <= 0)
- {
- //Reload(true);//不自动装弹
- }
- font.Clip = clipsize;
- bulletImages[clipsize].SetActive(false);
- shootingEvent.OnShooting();
- }
- private void Update()
- {
- //if (reloadTime > 0)
- //{
- // reloadTime -= Time.deltaTime;
- // if (reloadTime <= 0)
- // Reload();
- //}
- #if UNITY_EDITOR
- if (Input.GetMouseButtonDown(0))
- {
- shootingEvent.OnPositionUpdate(Input.mousePosition);
- Shooting(true);
- }
- if (Input.GetKeyDown(KeyCode.W))
- {
- countDownTime = 0;
- }
- if (Input.GetKeyDown(KeyCode.R))
- {
- UIManager._ins.Reload();
- }
- #endif
- if (isbegin)
- {
- if (canEnterNextOrder)//靶子全消失了 开始走序列休息时间
- {
- if (nextOrderWaitTime <= 0)
- {
- //开始下一序列
- TriggerRandomEvent();
- }
- nextOrderWaitTime -= Time.deltaTime;
- }
- //游戏倒计时
- if (countDownTime <= 0)
- {
- //游戏时间到了 结束
- GameEnd();
- }
- else
- {
- countDownTime -= Time.deltaTime;
- var timeInt = Mathf.CeilToInt(countDownTime);
- if(timeInt != countDownTimeCache)
- {
- countDownTimeCache = timeInt;
- UpdateCountDown(countDownTimeCache);
- }
- imgSlider.fillAmount = countDownTime / (float)LvCfg.TotalTime;
- }
- if (curMoveCtrl != null && curMoveCtrl is IUpdate)
- {
- (curMoveCtrl as IUpdate).Update();
- }
- }
- }
- private void UpdateCountDown(int value)
- {
- countDownUI.text = $"{value}";
- }
- private void GameEnd()
- {
- stop = true;
- GameOver.SetActive(true);
- GameOverGrade(score);
- isbegin = false;
- countDownTimeCache = 0;
- //游戏结束上传分数
- onUploadScore();
- }
- /// <summary>
- /// 下一轮
- /// </summary>
- void TriggerRandomEvent()
- {
- canEnterNextOrder = false;
- Debug.Log($"新一轮创建 curOrderIdx={curOrderIdx}");
- if (LvCfg.orders.Length > curOrderIdx)
- {
- orderCfg = LvCfg.orders[curOrderIdx];
- CreateTargets();
- curOrderIdx++;
- }
- else
- GameEnd();
- }
- Dictionary<MoveType, Move> movesCtrl = new Dictionary<MoveType, Move>()
- {
- [MoveType.Stay] = new Stay(),
- [MoveType.VET] = new VET(),
- [MoveType.ROT] = new ROT(),
- [MoveType.W] = new W(),
- [MoveType.W2] = new W2(),
- [MoveType.RelativeHor] = new RelativeHor(),
- [MoveType.RelativeVet] = new RelativeVet(),
- [MoveType.HOR] = new HOR(),
- [MoveType.Diagonal] = new Diagonal(),
- [MoveType.LeftToRight] = new LeftToRight(),
- [MoveType.RightToLeft] = new RightToLeft(),
- };
- private Move curMoveCtrl;
- /// <summary>
- /// 创建当前轮靶子
- /// </summary>
- private void CreateTargets()
- {
- var createCount = orderCfg.Big + orderCfg.Middle + orderCfg.Small;
- Debug.Log($"创建数量 Big={orderCfg.Big} Middle={orderCfg.Middle} Small={orderCfg.Small}");
- tragetLeftNum = createCount;
- List<SpineAnimationLoader> gos = new List<SpineAnimationLoader>();
- for (int i = 0; i < createCount; i++)
- {
- var go = Instantiate(target, tp);
- var targetIns = go.GetComponent<SpineAnimationLoader>();
- if(i < orderCfg.Big)
- targetIns.Init(0.8f * 0.732f, orderCfg, OnTargetDestory);
- else if (i < orderCfg.Big + orderCfg.Middle)
- targetIns.Init(0.5f * 0.692f, orderCfg, OnTargetDestory);
- else
- targetIns.Init(0.3f * 0.733f, orderCfg, OnTargetDestory);
- go.SetActive(true);
- gos.Add(targetIns);
- }
- movesCtrl.TryGetValue(orderCfg.MoveType, out curMoveCtrl);
- if (curMoveCtrl == null)
- curMoveCtrl = movesCtrl[MoveType.Stay];
- curMoveCtrl.SetGo(gos);
- }
- /// <summary>
- /// 靶子被射击或者到时间销毁
- /// </summary>
- private void OnTargetDestory()
- {
- tragetLeftNum--;
- if (tragetLeftNum <= 0)
- {
- curMoveCtrl = null;
- Debug.Log("当前轮结束");
- canEnterNextOrder = true;
- //重置休息时间
- nextOrderWaitTime = orderCfg.WaitTime;
- }
- }
- public void ShowScore()
- {
- //font.Text = score;
- TopScore.text = score.ToString().PadLeft(3, '0');
- }
- public Score scoreSprite;
- public void ShowScoreCom(int score, Vector3 pos, Vector2 scorepos, Transform tf, int posIdx)
- {
- Debug.Log($"得分 score{score}");
- if (score >= 6)
- {
- var go = GameObject.Instantiate(scoreCom, pos, Quaternion.identity, _canvasRectTransform);
- go.gameObject.SetActive(true);
- go.transform.localScale = Vector3.one * 0.55f;
- go.ShowScore(score, scorepos);
- }
- else
- {
- var go = GameObject.Instantiate(scoreCom1, tf.position, Quaternion.identity, _canvasRectTransform);
- go.gameObject.SetActive(true);
- var halfRadius = 547f * 0.5f;
- var offest = tf.localScale.x * halfRadius + 80f;
- var x = (posIdx == 1 || posIdx == 2) ? offest : -offest;
- var y = (posIdx == 1 || posIdx == 4) ? offest : -offest;
- go.ShowScore(score, new Vector3(x, y, 0));
- }
- }
- public void ShowMiss(Vector3 position)
- {
- if (stop)
- return;
- var go = GameObject.Instantiate(Miss, position, Quaternion.identity, _canvasRectTransform);
- go.AddComponent<CountDown>();
- go.SetActive(true);
- }
- public void GameOverGrade(int score)
- {
- hitCountUI.text = hitCount.ToString();
- var bulletUse = bulletCount - font.Clip;
- clipsizeUI.text = bulletUse.ToString();
- float rate = 0;
- if (hitCount != 0)
- rate = (float)hitCount / (float)bulletUse;
- if(rate == 0)
- {
- rate = 0;
- }
- shootRate.text = string.Format("{0:P0}", rate);
- //font.ShowOverScore();
- font.Text = score;
- if (score < 20)
- {
- Debug.Log("游戏失败");
- grade.sprite = gradeSprites[0];
- return;
- }
- if (score > 50)
- {
- Debug.Log("完美");
- grade.sprite = gradeSprites[1];
- return;
- }
- if (score >= 20 && score <= 30)
- {
- Debug.Log("合格");
- grade.sprite = gradeSprites[2];
- return;
- }
- if (score > 30 && score <= 50)
- {
- Debug.Log("优秀");
- grade.sprite = gradeSprites[3];
- return;
- }
- }
- public void Restart(int index)
- {
- string name = "";
- if (index == 0)
- name = "Hyperspace01";
- else if (index == 1)
- name = "Hyperspace02";
- else if (index == 2)
- name = "Hyperspace03";
- SceneManager.LoadScene(name);
- }
- //public void SetTarget(int index)
- //{
- // goodImage.sprite = font.sprites[index];
- // good.SetActive(true);
- //}
-
- //public void SetGreat(int index)
- //{
- // greatImage.sprite = font.sprites[index];
- // gaeat.SetActive(true);
- //}
- /// <summary>
- /// 弹夹分离
- /// </summary>
- public void OnSeparation()
- {
- unload = true;
- clipsize = 0;
- bulletCount -= font.Clip;
- font.Clip = clipsize;
- }
- /// <summary>
- /// 弹夹上膛
- /// </summary>
- public void OnLoading()
- {
- unload = false;
- Reload();
- }
- #region 新增 UIManager 和 TargetObject2D
- private GameObject uiManagerInstance;
- private GameObject targetObject2D;
- // 动态加载并生成 UIManager
- public void CreateUIManager()
- {
- GameObject uiManagerPrefab = Resources.Load<GameObject>("UIManager"); // 从 Resources 中加载 UIManager 预制
- uiManagerInstance = Instantiate(uiManagerPrefab); // 实例化 UIManager
- //管理分数上传
- userGameAnalyse1 = UserGameAnalyse1.CreateWhenGameStartAndReturn(16);
- }
- //校准靶子
- public void CreateTargetObject2D() {
-
- GameObject targetObject2DPrefab = Resources.Load<GameObject>("TargetObject2D");
- targetObject2D = Instantiate(targetObject2DPrefab, UI);
- }
- // 销毁 UIManager 实例
- public void DestroyUIManager()
- {
- if (UIManager._ins != null)
- {
- Destroy(UIManager._ins.gameObject); // 销毁 UIManager 实例
- uiManagerInstance = null;
- }
- }
- /// <summary>
- /// 射击次数
- /// </summary>
- /// <param name="count"></param>
- public void onShootCount(int count)
- {
- userGameAnalyse1.changeShootingCount(count);
- }
- /// <summary>
- /// 上传分数到服务器
- /// </summary>
- public void onUploadScore()
- {
- if (_score > 0)
- {
- Debug.Log("上传的积分为:" + _score);
- RankComp.Instance.uploadSinglePlayerGameRes(_score);
- _score = 0;
- }
- }
- #endregion
- }
|