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(); } } /// /// 游戏时间 /// private float countDownTime; int countDownTimeCache; /// /// 子弹数量 /// private int clipsize; const int BulletCount = 15; /// /// 靶子存在最长时间 /// float _targetExistenceTimeMax = 5; public float TargetExistenceTimeMax { get { return _targetExistenceTimeMax; } set { _targetExistenceTimeMax = value; } } /// /// 靶子存在最短时间 /// 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; /// /// 记录当前射箭是否记录分数 /// private bool bAddCountScore { get; set; } = false; [HideInInspector] public bool getAddCountScore => bAddCountScore; //分数统计 [HideInInspector] public UserGameAnalyse1 userGameAnalyse1; public int Index = 0; private bool unload = false; /// /// 当前难度的配置 /// public Level LvCfg = null; /// /// 当前序列的配置 /// public Order orderCfg = null; float nextOrderWaitTime; int curOrderIdx; bool canEnterNextOrder = true; bool isbegin = false; int tragetLeftNum; /// /// 当前序列 /// 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 = $"/{MaxLevel}"; shootingEvent = FindObjectOfType(); 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); } 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(FindObjectsSortMode.InstanceID); foreach (var canvas in canvases) { if (canvas.name == "Canvas") { _canvasRectTransform = canvas.GetComponent(); break; } } //靶子默认状态 var show = UIManager._ins.GetArrowBtnState(); var arrow = shootingEvent.GetComponent(); 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; /// /// 射击 /// /// 是否是有效射箭 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(); } /// /// 下一轮 /// void TriggerRandomEvent() { canEnterNextOrder = false; Debug.Log($"新一轮创建 curOrderIdx={curOrderIdx}"); if (LvCfg.orders.Length > curOrderIdx) { orderCfg = LvCfg.orders[curOrderIdx]; CreateTargets(); curOrderIdx++; } else GameEnd(); } Dictionary movesCtrl = new Dictionary() { [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; /// /// 创建当前轮靶子 /// 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 gos = new List(); for (int i = 0; i < createCount; i++) { var go = Instantiate(target, tp); var targetIns = go.GetComponent(); 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); } /// /// 靶子被射击或者到时间销毁 /// 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(); 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); //} /// /// 弹夹分离 /// public void OnSeparation() { unload = true; clipsize = 0; bulletCount -= font.Clip; font.Clip = clipsize; } /// /// 弹夹上膛 /// public void OnLoading() { unload = false; Reload(); } #region 新增 UIManager 和 TargetObject2D private GameObject uiManagerInstance; private GameObject targetObject2D; // 动态加载并生成 UIManager public void CreateUIManager() { GameObject uiManagerPrefab = Resources.Load("UIManager"); // 从 Resources 中加载 UIManager 预制 uiManagerInstance = Instantiate(uiManagerPrefab); // 实例化 UIManager //管理分数上传 userGameAnalyse1 = UserGameAnalyse1.CreateWhenGameStartAndReturn(16); } //校准靶子 public void CreateTargetObject2D() { GameObject targetObject2DPrefab = Resources.Load("TargetObject2D"); targetObject2D = Instantiate(targetObject2DPrefab, UI); } // 销毁 UIManager 实例 public void DestroyUIManager() { if (UIManager._ins != null) { Destroy(UIManager._ins.gameObject); // 销毁 UIManager 实例 uiManagerInstance = null; } } /// /// 射击次数 /// /// public void onShootCount(int count) { userGameAnalyse1.changeShootingCount(count); } /// /// 上传分数到服务器 /// public void onUploadScore() { if (_score > 0) { Debug.Log("上传的积分为:" + _score); RankComp.Instance.uploadSinglePlayerGameRes(_score); _score = 0; } } #endregion }