wangguan
2020-11-17 3da3d10bfdd30a1ad7f8c48ab9fd7e7745e3d053
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Core.Utilities;
using KTGMGemClient;
using Microsoft.VisualBasic;
using TMPro.Examples;
using TowerDefense.Level;
using TowerDefense.UI.HUD;
using UnityEditor;
using UnityEngine;
using UnityEngine.Analytics;
using UnityEngine.UI;
 
namespace TowerDefense.Towers.Placement
{
    /// <summary>
    /// A tower placement location made from a grid.
    /// Its origin is centered in the middle of the lower-right cell. It can be oriented in any direction
    /// </summary>
    [RequireComponent(typeof(BoxCollider))]
    public class TowerPlacementGrid : MonoBehaviour, IPlacementArea
    {
        public static float GRID_OPENCASH_SELF = 100;
        public static float GRID_OPENCASH_OPPO = 100;
        /// <summary>
        /// Prefab used to visualise the grid.
        /// 如果在游戏内并不需要Grid显示或者用其它的方式显示,则可以去掉这个数据。
        /// </summary>
        public PlacementTile placementTilePrefab;
 
        /// <summary>
        /// Visualisation prefab to instantiate on mobile platforms
        /// </summary>
        public PlacementTile placementTilePrefabMobile;
 
        /// <summary>
        /// 塔位血条对应的UI界面.
        /// </summary>
        public GameObject towerBloodUIPrefab;
 
        /// <summary>
        /// 此位置上塔对应的子弹充能Prefab.塔放置到当前的塔位后,如果是对应的塔防类型,需要把
        /// 相应的界面指针传到塔防的数据结构内。
        /// </summary>
        public GameObject towerBulletUIPrefab;
        /// <summary>
        /// 充能条对应的界面
        /// </summary>
        public GameObject towerEnergyUIPrefab;
 
        /// <summary>
        /// 等待购买开启对应按钮.
        /// </summary>
        public Button waitBuyBtnPrefab;
 
        /// <summary>
        /// 充能特效对应的Prefab.
        /// </summary>
        public ParticleSystem energyEffectPrefab;
 
        // TEST CODE TO DELETE: 
        public ParticleSystem TestParticle;
        protected ParticleSystem PlayParticle;
        protected Timer effectStopTimer;
        protected bool bTimerStart = false;
 
 
        /// <summary>
        /// 用于调试位置信息的Image.
        /// </summary>
        public Image debugImg;
 
        /// <summary>
        /// 最后一行格子与前一行格子之间的空位长度.
        /// </summary>
        public float gridFreePos;
 
 
        /// <summary>
        /// The dimensions of the grid 
        /// </summary>
        public IntVector2 dimensions;
 
 
        /// <summary>
        /// Size of the edge of a cell
        /// </summary>
        [Tooltip("The size of the edge of one grid cell for this area. Should match the physical grid size of towers")]
        public float gridSize = 1;
 
        /// <summary>
        /// Inverted grid size, to multiply with
        /// </summary>
        float m_InvGridSize;
 
        /// <summary>
        /// Array of available cells
        /// </summary>
        bool[,] m_AvailableCells;
 
        /// <summary>
        /// 每一个格子的对应的类型。不同的类型可以转化,但可合成的类型不能转化。
        /// 初始化的时候会根据配置数据来初始化不同的格子状态
        /// </summary>
        PlacementGridType[,] m_arrGridType;
 
        TowerGridOpen[] m_arrTGO;
 
        float[] m_arrCoinGenTime;
 
        /// <summary>
        /// 每一个Tile格子的中心点对应的屏幕坐标.
        /// </summary>
        Vector2[,] m_arrGridCentUIPos;
 
        /// <summary>
        /// 攻击塔位对应的UI位置信息.
        /// </summary>
        Vector2[] m_arrTowerBloodUIPos;
        TowerBloodVis[] arrTowerBloodUi;
 
        /// <summary>
        /// 攻击塔位对应的子弹UI位置信息.
        /// </summary>
        Vector2[] m_arrTowerBulletUIPos;
        BulletUICtl[] arrTowerBulletUi;
        EnergyUICtl[] arrTowerEnergyUi;
        ParticleSystem[] arrTowerEnergyEffect;
 
 
        /// <summary>
        /// 塔位对应的屏幕坐标尺寸
        /// </summary>
        float m_fGridUISize;
 
        /// <summary>
        /// Array of <see cref="PlacementTile"/>s
        /// </summary>
        PlacementTile[,] m_Tiles;
 
        /// <summary>
        /// Converts a location in world space into local grid coordinates.
        /// </summary>
        /// <param name="worldLocation"><see cref="Vector3"/> indicating world space coordinates to convert.</param>
        /// <param name="sizeOffset"><see cref="IntVector2"/> indicating size of object to center.</param>
        /// <returns><see cref="IntVector2"/> containing the grid coordinates corresponding to this location.</returns>
        public IntVector2 WorldToGrid(Vector3 worldLocation, IntVector2 sizeOffset)
        {
            Vector3 localLocation = transform.InverseTransformPoint(worldLocation);
 
            // Scale by inverse grid size
            localLocation *= m_InvGridSize;
 
            // Offset by half size
            var offset = new Vector3(sizeOffset.x * 0.5f, 0.0f, sizeOffset.y * 0.5f);
            localLocation -= offset;
 
            int xPos = Mathf.RoundToInt(localLocation.x);
            int yPos = Mathf.RoundToInt(localLocation.z);
 
            return new IntVector2(xPos, yPos);
        }
 
        public IntVector2 getdimsize()
        {
            return this.dimensions;
        }
 
 
        /// <summary>
        /// 实现引用.
        /// </summary>
        public bool opponent { get; set; }
        public bool isOpponent()
        {
            return opponent;
        }
 
        /// <summary>
        /// 获取对应位置的充能子弹界面指针.
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public BulletUICtl GetBulletUICtl(int x, int y)
        {
            return this.arrTowerBulletUi[x];
        }
 
        /// <summary>
        /// 获取对应位置的能量条界面指针.
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public EnergyUICtl GetEnergyUICtl(int x, int y)
        {
            return this.arrTowerEnergyUi[x];
        }
 
        public FreezeBreath GetFreezeBreath(int x, int y)
        {
            return null;
        }
 
        /// <summary>
        /// 获取一个可以放置塔防的位置.
        /// </summary>
        /// <returns></returns>
        public IntVector2 getFreePos(int xdim, int ydim, bool forceGet = false)
        {
            IntVector2 resvec = new IntVector2();
            int subval = 1;
            if (forceGet)
                subval = 0;
            // Range产生的随机数是包括min,排除max. Y值再减1是因为最前面一排是战斗塔位。
            int maxXdim = this.dimensions.x - xdim + 1;
            int maxYdim = (this.dimensions.y - ydim + 1) - subval;
            resvec.x = UnityEngine.Random.Range(0, maxXdim);
            resvec.y = UnityEngine.Random.Range(0, maxYdim);
 
            TowerFitStatus tfs = this.Fits(resvec, new IntVector2(xdim, ydim));
 
            // 处理ForceGet
            bool legalVal = (tfs == TowerFitStatus.Fits);
            if (legalVal && forceGet)
            {
                if (m_arrGridType[resvec.x, resvec.y] != PlacementGridType.EGridOpen)
                    legalVal = false;
            }
 
            if (legalVal)
            {
                return resvec;
            }
            else
            {
                int looptime = 0;
                while (looptime < 10)
                {
                    looptime++;
                    resvec.x = UnityEngine.Random.Range(0, maxXdim);
                    resvec.y = UnityEngine.Random.Range(0, maxYdim);
 
                    tfs = this.Fits(resvec, new IntVector2(xdim, ydim));
 
                    // 处理forceGet.
                    if (forceGet)
                    {
                        if (m_arrGridType[resvec.x, resvec.y] != PlacementGridType.EGridOpen)
                            continue;
                    }
 
                    if (tfs == TowerFitStatus.Fits) return resvec;
                }
 
                // 循环超过10次,则直接寻找空位,找不到则返回错误.
                for (int x = 0; x < maxXdim; x++)
                {
                    for (int y = 0; y < maxYdim; y++)
                    {
                        if (!m_AvailableCells[x, y])
                        {
                            // 处理ForceGet
                            if (forceGet)
                            {
                                if (m_arrGridType[x, y] != PlacementGridType.EGridOpen)
                                    continue;
                            }
 
                            resvec.x = x;
                            resvec.y = y;
                            return resvec;
                        }
                    }
                }
            }
 
            return new IntVector2(-1, -1);
        }
 
        /// <summary>
        /// 判断是否是一个空置的攻击位
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public bool isFreeAtackPos(int x, int y)
        {
            if (m_AvailableCells[x, y] == true)
                return false;
 
            if (m_arrGridType[x, y] == PlacementGridType.EGridOpen)
                return true;
 
            return false;
        }
 
        /// <summary>
        /// 是否是等待购买的攻击塔位.
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public bool isWaitBuyGrid(int x, int y)
        {
            if (m_AvailableCells[x, y] == true) return false;
 
            if (m_arrGridType[x, y] == PlacementGridType.EGridWaitBuy)
                return true;
 
            return false;
        }
 
        /// <summary>
        /// 开启金币生产模式
        /// </summary>
        public void startCoinGenMode()
        {
            m_arrCoinGenTime = new float[dimensions.x];
            int ty = dimensions.y - 1;
            for (int tx = 0; tx < dimensions.x; tx++)
            {
                if ((m_arrGridType[tx, ty] == PlacementGridType.EGridOpen) || (m_arrGridType[tx, ty] == PlacementGridType.EGridCombo))
                    m_arrCoinGenTime[tx] = 0.0f;
                else
                    m_arrCoinGenTime[tx] = -1f;
            }
        }
 
        protected void partilceUpdate()
        {
            if (bTimerStart)
            {
                if (effectStopTimer.Tick(Time.deltaTime))
                {
                    bTimerStart = false;
                    effectStopTimer.Reset();
                }
            }
 
            if (UnityEngine.Input.GetKeyDown(KeyCode.Q))
            {
                this.PlayEnergyEffect(2, true);
                return;
            }
            if (UnityEngine.Input.GetKeyDown(KeyCode.W))
            {
                this.PlayEnergyEffect(2, false);
                return;
            }
 
            // TEST CODE TO DELETE:
            if (PlayParticle != null)
            {
 
                if (UnityEngine.Input.GetKeyDown(KeyCode.E))
                {
                    PlayParticle = Instantiate(TestParticle);
                    Vector3 tpos = this.transform.position;
                    tpos.y += 5.0f;
                    PlayParticle.transform.position = tpos;
 
                    //Vector3 lookVec = Vector3.zero;
                    //lookVec.x = 1;
                    //PlayParticle.transform.LookAt(lookVec);
                    PlayParticle.Play();
                    //effectStopTimer.SetTime(0.15f);
                    //bTimerStart = true;
                }
                if (UnityEngine.Input.GetKeyDown(KeyCode.F))
                {
                    PlayParticle.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
                }
            }
        }
 
        void Update()
        {
            // 
            // TEST CODE TO DELETE:
            partilceUpdate();
 
            if (m_arrCoinGenTime == null) return;
 
            float delta = Time.deltaTime;
            float timePe = JsonDataCenter.GOLD_TIME / 1000.0f;
            // 处理每一开启的格子,用于金币数据增加:
            for (int ti = 0; ti < dimensions.x; ti++)
            {
                // 是否是可以增加金币的格子:
                if (m_arrCoinGenTime[ti] < 0) continue;
 
                // 时间判断.
                if (m_arrCoinGenTime[ti] >= 0)
                {
                    m_arrCoinGenTime[ti] += delta;
                    if (m_arrCoinGenTime[ti] > timePe)
                    {
                        m_arrCoinGenTime[ti] -= timePe;
                        // 增加金币:
                        if (opponent)
                            OpponentMgr.instance.currency.AddCurrency(JsonDataCenter.GOLD_ADD);
                        else
                            LevelManager.instance.currency.AddCurrency(JsonDataCenter.GOLD_ADD);
                    }
 
                }
 
            }
        }
 
        /// <summary>
        /// 设置格子为合成状态。
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public bool SetComboGrid(int x, int y)
        {
            if (m_arrGridType[x, y] == PlacementGridType.EGridOpen)
            {
                m_arrGridType[x, y] = PlacementGridType.EGridCombo;
                return true;
            }
            else return false;
        }
 
        /// <summary>
        /// 设置某一个格子为已破坏塔位。
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public bool SetDestroyedGrid(int x, int y)
        {
            // 释放掉界面显示
            if (m_arrGridType[x, y] == PlacementGridType.EGridWaitBuy)
            {
                if (m_arrTGO[x])
                {
                    m_arrTGO[x].Release();
                    m_arrTGO[x] = null;
                }
            }
 
            // 任何情况下,都可以破坏,没有购买,上面有塔,都得破坏
            m_arrGridType[x, y] = PlacementGridType.EGridDestroyed;
            if (arrTowerBloodUi[x] != null)
                arrTowerBloodUi[x].gameObject.SetActive(false);
 
            if (arrTowerBulletUi[x] != null)
                arrTowerBulletUi[x].gameObject.SetActive(false);
 
            if (arrTowerEnergyUi[x] != null)
                arrTowerEnergyUi[x].gameObject.SetActive(false);
 
            m_Tiles[x, y].SetTileType(PlacementGridType.EGridDestroyed);
 
            return true;
        }
 
 
        /// <summary>
        /// Returns the world coordinates corresponding to a grid location.
        /// </summary>
        /// <param name="gridPosition">The coordinate in grid space</param>
        /// <param name="sizeOffset"><see cref="IntVector2"/> indicating size of object to center.</param>
        /// <returns>Vector3 containing world coordinates for specified grid cell.</returns>
        public Vector3 GridToWorld(IntVector2 gridPosition, IntVector2 sizeOffset)
        {
            float freePos = 0;
            if (gridPosition.y == 2)
                freePos = gridFreePos;
            // Calculate scaled local position
            Vector3 localPos = new Vector3(gridPosition.x + (sizeOffset.x * 0.5f), 0, gridPosition.y + (sizeOffset.y * 0.5f) + freePos) *
                               gridSize;
 
            return transform.TransformPoint(localPos);
        }
 
        /// <summary>
        /// Tests whether the indicated cell range represents a valid placement location.
        /// </summary>
        /// <param name="gridPos">The grid location</param>
        /// <param name="size">The size of the item</param>
        /// <returns>Whether the indicated range is valid for placement.</returns>
        public TowerFitStatus Fits(IntVector2 gridPos, IntVector2 size)
        {
            // If the tile size of the tower exceeds the dimensions of the placement area, immediately decline placement.
            if ((size.x > dimensions.x) || (size.y > dimensions.y))
            {
                return TowerFitStatus.OutOfBounds;
            }
 
            IntVector2 extents = gridPos + size;
 
            // Out of range of our bounds
            if ((gridPos.x < 0) || (gridPos.y < 0) ||
                (extents.x > dimensions.x) || (extents.y > dimensions.y))
            {
                return TowerFitStatus.OutOfBounds;
            }
 
            // Ensure there are no existing towers within our tile silhuette.
            for (int y = gridPos.y; y < extents.y; y++)
            {
                for (int x = gridPos.x; x < extents.x; x++)
                {
                    if (m_AvailableCells[x, y])
                    {
                        return TowerFitStatus.Overlaps;
                    }
                }
            }
 
            // If we've got this far, we've got a valid position.
            return TowerFitStatus.Fits;
        }
 
        /// <summary>
        /// Sets a cell range as being occupied by a tower.
        /// </summary>
        /// <param name="gridPos">The grid location</param>
        /// <param name="size">The size of the item</param>
        public void Occupy(IntVector2 gridPos, IntVector2 size)
        {
            IntVector2 extents = gridPos + size;
 
            // Validate the dimensions and size
            if ((size.x > dimensions.x) || (size.y > dimensions.y))
            {
                throw new ArgumentOutOfRangeException("size", "Given dimensions do not fit in our grid");
            }
 
            // Out of range of our bounds
            if ((gridPos.x < 0) || (gridPos.y < 0) ||
                (extents.x > dimensions.x) || (extents.y > dimensions.y))
            {
                Debug.Log("目标GridPos is:" + gridPos.x + "," + gridPos.y + "," + size.x + "," + size.y);
                throw new ArgumentOutOfRangeException("gridPos", "Given footprint is out of range of our grid");
            }
 
            // 填充对应格子为占用状态
            for (int y = gridPos.y; y < extents.y; y++)
            {
                for (int x = gridPos.x; x < extents.x; x++)
                {
                    m_AvailableCells[x, y] = true;
                }
            }
        }
 
        /// <summary>
        /// Removes a tower from a grid, setting its cells as unoccupied.
        /// </summary>
        /// <param name="gridPos">The grid location</param>
        /// <param name="size">The size of the item</param>
        public void Clear(IntVector2 gridPos, IntVector2 size)
        {
            IntVector2 extents = gridPos + size;
 
            // Validate the dimensions and size
            if ((size.x > dimensions.x) || (size.y > dimensions.y))
            {
                throw new ArgumentOutOfRangeException("size", "Given dimensions do not fit in our grid");
            }
 
            // Out of range of our bounds
            if ((gridPos.x < 0) || (gridPos.y < 0) ||
                (extents.x > dimensions.x) || (extents.y > dimensions.y))
            {
                throw new ArgumentOutOfRangeException("gridPos", "Given footprint is out of range of our grid");
            }
 
            // 清空对应格子为占用状态
            for (int y = gridPos.y; y < extents.y; y++)
            {
                for (int x = gridPos.x; x < extents.x; x++)
                {
                    m_AvailableCells[x, y] = false;
                }
            }
        }
 
        /// <summary>
        /// Initialize values
        /// </summary>
        protected virtual void Awake()
        {
            ResizeCollider();
 
            // Initialize empty bool array (defaults are false, which is what we want)
            m_AvailableCells = new bool[dimensions.x, dimensions.y];
 
            // 暂使这种简单的模式来处理正反双方
            if (dimensions.y > 1)
                opponent = false;
            else
                opponent = true;
 
            /*
            // 初始化塔位类型.
            initTileGridType();
 
            // Precalculate inverted grid size, to save a division every time we translate coords
            m_InvGridSize = 1 / gridSize;
 
            SetUpGrid();
            */
        }
 
        protected void addDebugImg(Vector2 pos)
        {
            Image timg = Instantiate(this.debugImg);
            GameObject go = GameObject.Find("BattleMainUI");
            if (!go) return;
            Transform tp = go.GetComponent<Transform>();
            timg.GetComponent<Transform>().SetParent(tp, true);
            Vector3 tpos = timg.transform.position;
            tpos.x = pos.x;
            tpos.y = pos.y;
            timg.transform.position = tpos;
 
            return;
        }
 
        /// <summary>
        /// 预计算塔位格子对应的屏幕坐标以及塔位格子的屏幕尺寸
        /// WORK START: 计算屏幕坐标,然后开搞屏幕相关的内容。下午要把塔位上显示界面搞出来。
        /// WORK START: 为什么OppoGrid对应的屏幕坐标不对?
        /// 
        /// </summary>
        void preCalculateGridUIPos()
        {
            m_arrGridCentUIPos = new Vector2[dimensions.x, dimensions.y];
 
            Vector3 targetPos = GridToWorld(new IntVector2(0, 0), new IntVector2(1, 1));
            Vector3 svec = this.transform.position;
 
            if (!ViewPortAdj.instance.bAdjViewPort)
                ViewPortAdj.instance.adjViewportRect();
 
            UnityEngine.Camera sceneCam = ViewPortAdj.instance.cachedCamera;
            Vector3 centPos = sceneCam.WorldToScreenPoint(targetPos);
            Vector3 lbPos = sceneCam.WorldToScreenPoint(svec);
 
            m_fGridUISize = (centPos.y - lbPos.y) * 2.0f;
 
            for (int ty = 0; ty < dimensions.y; ty++)
            {
                for (int tx = 0; tx < dimensions.x; tx++)
                {
                    m_arrGridCentUIPos[tx, ty].x = centPos.x + tx * m_fGridUISize;
                    m_arrGridCentUIPos[tx, ty].y = centPos.y + ty * m_fGridUISize;
                }
 
                if ((gridFreePos > 0) && (ty == (dimensions.y - 1)))
                {
                    targetPos = GridToWorld(new IntVector2(0, ty), new IntVector2(1, 1));
                    centPos = sceneCam.WorldToScreenPoint(targetPos);
 
                    for (int tx = 0; tx < dimensions.x; tx++)
                    {
                        m_arrGridCentUIPos[tx, ty].x = centPos.x + tx * m_fGridUISize;
                        m_arrGridCentUIPos[tx, ty].y = centPos.y;
                    }
                }
            }
 
            // 血条位置的设定
            preCalculateTowerBloodUi();
 
            m_arrTGO = new TowerGridOpen[dimensions.x];
            // 设置界面相关的内容:
            for (int y = dimensions.y - 1; y < dimensions.y; y++)
            {
                for (int x = 0; x < dimensions.x; x++)
                {
                    if (m_arrGridType[x, y] != PlacementGridType.EGridWaitBuy)
                        continue;
                    Button tbtn = Instantiate(this.waitBuyBtnPrefab);
                    GameObject go = GameObject.Find("BattleMainUI");
                    if (!go) continue;
                    Transform tp = go.GetComponent<Transform>();
                    tbtn.GetComponent<Transform>().SetParent(tp, true);
                    Vector3 tpos = tbtn.transform.position;
                    tpos.x = m_arrGridCentUIPos[x, y].x;
                    tpos.y = m_arrGridCentUIPos[x, y].y + m_fGridUISize / 10;
                    tbtn.transform.position = tpos;
 
                    // 设置为界面最下层:
                    tbtn.transform.SetAsFirstSibling();
 
                    // 设置按钮对应的点击功能
                    TowerGridOpen tgo = tbtn.GetComponent<TowerGridOpen>();
                    if (tgo)
                    {
                        tgo.SetBuyBtnInfo(x, y, this);
                        if (opponent)
                            tgo.cashText.SetText(TowerPlacementGrid.GRID_OPENCASH_OPPO.ToString());
                        else
                            tgo.cashText.SetText(TowerPlacementGrid.GRID_OPENCASH_SELF.ToString());
                        m_arrTGO[x] = tgo;
                    }
                }
            }
 
        }
 
        /// <summary>
        /// 设置某一个位置的血条.
        /// </summary>
        /// <param name="ix">Tower在X方向上的位置信息</param>
        /// <param name="health"></param>
        public void setTowerPosHealth(int ix, float health)
        {
            if (m_arrGridType[ix, dimensions.y - 1] == PlacementGridType.EGridDestroyed)
                return;
 
            if ((arrTowerBloodUi[ix] != null))
            {
                if (health < 1.0f)
                {
                    arrTowerBloodUi[ix].gameObject.SetActive(true);
                    arrTowerBloodUi[ix].SetHealthScale(health);
                }
            }
        }
 
        /// <summary>
        /// 处理Tower血量的UI界面
        /// </summary>
        protected void preCalculateTowerBloodUi()
        {
            // 处理攻击塔位的血条位置信息.
            m_arrTowerBloodUIPos = new Vector2[dimensions.x];
            arrTowerBloodUi = new TowerBloodVis[dimensions.x];
            int dy = dimensions.y - 1;
            for (int x = 0; x < dimensions.x; x++)
            {
                m_arrTowerBloodUIPos[x].x = m_arrGridCentUIPos[x, dy].x;
                m_arrTowerBloodUIPos[x].y = m_arrGridCentUIPos[x, dy].y + m_fGridUISize / 10 * 3;
 
                GameObject img = Instantiate(towerBloodUIPrefab);
                GameObject go = GameObject.Find("BattleMainUI");
                if (!go) continue;
                Transform tp = go.GetComponent<Transform>();
                img.GetComponent<Transform>().SetParent(tp, true);
                Vector3 tpos = img.transform.position;
                tpos.x = m_arrTowerBloodUIPos[x].x;
                tpos.y = m_arrTowerBloodUIPos[x].y;
                img.transform.position = tpos;
 
                // 设置为界面最下层:
                img.transform.SetAsFirstSibling();
 
                TowerBloodVis tbv = img.GetComponent<TowerBloodVis>();
                arrTowerBloodUi[x] = tbv;
                tbv.gameObject.SetActive(false);
            }
 
            // 处理攻击塔位对应的血条
            m_arrTowerBulletUIPos = new Vector2[dimensions.x];
            arrTowerBulletUi = new BulletUICtl[dimensions.x];
            arrTowerEnergyUi = new EnergyUICtl[dimensions.x];
            arrTowerEnergyEffect = new ParticleSystem[dimensions.x];
 
            for (int x = 0; x < dimensions.x; x++)
            {
                m_arrTowerBulletUIPos[x].x = m_arrGridCentUIPos[x, dy].x + m_fGridUISize / 2.0f - 10;
                m_arrTowerBulletUIPos[x].y = m_arrGridCentUIPos[x, dy].y;
 
 
                GameObject go = GameObject.Find("BattleMainUI");
                if (!go) continue;
                Transform tp = go.GetComponent<Transform>();
 
                GameObject img;
 
                img = Instantiate(towerBulletUIPrefab);
                img.GetComponent<Transform>().SetParent(tp, true);
                Vector3 tpos = img.transform.position;
                tpos.x = m_arrTowerBulletUIPos[x].x;
                tpos.y = m_arrTowerBulletUIPos[x].y;
                img.transform.position = tpos;
 
                // 设置为界面最下层,并记录相应的数据指针。
                img.transform.SetAsFirstSibling();
                BulletUICtl buc = img.GetComponent<BulletUICtl>();
                arrTowerBulletUi[x] = buc;
                buc.gameObject.SetActive(false);
 
                // 把充能条也创建出来了.
                img = Instantiate(towerEnergyUIPrefab);
                img.GetComponent<Transform>().SetParent(tp, true);
                tpos = img.transform.position;
                tpos.x = m_arrTowerBulletUIPos[x].x;
                tpos.y = m_arrTowerBulletUIPos[x].y;
                img.transform.position = tpos;
 
                img.transform.SetAsFirstSibling();
                EnergyUICtl euc = img.GetComponent<EnergyUICtl>();
                arrTowerEnergyUi[x] = euc;
                euc.gameObject.SetActive(false);
 
                // 设置播放特效对应的3D坐标:
                Vector3 vpos = GridToWorld(new IntVector2(x, dy), new IntVector2(2, 1));
                vpos.x -= (gridSize / 2.0f);
                vpos.y += 5.0f;
 
                arrTowerEnergyEffect[x] = Instantiate(energyEffectPrefab);
                arrTowerEnergyEffect[x].transform.position = vpos;
                arrTowerEnergyEffect[x].Stop();
            }
 
            return;
        }
 
        /// <summary>
        /// 在指定的位置播放充能成功的特效.
        /// </summary>
        /// <param name="x"></param>
        /// <param name="play">是播放还是停止播放</param>
        public void PlayEnergyEffect(int x, bool play = true)
        {
            if (!arrTowerEnergyEffect[x]) return;
            if (play)
            {
                arrTowerEnergyEffect[x].Play();
            }
            else
            {
                arrTowerEnergyEffect[x].Stop();
            }
            return;
        }
 
 
        public void updateGridOpenCoin(int ix, int iy)
        {
            // 更新显示相关的信息, 
            if (opponent)
                GRID_OPENCASH_OPPO += GRID_OPENCASH_OPPO;
            else
                GRID_OPENCASH_SELF += GRID_OPENCASH_SELF;
 
            for (int x = 0; x < dimensions.x; x++)
            {
                if (x == ix)
                {
                    m_arrTGO[x] = null;
                }
                else
                {
                    if (m_arrGridType[x, iy] != PlacementGridType.EGridWaitBuy)
                        continue;
                    if (m_arrTGO[x] != null)
                    {
                        if (opponent)
                            m_arrTGO[x].cashText.SetText(GRID_OPENCASH_OPPO.ToString());
                        else
                            m_arrTGO[x].cashText.SetText(GRID_OPENCASH_SELF.ToString());
                    }
                }
            }
        }
 
        /// <summary>
        /// 是否有已开启的可放置攻击位置。
        /// </summary>
        /// <returns></returns>
        public bool hasFreeAttackPos()
        {
            int iy = dimensions.y - 1;
            for (int ix = 0; ix < dimensions.x; ix++)
            {
                if (m_arrGridType[ix, iy] == PlacementGridType.EGridOpen)
                    return true;
            }
            return false;
        }
 
        /// <summary>
        /// 购买塔位.
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public void BuyTowerGrid(int ix, int iy)
        {
            // 更新核心的数据信息
            if (m_arrGridType[ix, iy] != PlacementGridType.EGridWaitBuy) return;
            m_arrGridType[ix, iy] = PlacementGridType.EGridOpen;
            m_AvailableCells[ix, iy] = false;
 
            /*            // 更新显示相关的信息, 
                        if (opponent)
                            GRID_OPENCASH_OPPO += GRID_OPENCASH_OPPO;
                        else
                            GRID_OPENCASH_SELF += GRID_OPENCASH_SELF;*/
 
            m_Tiles[ix, iy].SetTileType(PlacementGridType.EGridOpen);
            // 开启金币获取模式.
            m_arrCoinGenTime[ix] = 0.0f;
 
        }
 
 
        /// <summary>
        /// 购买对应的待购攻击塔位.
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public bool buyWaitBuyGrid(int x, int y)
        {
            TowerGridOpen tgo = m_arrTGO[x];
            if (tgo)
                tgo.OnClick();
            else
                return false;
            return true;
        }
 
        /// <summary>
        /// 预计算每一个塔位格子的屏幕坐标。
        /// </summary>
        void Start()
        {
            // 初始化塔位类型.
            initTileGridType();
 
            // Precalculate inverted grid size, to save a division every time we translate coords
            m_InvGridSize = 1 / gridSize;
 
            SetUpGrid();
 
 
            // 初始化格子对应的屏幕坐标数据
            preCalculateGridUIPos();
 
            // TEST CODE TO DELETE:
            if (TestParticle != null)
                PlayParticle = Instantiate(TestParticle);
            effectStopTimer = new Timer(1.0f, stopParticle);
            bTimerStart = false;
        }
 
        protected void stopParticle()
        {
            if (PlayParticle)
                PlayParticle.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
            //if (fireParticleSystem)
            //fireParticleSystem.gameObject.SetActive(false);
            //fireParticleSystem.Stop(true,ParticleSystemStopBehavior.StopEmittingAndClear );
            //fireParticleSystem.Clear();
            //Vector3 vpos = fireParticleSystem.gameObject.transform.position;
            //vpos.y = 3000;
            //fireParticleSystem.gameObject.transform.position = vpos;
        }
        /// <summary>
        /// 初始化当前塔防位的类型信息.
        /// </summary>
        void initTileGridType()
        {
            m_arrGridType = new PlacementGridType[dimensions.x, dimensions.y];
            int sy = dimensions.y - 1;
            for (int tx = 0; tx < dimensions.x; tx++)
            {
                m_arrGridType[tx, sy] = PlacementGridType.EGridWaitBuy;
                if ((tx * 2 + 1) == dimensions.x)
                    m_arrGridType[tx, sy] = PlacementGridType.EGridOpen;
            }
        }
 
        /// <summary>
        /// Set collider's size and center
        /// </summary>
        void ResizeCollider()
        {
            var myCollider = GetComponent<BoxCollider>();
            Vector3 size = new Vector3(dimensions.x, 0, dimensions.y) * gridSize;
            myCollider.size = size;
 
            // Collider origin is our bottom-left corner
            myCollider.center = size * 0.5f;
        }
 
        /// <summary>
        /// Instantiates Tile Objects to visualise the grid and sets up the <see cref="m_AvailableCells" />
        /// </summary>
        protected void SetUpGrid()
        {
            PlacementTile tileToUse;
#if UNITY_STANDALONE
            tileToUse = placementTilePrefab;
#else
            tileToUse = placementTilePrefabMobile;
#endif
 
            if (tileToUse != null)
            {
                // Create a container that will hold the cells.
                var tilesParent = new GameObject("Container");
                tilesParent.transform.parent = transform;
                tilesParent.transform.localPosition = Vector3.zero;
                tilesParent.transform.localRotation = Quaternion.identity;
                m_Tiles = new PlacementTile[dimensions.x, dimensions.y];
 
                for (int y = dimensions.y - 1; y < dimensions.y; y++)
                {
                    for (int x = 0; x < dimensions.x; x++)
                    {
                        Vector3 targetPos = GridToWorld(new IntVector2(x, y), new IntVector2(1, 1));
                        targetPos.z -= 1.0f;
                        PlacementTile newTile = Instantiate(tileToUse);
                        newTile.transform.parent = tilesParent.transform;
                        newTile.transform.position = targetPos;
                        newTile.transform.localRotation = Quaternion.identity;
 
                        m_Tiles[x, y] = newTile;
                        newTile.SetTileType(m_arrGridType[x, y]);
                    }
                }
            }
        }
 
#if UNITY_EDITOR
        /// <summary>
        /// On editor/inspector validation, make sure we size our collider correctly.
        /// Also make sure the collider component is hidden so nobody can mess with its settings to ensure its integrity.
        /// Also communicates the idea that the user should not need to modify those values ever.
        /// </summary>
        void OnValidate()
        {
            // Validate grid size
            if (gridSize <= 0)
            {
                Debug.LogError("Negative or zero grid size is invalid");
                gridSize = 1;
            }
 
            // Validate dimensions
            if (dimensions.x <= 0 ||
                dimensions.y <= 0)
            {
                Debug.LogError("Negative or zero grid dimensions are invalid");
                dimensions = new IntVector2(Mathf.Max(dimensions.x, 1), Mathf.Max(dimensions.y, 1));
            }
 
            // Ensure collider is the correct size
            ResizeCollider();
 
            GetComponent<BoxCollider>().hideFlags = HideFlags.HideInInspector;
        }
 
        /// <summary>
        /// Draw the grid in the scene view
        /// </summary>
        void OnDrawGizmos()
        {
            Color prevCol = Gizmos.color;
            Gizmos.color = Color.yellow;
 
            Matrix4x4 originalMatrix = Gizmos.matrix;
            Gizmos.matrix = transform.localToWorldMatrix;
 
            // Draw local space flattened cubes
            for (int y = 0; y < dimensions.y; y++)
            {
                float freePos = 0;
                if ((y > 0) && (y == dimensions.y - 1))
                    freePos = gridFreePos;
 
                for (int x = 0; x < dimensions.x; x++)
                {
                    var position = new Vector3((x + 0.5f) * gridSize, 0, (y + 0.5f) * gridSize + freePos);
                    Gizmos.DrawWireCube(position, new Vector3(gridSize, 0, gridSize));
                }
            }
 
            Gizmos.matrix = originalMatrix;
            Gizmos.color = prevCol;
 
            // Draw icon too, in center of position
            Vector3 center = transform.TransformPoint(new Vector3(gridSize * dimensions.x * 0.5f,
                                                                  1,
                                                                  gridSize * dimensions.y * 0.5f));
            Gizmos.DrawIcon(center, "build_zone.png", true);
        }
#endif
    }
}