Spring774
2025-10-30 4d84b498fbb08b9f177b5d9a39e2fedd0522f16f
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
import Ball from "./Ball";
import BallRaycast from "./BallRaycast";
import Brick from "./Brick";
import Game from "./Game";
import Global, { PROP_TYPE } from "./Global";
import { PoolManager, PoolType } from "./PoolManager";
import Prop from "./Prop";
import SoundManager from "./SoundManager";
import Userdata from "./Userdata";
 
const { ccclass, property } = cc._decorator;
 
@ccclass
export default class Playground extends cc.Component {
    private static readonly MIN_DEGREE = 7;
    private static readonly MAX_DEGREE = 173;
    private static readonly WIDHT = 690;
    public static instance: Playground = null;
 
    @property(BallRaycast)
    ballAimLine: BallRaycast = null;
 
    @property(cc.Node)
    ballMarkNode: cc.Node = null;
 
    @property(cc.Node)
    bricksRootNode: cc.Node = null;
    @property(cc.Node)
    ballsRootNode: cc.Node = null;
    @property(cc.Node)
    propsRootNode: cc.Node = null;
 
    @property(cc.Node)
    fingerNode: cc.Node = null;
 
    @property(cc.Node)
    boardNode: cc.Node = null;
 
    @property(cc.Node)
    wallNode: cc.Node = null;
 
    @property(sp.Skeleton)
    startSkeleton: sp.Skeleton = null;
 
    @property(cc.Node)
    buttonShootNode: cc.Node = null;
 
    @property(cc.Node)
    buttonTimesNode: cc.Node = null;
 
    @property(cc.Node)
    buttonWallNode: cc.Node = null;
 
    private touchId = -1;
    private isFired = false;
    private startTouch: cc.Vec2;
    private _zeroAngleVec = cc.v2(1, 0).normalizeSelf();
    private fireDirection: cc.Vec2;
    private ballSpriteFrame: cc.SpriteFrame = null;
 
    private currBalls: Ball[] = [];
    private breakableBricks: Brick[] = [];
    private obstacleBricks: Brick[] = [];
    private boardStartPos: cc.Vec2;
    private boardMoveWidth = 0;
    private recycleBrickCounter = 0;
    private createPropTimes = 0;
 
    onLoad() {
        Playground.instance = this;
 
        this.boardMoveWidth = (Playground.WIDHT) * 0.5;// - this.boardNode.width;
 
        this.openPhysics();
 
        // 使用枚举类型来注册
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }
 
    onEnable() {
        this.loadSkin();
        this.loadLevel(Userdata.SelectLevel);
    }
 
    resetLevel() {
        cc.director.getPhysicsManager().enabled = true;
        this.isFired = false;
        this.recycleBrickCounter = 0;
        this.createPropTimes = 0;
 
        this.ballMarkNode.active = true;
        this.ballAimLine.node.active = false;
        this.boardNode.position = cc.v2(0, this.boardNode.position.y);
 
        this.wallNode.active = false;
 
        this.clearBricks();
        this.clearBalls();
        this.clearProps();
    }
 
    loadLevel(levelNum: number, cb?: Function) {
        this.resetLevel();
 
        let loadNum = levelNum > 1161 ? (((levelNum - 1161) % 1000) + 150) : levelNum;
        cc.loader.loadRes('d/' + loadNum, (err, data) => {
            if (data && data.json) {
                cc.log('data = ', data.json);
 
                this.createLevel(data.json.data, cb);
            }
        });
    }
 
    private createLevel(data, cb?: Function) {
        this.bricksRootNode.removeAllChildren();
        Game.instance.updateLevelNum();
 
        let width = Math.max(data[0], data[1]);
        let brickOriginWidth = Playground.WIDHT / width;
        let brickWidth = brickOriginWidth * 0.76;
        let brickPhysicWidth = brickOriginWidth * 0.76;
 
        let startPos = cc.v2((1 - width) * 0.5 * brickOriginWidth, (1 - width) * 0.5 * brickOriginWidth);
 
        //bricks config
        for (let i = 2, len = data.length; i < len; i += 4) {
            let x = data[i];
            let y = data[i + 1];
            let isObstacle = data[i + 2];
            let colorValue = data[i + 3];
 
            let _brick = this.createBrick();
            _brick.init(isObstacle, isObstacle ? cc.color().fromHEX('#828282') : cc.color(colorValue.toString(16))
                , brickWidth, isObstacle ? brickPhysicWidth : brickPhysicWidth);
            _brick.node.position = startPos.add(cc.v2(x * brickOriginWidth, y * brickOriginWidth));
 
            if (!isObstacle) {
                this.breakableBricks.push(_brick);
            } else {
                this.obstacleBricks.push(_brick);
            }
        }
 
        cb && cb();
        this.onLevelLoaded();
    }
 
    onLevelLoaded() {
        let loading = cc.find('Loading');
        if (loading) {
            cc.game.removePersistRootNode(loading);
            loading.destroy();
        }
 
        cc.log('total bricks -> ' + this.breakableBricks.length);
        this.recycleBrickCounter = 0;
        this.createPropTimes = 0;
        this.showFingerAnimation();
 
        SoundManager.playStartAudio();
 
        this.startSkeleton.setAnimation(0, 'animation', false);
    }
 
 
    loadSkin() {
        //加载图片皮肤,并设置尺寸
        cc.loader.loadRes('skins/skin_' + Userdata.CurrSkin, cc.SpriteFrame, (err, res) => {
            this.ballSpriteFrame = res;
            this.ballMarkNode.getComponent(cc.Sprite).spriteFrame = res;
        });
    }
 
    //物理设置
    openPhysics() {
        cc.director.getPhysicsManager().enabled = true;
        cc.director.getPhysicsManager().gravity = cc.v2(0, 0);//-8000);
 
        console.log('os = ', cc.sys.os);
        if (cc.sys.os == cc.sys.OS_IOS) {
 
            var manager = cc.director.getPhysicsManager();
            // 开启物理步长的设置
            manager.enabledAccumulator = true;
 
            // manager.PTM_RATIO = 6;
 
            // manager.MAX_ACCUMULATOR = 
 
            // 物理步长,默认 FIXED_TIME_STEP 是 1/60
            manager.FIXED_TIME_STEP = 1 / 3;
 
            // 每次更新物理系统处理速度的迭代次数,默认为 10
            manager.VELOCITY_ITERATIONS = 5;
 
            // 每次更新物理系统处理位置的迭代次数,默认为 10
            manager.POSITION_ITERATIONS = 5;
        }
 
        if (Global.DEBUG) {
            console.log('physics in debug mode.');
            cc.director.getPhysicsManager().debugDrawFlags =
                // cc.PhysicsManager.DrawBits.e_aabbBit |
                //cc.PhysicsManager.DrawBits.e_pairBit |
                //cc.PhysicsManager.DrawBits.e_jointBit |
                cc.PhysicsManager.DrawBits.e_shapeBit
                ;
        } else {
            console.log('physics not in debug.');
            cc.director.getPhysicsManager().debugDrawFlags = 0;
        }
    }
 
 
    onTouchStart(event: cc.Event.EventTouch) {
        this.touchId = event.getID();
        if (this.isFired) {//木板左右移动
            this.boardStartPos = this.boardNode.position;
        } else {//显示发射线
            this.startAim();
            this.onTouchMove(event);
        }
    }
 
    onTouchMove(event: cc.Event.EventTouch) {
        if (this.isFired) {
            let x = this.boardStartPos.x + event.getLocationX() - event.getStartLocation().x;
            if (x < -this.boardMoveWidth) {
                x = -this.boardMoveWidth;
            } else if (x > this.boardMoveWidth) {
                x = this.boardMoveWidth;
            }
 
            this.boardNode.position = cc.v2(x, this.boardStartPos.y);
        } else {//draw line to aim
            if (this.touchId != event.getID()) {
                return;
            }
 
            let currTouch = event.touch.getLocation();
            if (currTouch.y < this.startTouch.y) {
                currTouch.y = this.startTouch.y + (this.startTouch.y - currTouch.y);
            }
 
            let direction = cc.v2(currTouch.x - this.startTouch.x, currTouch.y - this.startTouch.y).normalizeSelf();
 
            let _angle = direction.angle(this._zeroAngleVec);
            let _degree = cc.misc.radiansToDegrees(_angle);
            if (_degree < Playground.MIN_DEGREE || _degree > Playground.MAX_DEGREE) {
                _angle = cc.misc.degreesToRadians(_degree < Playground.MIN_DEGREE ? Playground.MIN_DEGREE : Playground.MAX_DEGREE);
                direction = cc.v2(Math.cos(_angle), Math.sin(_angle)).normalize();
            }
 
            this.aim(direction);
        }
    }
 
 
    onTouchEnd(event: cc.Event.EventTouch) {
        if (this.isFired) {
 
        } else {
            this.tryFire();
        }
    }
 
    onTouchCancel(event: cc.Event.EventTouch) {
        this.cancelAim();
    }
 
    showFingerAnimation() {
        this.fingerNode.active = true;
        this.fingerNode.stopAllActions();
        this.fingerNode.position = cc.v2(-200, -50);
        this.fingerNode.scale = 1.2;
        this.fingerNode.runAction(
            cc.repeatForever(
                cc.sequence(
                    cc.scaleTo(0.3, 0.8),
                    cc.moveBy(1, cc.v2(450, 0)),
                    cc.moveBy(1, cc.v2(-450, 0)),
                    cc.scaleTo(0.5, 1.2)
                )
            )
        );
    }
 
    startAim() {
        // Game.instance.fingerNode.active = false;
        this.startTouch = this.ballMarkNode.convertToWorldSpaceAR(cc.v2());
        cc.log("ballMarkNode start = " + this.ballMarkNode.position.x + ", " + this.ballMarkNode.position.y);
 
        if (!this.isFired) {
            this.fingerNode.active = false;
        }
    }
 
    aim(direction: cc.Vec2) {
        this.fireDirection = direction;
 
        this.ballAimLine.node.active = true;
        this.ballAimLine.startRaycast(this.startTouch, this.fireDirection, 13);
    }
 
    cancelAim() {
        if (!this.isFired) {
            this.ballAimLine.node.active = false;
            this.showFingerAnimation();
        }
    }
 
    tryFire() {
        if (this.isFired)
            return;
 
        if (this.ballAimLine.node.active) {//Fire
            this.isFired = true;
            this.ballMarkNode.active = false;
            this.ballAimLine.node.active = false;
 
            let worldPos = this.ballMarkNode.convertToWorldSpaceAR(cc.Vec2.ZERO);
            let pos = this.node.convertToNodeSpaceAR(worldPos);
            this.fireBall(pos, this.fireDirection);
 
            Game.instance.IsStartGame = true;
        }
    }
 
    createBall(): Ball {
        let _ball = PoolManager.Ins.get(PoolType.BALL, this);
 
        _ball.parent = this.ballsRootNode;
        _ball.active = true;
 
        let ball = _ball.getComponent(Ball);
        ball.updateSkin(this.ballSpriteFrame);
 
        return ball;
    }
 
    createBrick(): Brick {
        let _brick = PoolManager.Ins.get(PoolType.BRICK, this);
 
        _brick.parent = this.bricksRootNode;
        _brick.active = true;
 
        return _brick.getComponent(Brick);
    }
 
    createProp(propType: PROP_TYPE): Prop {
        let _node: cc.Node = null;
 
        if (propType == PROP_TYPE.SHOOT3) {
            _node = PoolManager.Ins.get(PoolType.PROP_SHOOT, this);
        } else if (propType == PROP_TYPE.TIMES3) {
            _node = PoolManager.Ins.get(PoolType.PROP_TIMES, this);
        } else if (propType == PROP_TYPE.WALL) {
            _node = PoolManager.Ins.get(PoolType.PROP_WALL, this);
        }
 
        _node.parent = this.propsRootNode;
        _node.active = true;
 
        let prop = _node.getComponent(Prop);
        return prop;
    }
 
    pickupProp(propType: number) {
        cc.log('pickup proptype = ' + propType);
        SoundManager.playProp();
        if (propType == PROP_TYPE.SHOOT3) {
            let worldPos = this.ballMarkNode.convertToWorldSpaceAR(cc.Vec2.ZERO);
            let pos = this.node.convertToNodeSpaceAR(worldPos);
            let leftDir = cc.v2(-1, 1).normalizeSelf();
            this.fireBall(pos, leftDir);
            let topDir = cc.v2(0, 1).normalizeSelf();
            this.fireBall(pos, topDir);
            let rightDir = cc.v2(1, 1).normalizeSelf();
            this.fireBall(pos, rightDir);
        } else if (propType == PROP_TYPE.TIMES3) {
            let len = this.currBalls.length;
            let maxBall = cc.sys.os == cc.sys.OS_IOS ? Global.MAX_BALLS * 0.25 : Global.MAX_BALLS;
            for (let i = 0; i < len; ++i) {
                if (this.currBalls.length > maxBall) {
                    // cc.error('too many balls.');
                    break;
                }
                let ball = this.currBalls[i];
                let leftDir = cc.v2(Math.random() * 2 - 1, Math.random() * 2 - 1).normalizeSelf();
                this.fireBall(ball.node.position, leftDir);
                this.scheduleOnce(()=>{
                    let topDir = cc.v2(Math.random() * 2 - 1, Math.random() * 2 - 1).normalizeSelf();
                    this.fireBall(ball.node.position, topDir);
                }, 0);
                this.scheduleOnce(()=>{
                    let rightDir = cc.v2(Math.random() * 2 - 1, Math.random() * 2 - 1).normalizeSelf();
                    this.fireBall(ball.node.position, rightDir);
                }, 0.016);
            }
        } else if (propType == PROP_TYPE.WALL) {
            this.wallNode.stopAllActions();
            this.wallNode.active = true;
            this.wallNode.opacity = 255;
            this.wallNode.runAction(
                cc.sequence(
                    cc.delayTime(Global.WALL_TIME),
                    cc.blink(1, 3),
                    cc.callFunc(
                        () => {
                            this.wallNode.active = false;
                        }
                    )
                )
            )
        }
    }
 
    recycleProp(prop: Prop) {
        if (prop.propType == PROP_TYPE.SHOOT3) {
            PoolManager.Ins.put(PoolType.PROP_SHOOT, prop.node);
        } else if (prop.propType == PROP_TYPE.TIMES3) {
            PoolManager.Ins.put(PoolType.PROP_TIMES, prop.node);
        } else if (prop.propType == PROP_TYPE.WALL) {
            PoolManager.Ins.put(PoolType.PROP_WALL, prop.node);
        }
    }
 
    fireBall(pos: cc.Vec2, direction: cc.Vec2) {
        let ball = this.createBall();
        ball.node.position = pos;
        ball.fire(direction);
 
        this.currBalls.push(ball);
    }
 
    recycleBall(ball: Ball) {
        PoolManager.Ins.put(PoolType.BALL, ball.node);
        let idx = this.currBalls.indexOf(ball);
        if (idx != -1) {
            this.currBalls.splice(idx, 1);
            cc.log('recycle a ball.');
            if (this.currBalls.length == 0) {
                cc.log('Game over.');
                Game.instance.gameover();
            }
        }
    }
 
    clearProps() {
        let count = this.propsRootNode.childrenCount;
        for (let i = count - 1; i >= 0; --i) {
            let _node = this.propsRootNode.children[i];
            this.recycleProp(_node.getComponent(Prop));
        }
    }
 
    clearBalls() {
        let count = this.ballsRootNode.childrenCount;
        for (let i = count - 1; i >= 0; --i) {
            let _node = this.ballsRootNode.children[i];
            PoolManager.Ins.put(PoolType.BALL, _node);
        }
 
        this.currBalls = [];
    }
 
    clearBricks() {
        let count = this.bricksRootNode.childrenCount;
        for (let i = count - 1; i >= 0; --i) {
            let _node = this.bricksRootNode.children[i];
            PoolManager.Ins.put(PoolType.BRICK, _node);
        }
 
        this.obstacleBricks = [];
        this.breakableBricks = [];
    }
 
    recycleBrick(brick: Brick, isClear = false) {
        let worldPos = brick.node.convertToWorldSpaceAR(cc.Vec2.ZERO);
        PoolManager.Ins.put(PoolType.BRICK, brick.node);
        let idx = this.breakableBricks.indexOf(brick);
        if (idx != -1) {
            this.breakableBricks.splice(idx, 1);
            cc.log('recycle a brick.')
 
            if (isClear) {
                return;
            }
 
            if (this.breakableBricks.length == 0) {//win
                cc.log('You win.');
                Game.instance.showResultLayer(true);
                return;
            }
 
            this.recycleBrickCounter++;
            if (this.recycleBrickCounter == Global.getPropDropCount(this.createPropTimes, Userdata.SelectLevel)) {
                cc.log('recycleBrickCounter: ' + this.recycleBrickCounter + ' , prop drops: ' + this.createPropTimes);
                this.recycleBrickCounter = 0;
                this.createPropTimes++;
                this.generateProp(worldPos);//生成一个道具
            }
        }
    }
 
    generateProp(worldPos: cc.Vec2) {
        let propType = Global.getNextPropType(Userdata.SelectLevel);
 
        let prop = this.createProp(propType);
        prop.node.position = this.propsRootNode.convertToNodeSpaceAR(worldPos);
    }
 
    resetButtonTip() {
        this.buttonShootNode.angle = 0;
        this.buttonShootNode.stopAllActions();
        this.buttonTimesNode.angle = 0;
        this.buttonTimesNode.stopAllActions();
        this.buttonWallNode.angle = 0;
        this.buttonWallNode.stopAllActions();
    }
 
    showButtonTipActions() {
        this.runTipUseTimeAction(this.buttonShootNode);
        this.runTipUseTimeAction(this.buttonTimesNode);
        this.runTipUseTimeAction(this.buttonWallNode);
    }
 
    private runTipUseTimeAction(node: cc.Node) {
        if (node.active) {
            node.stopAllActions();
            node.runAction(
                cc.repeatForever(
                    cc.sequence(
                        // cc.scaleTo(0.5, 0.9),
                        // cc.scaleTo(0.5, 1)
                        cc.rotateTo(0.1, -5),
                        cc.rotateTo(0.1, 5),
                        cc.rotateTo(0.1, 0)
                    )
                )
            );
        }
    }
 
}