Форум программистов, компьютерный форум, киберфорум
JavaScript: HTML5 Canvas
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.81/21: Рейтинг темы: голосов - 21, средняя оценка - 4.81
403 / 19 / 5
Регистрация: 17.01.2017
Сообщений: 572

Как сделать столкновение объектов?

24.03.2024, 21:02. Показов 6352. Ответов 70
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте мне нужно сделать столкновение объектов через функцию. Вот пример варианта, что нужно получить.
Название: GameCollision.gif
Просмотров: 615

Размер: 63.7 Кб
Я для этого специально написала функцию hitTest. Выше пример это обычный вариант где сравниваются по оси координат столкновения граней.

Через hitTest у меня фиксируется только столкновение когда объект находиться внутри. Пример на gif-анимации.
Название: GameHitTest.gif
Просмотров: 618

Размер: 88.7 Кб

Как проверять грани и запускать hitTest?

В прошлый раз мне не ответили поэтому я код изменила и сделала более легкую версию.

Здесь используются функции

- Transform
- setTransform. Все это важно для проверки столкновения.

Вот код, чтобы протестировать достаточно скопировать, сохранить в html файл и загрузить в браузере. Никакие библиотеки дополнительно подключать не нужно.
PHP/HTML
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
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Пример hitTest </title>
<script>
window.onload = function()
{
var canvas = document.getElementById("drawingCanvas");
var context = canvas.getContext("2d");
 
var BB=canvas.getBoundingClientRect();
var offsetX=BB.left;
var offsetY=BB.top;
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
 
var dragok = false;
var startX;
var startY;
var _activeInstructions = [];
 
var shapeW = 50, hitW = 100;
 
 
 
   localToLocal = function(hit1,x, y, target, pt) {
        var tx1,ty1,pt1;
        tx1 = 1*hit1.x+0*hit1.y+0;
        ty1 = 0*hit1.x+1*hit1.y+0;
 
        
        pt1 = {};
        pt1.x = x*1+y*0+tx1;
        pt1.y = x*0+y*1+ty1;
        
      
     
        return globalToLocal(target,pt1.x, pt1.y, pt);
    };
 
 
 
 
 
globalToLocal = function(hit1,x, y, pt) {
  
      
      var mtx1 = {a:1,b:0,c:0,d:1,tx:-150,ty:-150};
      
     
      var pt1 = {};
      pt1.x = x*1+y*0+mtx1.tx;
      pt1.y = x*0+y*1+mtx1.ty;
      
      
      return pt1;
       
}
 
 
 
Shape = function(x,y,w,h,color,color1,lineWidth1)
{
   
    this.x1 = x;
    this.y1 = y;
    this.w = w;
    this.h = h;
    this.color = color;
    this.color1 = color1;
    this.lineWidth = lineWidth1;
    this.exec = function(ctx)
    {
      ctx.lineWidth =  this.lineWidth;
      ctx.beginPath(); 
     
      
      ctx.rect(this.x1, this.y1, this.w, this.h);
      ctx.fillStyle = this.color;
      ctx.fill();
      
     
      ctx.strokeStyle = this.color1;
      ctx.stroke();
        
    }
    
   this.hitTest = function(ctx, x, y) {
     
      ctx.setTransform(1, 0, 0, 1, -x, -y);
      this.exec(ctx);
      
      var hit = this._testHit(ctx);
      
       
      ctx.setTransform(1, 0, 0, 1, 0, 0);
      ctx.clearRect(0, 0, 2, 2);
      return hit;
      
    };
   this.set = function(props) {
        
        for (var n in props) { 
        this[n] = props[n]; 
        }
        return this;
    };
    
  this._testHit = function(ctx) {
        try {
          
            var hit = ctx.getImageData(0, 0, 1, 1).data[3] > 1;
            
        } catch (e) {
            
        }
        
        return hit;
    };
    
    
 
    this.updateContext = function(ctx) {
        var o = this;
          var a1 = 1;
          var b1 = 0;
          var c1 = 0;
          var d1 = 1;
          
          var tx1 = a1*o.x+c1*o.y+0;
          var ty1 = b1*o.x+d1*o.y+0;
          
          var mtx = {a:1,b:0,c:0,d:1,tx:tx1,ty:ty1};
        
        var tx = mtx.tx,
            ty = mtx.ty;
       
        
        ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, tx, ty);
     
    }
}
 
Rectangle = function(x,y,w,h,color)
{
  this.x1 = x;
  this.y1 = y;
  this.w = w;
  this.h = h;
  this.color = color;
  this.exec = function(ctx)
  {
  
    ctx.beginPath(); 
    ctx.rect(0, 0, this.w, this.h);
    ctx.fillStyle = "#906";
    ctx.fill();
   
  }
  this.set = function(props) {
      
        for (var n in props) { this[n] = props[n]; }
        return this;
  };
  
  
  
  
  this.updateContext = function(ctx) {
        var o = this;
 
       
        
        
        var a1 = 1;
          var b1 = 0;
          var c1 = 0;
          var d1 = 1;
          
          var tx1 = a1*o.x+c1*o.y+0;
          var ty1 = b1*o.x+d1*o.y+0;
          
           
       var mtx = {a:1,b:0,c:0,d:1,tx:tx1,ty:ty1};
       var tx = mtx.tx,
            ty = mtx.ty;
        ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, tx, ty);
        ctx.globalAlpha *= 1;
    }
} 
 
 
 
function clear() {
  context.clearRect(0, 0, WIDTH, HEIGHT);
}
 
 
 
 
   setInterval(() => {
              (
                function() {
                  clear();
                  draw();
                }).call(this);
   }, 33);
var shape1,rect1; 
 
 
function init() {
  clear();
  
  shape1 = new Shape(0,0,hitW,hitW,"#ddd","blue",1);
  shape1.set({x:150, y:150});
  
  
 
  
  rect1 = new Rectangle(0,0,50,50,"#906");
  rect1.set({x:10, y:170});
  
   
   
   
 canvas.addEventListener("mousedown", (e) => {
      e.preventDefault();
      e.stopPropagation();
      
      var mx=parseInt(e.clientX-offsetX);
      var my=parseInt(e.clientY-offsetY);
      dragok=false;
      
      
      if(mx>rect1.x && mx<rect1.x+rect1.w && my>rect1.y && my<rect1.y+rect1.h){
          
         
          dragok=true;
          
     }
      
      
       startX=mx;
       startY=my;
      
      
  });
  canvas.addEventListener("mouseup", (e) => {
     e.preventDefault();
     e.stopPropagation();
 
 
     dragok = false;
      
  });
  
  canvas.addEventListener("mousemove", (e) => {
     
   if (dragok){
       e.preventDefault();
      e.stopPropagation();
 
    
      var mx=parseInt(e.clientX-offsetX);
      var my=parseInt(e.clientY-offsetY);
 
     
      var dx=mx-startX;
      var dy=my-startY;
      
     
      
      
      rect1.x+=dx;
      rect1.y+=dy;
      
      
       var pt = localToLocal(rect1,rect1.x-shape1.x,rect1.y-shape1.y,shape1);
                  if (shape1.hitTest(context,pt.x, pt.y)) {
                      shape1.color1 = "green";
                      shape1.lineWidth = 7;
                    } else {
                      shape1.color1 = "blue";
                      shape1.lineWidth = 1;
                   }
      startX=mx;
      startY=my;
      
      
    }
     
      
  });
   
   
  
 draw();
  
 
}
function draw()
{
  context.save();
  shape1.updateContext(context);
  shape1.exec(context);
  context.restore();
  
  context.save();
  rect1.updateContext(context);
  rect1.exec(context);
  context.restore();
}
init();
}
</script>
</head>
<body>
 
<canvas id="drawingCanvas" width="500" height="500"></canvas>
</body>
</html>
0
Лучшие ответы (1)
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
24.03.2024, 21:02
Ответы с готовыми решениями:

Непростое столкновение объектов на Canvas
Здравствуйте, уважаемые форумчане. Познаю работу с canvas. Нужно написать скрипт, реализующий перемещение круга мышкой из А в Б,...

Как определить столкновение объектов
Как сделать столкновение объектов. Когда зеленый объект прикасается слева или справа красный объект или когда верхняя часть зеленого...

Столкновение объектов
Есть проблемка, запутался ,помогите,пожалуйста.Не реагирует на столкновение,заранее большое спасибо &lt;html&gt; ...

70
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
15.04.2024, 15:16
Студворк — интернет-сервис помощи студентам
Для начала, надо как-то добавить прямоугольники (статические платформы) в статическую группу. У вас есть такой код:

JavaScript
1
2
3
4
5
create() {
    this.footer2 = this.add.rectangle(361, 348, 721.35, 48.4, 0xcccccc);
    this.footer2.setStrokeStyle(1, 0xff0000);
    // ...
}
Этот код создаёт большую платформу. Эту платформу надо добавить в статичекую группа, как это сделано в туториале Making your first Phaser 3 Game

JavaScript
1
2
3
4
5
6
7
8
function create() {
    this.add.image(400, 300, "sky");
    
    platforms = this.physics.add.staticGroup();
    platforms.create(400, 568, "ground").setScale(2).refreshBody();
    platforms.create(600, 400, "ground");
    platforms.create(50, 250, "ground");
    platforms.create(750, 220, "ground");
Здесь статические платформы создаются в физическом мире на основе спрайтов. Я не нашёл, как создать статические платформы на основе прямоугольников. Я задал вопрос на официальном форуме Phaser. Может быть ответят.

Цитата Сообщение от Telinc1;
My recommendation, however, would be to use one of the shape objects - such as a line or a rectangle . They’re more efficient than Graphics objects and you don’t need workarounds to add physics to them.
I try to add a rectangle to a static group. How to make it?

JavaScript
1
2
3
4
5
6
7
function create() {
    const ground = this.add.rectangle(361, 348, 721.35, 48.4, 0xcccccc);
    ground.setStrokeStyle(1, 0xff0000);
 
    platforms = this.physics.add.staticGroup();
    // How to add a ground to a static Group?
}
0
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
15.04.2024, 15:22
Интересный у вас пример:



Миниатюры
0
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
15.04.2024, 16:53
Следующим образом можно сделать статическую платформу из прямоугольника:

JavaScript
1
2
3
4
5
6
7
function create() {
    const ground = this.add.rectangle(361, 348, 721.35, 48.4, 0xcccccc);
    ground.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(ground);
    ground.body.immovable = true;
    ground.body.allowGravity = false;
}
0
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
15.04.2024, 20:29
Перенёс в песочницу все 10 примеров из уроков туториала по платформеру: Making your first Phaser 3 game

Примеры залил на GitHub и добавил в README.md инструкцию по сборке примеров на Rollup.



Миниатюры
Вложения
Тип файла: zip making-your-first-game-rollup-phaser3-js-main.zip (155.2 Кб, 5 просмотров)
0
403 / 19 / 5
Регистрация: 17.01.2017
Сообщений: 572
16.04.2024, 21:18  [ТС]
8Observer8, я все равно не понимаю как это сделать столкновение на Phaser, зато я хорошо разбираюсь в библиотеке EaselJS. Это библиотека как и Phaser разработана для создания игр. Только более легковесная. Вообщем на EaselJS я сделала свой пример.

В EaselJS есть функция hitTest для столкновения объектов только я непоняла как ей пользоваться и написала свою функцию. Назвала hitTestPoint – так же как на Flash.

Пример кода.
PHP/HTML
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
<!DOCTYPE html>
<html>
<head>
    <title>EaselJS demo: AI</title>
  
  <script src="./easeljs.js"></script>
    <script>
        var stage, holder,footer2,box1,box2,box3,box4,box5,platform1,platform2,platform3,platform4,guy2;
        
        
        var arr1 = [];
        var computer = 1;
        var shieldnum = 0;
        var shieldavailable = 0;
        var shieldtimer = 0;
        var shieldtime = 1000;
        var reloadtime = 50;
        var reloadtimer = 0;
        var reloadtimer2 = 0;
        var shotsleft = 5;
        var shotsleft2 = 5;
        var gotshield = 0;
        var gotshield2 = 0;
        var xspeed = 0;
        var yspeed = -15;
        var grav = 1;
        var startposx = 802;
        var startposy = 12;
        var startposx2 = 0;
        var startposy2 = 300;
 
        var guyheight = 10;
        var guywidth = 5;
        var speed = 0.3;
        var jump = 0;
        var jumpheight = 13;
        var stagewidth = 640;
        var stageheight = 640;
        var canshoot = 1;
        var dir = 2;
 
        var threshold = 0.5;
        var firing = 0;
        var canjump = 1;
        var alive = 1;
        var xspeed2 = 0;
        var yspeed2 = -15;
        var guyposy2 = startposy2;
        var guyposx2 = startposx2;
 
        var jump2 = 0;
        var canshoot2 = 1;
        var dir2 = 1;
        var firing2 = 0;
        var canjump2 = 1;
        var alive2 = 1;
        var gamepaused = 0;
        var barnumber = 0;
 
        var guyposy = startposy;
        var guyposx = startposx;
        var firetrigger;
        var lefttrigger;
        var righttrigger;
 
        var testcount = 0;
        var testevery = 10;
        var startshoot = 0;
        var reflex = 10;
        var minimumreflex = 3;
        var randomreflex = minimumreflex + Math.random(reflex);
        var count = 0;
 
        var sections = 0;
        var guy1section = 1;
        var guy2section = 1;
        var targetnum = 1;
        var optionnum = 1;
        var currenttarget;
        
        
        document.onkeyup = handleKeyUp.bind(this);
    document.onkeydown = handleKeyDown.bind(this);
     function handleKeyDown(e) {
        if (!e) {
          var e = window.event;
        }
        if(e.keyCode==39)
        {
            right = true;
        }
        if(e.keyCode==38)
        {
            up = true;
        }
        if(e.keyCode==37)
        {
            left = true;
        }
        if(e.keyCode==40)
        {
            down = true;
            ymov = ymov + 5; 
        }
 
        
    }
    
    function handleKeyUp(e) {
        if (!e) {
          var e = window.event;
        }
        if(e.keyCode==39)
        {
          right = false;
        }
        if(e.keyCode==38)
        {
            up = false;
        }
        if(e.keyCode==37)
        {
            left = false;
        }
         if(e.keyCode==40)
        {
            down = false;
            ymov = 0; 
        }
    } 
    
    
        function init() {
            stage = new createjs.Stage("demoCanvas");
            
            
            footer2 = new createjs.Shape();
            footer2.graphics.beginStroke("black");
      footer2.graphics.beginFill("#cccccc");
      footer2.graphics.moveTo(0,0).lineTo(721.35,0).lineTo(721.35,48.4).lineTo(0,48.4).lineTo(0,0);
      footer2._name = "background";
      footer2.isCollision = true;
     
      footer2.width = 721;
      footer2.height = 48;
      footer2.x = 0;
      footer2.y = 324;
      arr1.push(footer2);
      
            box1 = new createjs.Shape();
            
            box1.graphics.beginStroke("black");
      box1.graphics.beginFill("#cccccc");
      box1.graphics.moveTo(0,0).lineTo(23,0).lineTo(23,23).lineTo(0,23).lineTo(0,0);
      box1._name = "box1";
      box1.isCollision = true;
     
      box1.width = 23;
      box1.height = 23;
      box1.x = 113;
      box1.y = 300;
      arr1.push(box1); 
            
            box2 = new createjs.Shape();
            box2.graphics.beginStroke("black");
      box2.graphics.beginFill("#cccccc");
      box2.graphics.moveTo(0,0).lineTo(23,0).lineTo(23,23).lineTo(0,23).lineTo(0,0);
      box2._name = "box2";
      box2.isCollision = false;
      box2.width = 23;
      box2.height = 23;
      box2.x = 183;
      box2.y = 300;
      arr1.push(box2);
      
      box3 = new createjs.Shape();
            box3.graphics.beginStroke("black");
      box3.graphics.beginFill("#cccccc");
      box3.graphics.moveTo(0,0).lineTo(23,0).lineTo(23,23).lineTo(0,23).lineTo(0,0);
      box3._name = "box3";
      box3.isCollision = true;
     
      box3.width = 23;
      box3.height = 23;
      box3.x = 308;
      box3.y = 300;
      arr1.push(box3);
     
     
      
      box4 = new createjs.Shape();
            box4.graphics.beginStroke("black");
      box4.graphics.beginFill("#cccccc");
      box4.graphics.moveTo(0,0).lineTo(30,0).lineTo(30,40).lineTo(0,40).lineTo(0,0);
      box4._name = "box4";
      box4.isCollision = true;
     
      box4.width = 30;
      box4.height = 40;
     
      box4.x = 335;
      box4.y = 283;
      arr1.push(box4);
      
      box5 = new createjs.Shape();
            box5.graphics.beginStroke("black");
      box5.graphics.beginFill("#cccccc");
      box5.graphics.moveTo(0,0).lineTo(23,0).lineTo(23,23).lineTo(0,23).lineTo(0,0);
      box5._name = "box5";
      
      box5.isCollision = true;
    
   
      box5.width = 23;
      box5.height = 23;
      box5.x = 428;
      box5.y = 300;
      arr1.push(box5);
      
      
      platform1 = new createjs.Shape();
            platform1.graphics.beginStroke("black");
      platform1.graphics.beginFill("#cccccc");
      platform1.graphics.moveTo(0,0).lineTo(72,0).lineTo(72,13).lineTo(0,13).lineTo(0,0);
      platform1._name = "platform1";
      platform1.isCollision = true;
     
      platform1.width = 72;
      platform1.height = 13;
      platform1.x = 164;
      platform1.y = 278;
      arr1.push(platform1);
      
      platform2 = new createjs.Shape();
            platform2.graphics.beginStroke("black");
      platform2.graphics.beginFill("#cccccc");
      platform2.graphics.moveTo(0,0).lineTo(40,0).lineTo(40,10).lineTo(0,10).lineTo(0,0);
      platform2._name = "platform2";
      platform2.isCollision = true;
      
      platform2.width = 40;
      platform2.height = 10;
      platform2.x = 480;
      platform2.y = 280;
      arr1.push(platform2);
      
      platform3 = new createjs.Shape();
            platform3.graphics.beginStroke("black");
      platform3.graphics.beginFill("#cccccc");
      platform3.graphics.moveTo(0,0).lineTo(40,0).lineTo(40,10).lineTo(0,10).lineTo(0,0);
      platform3._name = "platform3";
      platform3.isCollision = true;
     
      platform3.width = 40;
      platform3.height = 10;
      platform3.x = 565;
      platform3.y = 280;
      arr1.push(platform3);
      
      platform4 = new createjs.Shape();
            platform4.graphics.beginStroke("black");
      platform4.graphics.beginFill("#cccccc");
      platform4.graphics.moveTo(0,0).lineTo(40,0).lineTo(40,10).lineTo(0,10).lineTo(0,0);
      platform4._name = "platform4";
      platform4.isCollision = true;
     
      platform4.width = 40;
      platform4.height = 10;
      platform4.x = 650;
      platform4.y = 280;
      arr1.push(platform4);
     
      guy1 = new createjs.Shape();
            guy1.graphics.beginStroke("black");
      guy1.graphics.beginFill("#cccccc");
      guy1.graphics.moveTo(0,0).lineTo(23,0).lineTo(23,23).lineTo(0,23).lineTo(0,0);
      guy1._name = "guy1";
      guy1.isCollision = false;
      
      guy1.width = 23;
      guy1.height = 23;
      guy1.x = startposx2;
      guy1.y = startposy2;
      arr1.push(guy1);
      
      
      guy2 = new createjs.Shape();
            guy2.graphics.beginStroke("black");
      guy2.graphics.beginFill("#cccccc");
      guy2.graphics.moveTo(0,0).lineTo(23,0).lineTo(23,23).lineTo(0,23).lineTo(0,0);
      guy2._name = "guy2";
      guy2.isCollision = false;
     
      guy2.width = 23;
      guy2.height = 23;
      guy2.x = startposx;
      guy2.y = startposy;
            arr1.push(guy2);
        
        
          stage.addChild(footer2,box1,box2,box3,box4,box5,platform1,platform2,platform3,platform4,guy1,guy2);
            createjs.Ticker.on("tick", tick);
        }
        var coll = false;
        
        
        function hitTestPoint(x1, y1) {
 
 
 
           for(var i = 0; i<arr1.length; i++)
           {
             if(arr1[i].isCollision)
             {
               if (x1 >= arr1[i].x-23 && x1 <= arr1[i].x+arr1[i].width
                    && y1 >= arr1[i].y-23 && y1 <= arr1[i].y+arr1[i].height) {
                   return true;
                } 
             }
            }
            return false;
 
 
        }
        
        function tick(event) {
      if (computer == 0) {
                    humanfunction();
                } else {
                    computerfunction();
                }
                if (alive2 == 1) {
                    if (jumptrigger == 1) {
                        if (jump2 == 1) {
                            if (firetrigger != 1) {
                                if (canjump2 == 1) {
                                    yspeed2 = 0 - jumpheight;
                                    canjump2 = 0;
                                }
                            }
                        }
                    } else {
                        canjump2 = 1;
                    }
                    if (firetrigger == 1) {
 
 
                    } else {
 
                        if (lefttrigger == 1) {
                            dir2 = 1;
                            xspeed2 = xspeed2 - 1;
 
                        } else {
                            if (righttrigger == 1) {
                                dir2 = 2;
                                xspeed2 = xspeed2 + 1;
 
                            } else {
 
                            }
                        }
                    }
                    if (0 != xspeed2 > 0 & 0 != xspeed2 < threshold) {
                        xspeed2 = 0;
                    } else {
                        if (0 != xspeed2 < 0 & 0 != xspeed2 > 0 - threshold) {
                            xspeed2 = 0;
                        }
                    }
                    xspeed2 = xspeed2 * 0.9;
                    yspeed2 = yspeed2 + grav;
                    i = 0;
                    while (i <= Math.sqrt(yspeed2 * yspeed2)) {
                        if (yspeed2 > 0) {
 
                            if (0 != hitTestPoint(guyposx2 + guywidth - 4, guyposy2 + guyheight, true) |
                                0 != hitTestPoint(guyposx2 - guywidth + 4, guyposy2 + guyheight, true)) {
                                //trace(yspeed2);
                                yspeed2 = 0;
                                jump2 = 1;
                            } else {
                                jump2 = 0;
                                guyposy2 = guyposy2 + speed;
                            }
                        } else {
                            if (yspeed2 < 0) {
                                jump2 = 0;
                                if (0 != hitTestPoint(guyposx2 + guywidth - 4, guyposy2 - guyheight, true) |
                                    0 != hitTestPoint(guyposx2 - guywidth + 4, guyposy2 - guyheight, true)) {
                                    yspeed2 = 0;
                                } else {
                                    guyposy2 = guyposy2 - speed;
                                }
                            }
                        }
                        ++i;
                    }
                    i = 0;
                    while (i <= Math.sqrt(xspeed2 * xspeed2)) {
                        if (xspeed2 > 0) {
                           
 
 
 
                            if (hitTestPoint(guyposx2 + guywidth, guyposy2 + guyheight - 1, true) |
                                hitTestPoint(guyposx2 + guywidth, guyposy2 - guyheight + 1, true))
                            {
                                xspeed2 = 0;
                            } else {
                                guyposx2 = guyposx2 + speed;
                            }
                        } else {
                            if (xspeed2 < 0) {
                                if (0 != hitTestPoint(guyposx2 - guywidth, guyposy2 + guyheight - 1, true) |
                                    0 != hitTestPoint(guyposx2 - guywidth, guyposy2 - guyheight + 1, true)) {
                                    xspeed2 = 0;
                                } else {
                                    guyposx2 = guyposx2 - speed;
                                }
                            }
                        }
                        ++i;
                    }
                    arr1[11].x = guyposx2;
                    arr1[11].y = guyposy2 + 7;
 
 
                }
      stage.update(event);
        }
        
        
        function humanfunction() {
            
        }
 
        function computerfunction() {
            if (firetrigger == 0) {
                lefttrigger = 0;
                righttrigger = 0;
            }
            ++testcount;
            if (testcount > testevery) {
                testcount = 0;
                if (guyposy < guyposy2 + 10) {
                    if (guyposy > guyposy2 - 10) {
                        if (guyposx < guyposx2 - 10) {
                            if (testfunction(-1, 0)) {
                                startshoot = 1;
                                firetrigger = 1;
                                lefttrigger = 1;
                            }
                        } else {
                            if (guyposx > guyposx2 + 10) {
                                if (testfunction(1, 0)) {
                                    startshoot = 1;
                                    righttrigger = 1;
                                    firetrigger = 1;
                                }
                            }
                        }
                    }
                    if (guyposx > guyposx2 - 10) {
                        if (guyposx < guyposx2 + 10) {
                            if (testfunction(0, -1)) {
                                startshoot = 1;
                                jumptrigger = 1;
                                firetrigger = 1;
                            }
                        } else {
                            if (testfunction(1, -1)) {
                                startshoot = 1;
                                righttrigger = 1;
                                jumptrigger = 1;
                                firetrigger = 1;
                            }
                        }
                    } else {
                        if (testfunction(-1, -1)) {
                            startshoot = 1;
                            lefttrigger = 1;
                            jumptrigger = 1;
                            firetrigger = 1;
                        }
                    }
                }
            }
            if (startshoot > 0) {
                ++startshoot;
                if (startshoot > randomreflex) {
                    randomreflex = minimumreflex + random(reflex);
                    startshoot = 0;
                    firetrigger = 0;
                }
            } else {
                righttrigger = 1;
                lefttrigger = 0;
                settarget();
                if (hitTestPoint(guyposx2 - guywidth - 1, guyposy2 + guyheight + 2, true)) {
                   
                    if (0 != hitTestPoint(guyposx2 - guywidth - 1, guyposy2, true) & 0 != !hitTestPoint(guyposx2 - guywidth - 1, guyposy2 - 16, true)) {
                        if (lefttrigger == 1) {
                            if (jumptrigger == 0) {
                                jumptrigger = 1;
                            } else {
                                jumptrigger = 0;
                            }
                        } else {
                            jumptrigger = 0;
                        }
                    } else {
 
                        if (hitTestPoint(guyposx2 + guywidth + 1, guyposy2 + guyheight + 2, true)) {
                            if (0 != hitTestPoint(guyposx2 + guywidth + 1, guyposy2, true) &
                                0 != !hitTestPoint(guyposx2 + guywidth + 1, guyposy2 - 16, true)) {
                                if (righttrigger == 1) {
                                    if (jumptrigger == 0) {
                                        jumptrigger = 1;
                                    } else {
                                        jumptrigger = 0;
                                    }
                                } else {
                                    jumptrigger = 0;
                                }
                            } else {
                                jumptrigger = 0;
                            }
                        } else {
                           jumptrigger = 1;
                        }
                    }
                } else {
                    jumptrigger = 0;
                }
            }
            ++count;
        }
 
        function testfunction() {
 
        }
        
        function settarget() {
            i = 1;
            while (i <= sections) {
                if (!hitTestPoint(guyposx, guyposy)) {
                    if (hitTestPoint(guyposx, guyposy)) {
                        guy1section = i;
                        targetnum = 1;
                        optionnum = 1;
                    }
                }
                if (!hitTestPoint(guyposx2, guyposy2)) {
                    if (hitTestPoint(guyposx2, guyposy2)) {
                        guy2section = i;
                        targetnum = 1;
                        optionnum = 1;
                    }
                }
                ++i;
            }
            if (0 != (guy1section == guy2section) & 0 != (gotshield == 0)) {
                currenttarget = arr1[10];
            } else {
 
            }
 
 
            if (alive == 0) {
 
            }
            if (alive2 == 0) {
                guy2section = 0;
            }
        }
        
        
        
    </script>
</head>
<body onload="init();">
  
    <canvas id="demoCanvas" width="800" height="600">
        alternate content
    </canvas>
    <input type="text" id="debug"/>
</body>
</html>
Исходники вместе с библиотекой.
Game.zip

P.S. На мой взгляд библиотека EaselJS очень удобная, единственный недостаток, отсутствует функция для подгона размера под мобильная устройства, т.е. адаптивности как таковой нет, по крайне мере я ее не нашла пока изучала библиотеку, придется позже самой написать.

Все остальное есть для создания браузерных игр: добавление графики, звуков, прогресс бара.
0
403 / 19 / 5
Регистрация: 17.01.2017
Сообщений: 572
06.05.2024, 18:03  [ТС]
8Observer8, еще обнаружила небольшую ошибку при столкновении объектов прежде чем сделать прыжок на следующую платформу герой выезжает за край предыдущей платформы. Ширина смешения равна ширины героя, чтобы этого избежать нужно в столкновениях вычесть ширину героя "arr1[i].width-guy2.width".
JavaScript
1
2
3
4
if (x1 >= arr1[i].x-23 && x1 <= arr1[i].x+arr1[i].width-guy2.width
                    && y1 >= arr1[i].y-23 && y1 <= arr1[i].y+arr1[i].height) {
                   return true;
                }
Полностью код:
PHP/HTML
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
<!DOCTYPE html>
<html>
<head>
    <title>EaselJS demo: AI</title>
  
  <script src="./easeljs.js"></script>
    <script>
        var stage, holder,footer2,box1,box2,box3,box4,box5,platform1,platform2,platform3,platform4,guy2;
        
        
        var arr1 = [];
        var computer = 1;
        var shieldnum = 0;
        var shieldavailable = 0;
        var shieldtimer = 0;
        var shieldtime = 1000;
        var reloadtime = 50;
        var reloadtimer = 0;
        var reloadtimer2 = 0;
        var shotsleft = 5;
        var shotsleft2 = 5;
        var gotshield = 0;
        var gotshield2 = 0;
        var xspeed = 0;
        var yspeed = -15;
        var grav = 1;
        var startposx = 802;
        var startposy = 12;
        var startposx2 = 0;
        var startposy2 = 300;
 
        var guyheight = 10;
        var guywidth = 5;
        var speed = 0.3;
        var jump = 0;
        var jumpheight = 13;
        var stagewidth = 640;
        var stageheight = 640;
        var canshoot = 1;
        var dir = 2;
 
        var threshold = 0.5;
        var firing = 0;
        var canjump = 1;
        var alive = 1;
        var xspeed2 = 0;
        var yspeed2 = -15;
        var guyposy2 = startposy2;
        var guyposx2 = startposx2;
 
        var jump2 = 0;
        var canshoot2 = 1;
        var dir2 = 1;
        var firing2 = 0;
        var canjump2 = 1;
        var alive2 = 1;
        var gamepaused = 0;
        var barnumber = 0;
 
        var guyposy = startposy;
        var guyposx = startposx;
        var firetrigger;
        var lefttrigger;
        var righttrigger;
 
        var testcount = 0;
        var testevery = 10;
        var startshoot = 0;
        var reflex = 10;
        var minimumreflex = 3;
        var randomreflex = minimumreflex + Math.random(reflex);
        var count = 0;
 
        var sections = 0;
        var guy1section = 1;
        var guy2section = 1;
        var targetnum = 1;
        var optionnum = 1;
        var currenttarget;
        
        
        document.onkeyup = handleKeyUp.bind(this);
    document.onkeydown = handleKeyDown.bind(this);
     function handleKeyDown(e) {
        if (!e) {
          var e = window.event;
        }
        if(e.keyCode==39)
        {
            right = true;
        }
        if(e.keyCode==38)
        {
            up = true;
        }
        if(e.keyCode==37)
        {
            left = true;
        }
        if(e.keyCode==40)
        {
            down = true;
            ymov = ymov + 5; 
        }
 
        
    }
    
    function handleKeyUp(e) {
        if (!e) {
          var e = window.event;
        }
        if(e.keyCode==39)
        {
          right = false;
        }
        if(e.keyCode==38)
        {
            up = false;
        }
        if(e.keyCode==37)
        {
            left = false;
        }
         if(e.keyCode==40)
        {
            down = false;
            ymov = 0; 
        }
    } 
    
    
        function init() {
            stage = new createjs.Stage("demoCanvas");
            
            
            footer2 = new createjs.Shape();
            footer2.graphics.beginStroke("black");
      footer2.graphics.beginFill("#cccccc");
      footer2.graphics.moveTo(0,0).lineTo(721.35,0).lineTo(721.35,48.4).lineTo(0,48.4).lineTo(0,0);
      footer2._name = "background";
      footer2.isCollision = true;
     
      footer2.width = 721;
      footer2.height = 48;
      footer2.x = 0;
      footer2.y = 324;
      arr1.push(footer2);
      
            box1 = new createjs.Shape();
            
            box1.graphics.beginStroke("black");
      box1.graphics.beginFill("#cccccc");
      box1.graphics.moveTo(0,0).lineTo(23,0).lineTo(23,23).lineTo(0,23).lineTo(0,0);
      box1._name = "box1";
      box1.isCollision = true;
     
      box1.width = 23;
      box1.height = 23;
      box1.x = 113;
      box1.y = 300;
      arr1.push(box1); 
            
            box2 = new createjs.Shape();
            box2.graphics.beginStroke("black");
      box2.graphics.beginFill("#cccccc");
      box2.graphics.moveTo(0,0).lineTo(23,0).lineTo(23,23).lineTo(0,23).lineTo(0,0);
      box2._name = "box2";
      box2.isCollision = false;
      box2.width = 23;
      box2.height = 23;
      box2.x = 183;
      box2.y = 300;
      arr1.push(box2);
      
      box3 = new createjs.Shape();
            box3.graphics.beginStroke("black");
      box3.graphics.beginFill("#cccccc");
      box3.graphics.moveTo(0,0).lineTo(23,0).lineTo(23,23).lineTo(0,23).lineTo(0,0);
      box3._name = "box3";
      box3.isCollision = true;
     
      box3.width = 23;
      box3.height = 23;
      box3.x = 308;
      box3.y = 300;
      arr1.push(box3);
     
     
      
      box4 = new createjs.Shape();
            box4.graphics.beginStroke("black");
      box4.graphics.beginFill("#cccccc");
      box4.graphics.moveTo(0,0).lineTo(30,0).lineTo(30,40).lineTo(0,40).lineTo(0,0);
      box4._name = "box4";
      box4.isCollision = true;
     
      box4.width = 30;
      box4.height = 40;
     
      box4.x = 335;
      box4.y = 283;
      arr1.push(box4);
      
      box5 = new createjs.Shape();
            box5.graphics.beginStroke("black");
      box5.graphics.beginFill("#cccccc");
      box5.graphics.moveTo(0,0).lineTo(23,0).lineTo(23,23).lineTo(0,23).lineTo(0,0);
      box5._name = "box5";
      
      box5.isCollision = true;
    
   
      box5.width = 23;
      box5.height = 23;
      box5.x = 428;
      box5.y = 300;
      arr1.push(box5);
      
      
      platform1 = new createjs.Shape();
            platform1.graphics.beginStroke("black");
      platform1.graphics.beginFill("#cccccc");
      platform1.graphics.moveTo(0,0).lineTo(72,0).lineTo(72,13).lineTo(0,13).lineTo(0,0);
      platform1._name = "platform1";
      platform1.isCollision = true;
     
      platform1.width = 72;
      platform1.height = 13;
      platform1.x = 164;
      platform1.y = 278;
      arr1.push(platform1);
      
      platform2 = new createjs.Shape();
            platform2.graphics.beginStroke("black");
      platform2.graphics.beginFill("#cccccc");
      platform2.graphics.moveTo(0,0).lineTo(40,0).lineTo(40,10).lineTo(0,10).lineTo(0,0);
      platform2._name = "platform2";
      platform2.isCollision = true;
      
      platform2.width = 40;
      platform2.height = 10;
      platform2.x = 480;
      platform2.y = 280;
      arr1.push(platform2);
      
      platform3 = new createjs.Shape();
            platform3.graphics.beginStroke("black");
      platform3.graphics.beginFill("#cccccc");
      platform3.graphics.moveTo(0,0).lineTo(40,0).lineTo(40,10).lineTo(0,10).lineTo(0,0);
      platform3._name = "platform3";
      platform3.isCollision = true;
     
      platform3.width = 40;
      platform3.height = 10;
      platform3.x = 565;
      platform3.y = 280;
      arr1.push(platform3);
      
      platform4 = new createjs.Shape();
            platform4.graphics.beginStroke("black");
      platform4.graphics.beginFill("#cccccc");
      platform4.graphics.moveTo(0,0).lineTo(40,0).lineTo(40,10).lineTo(0,10).lineTo(0,0);
      platform4._name = "platform4";
      platform4.isCollision = true;
     
      platform4.width = 40;
      platform4.height = 10;
      platform4.x = 650;
      platform4.y = 280;
      arr1.push(platform4);
     
      guy1 = new createjs.Shape();
            guy1.graphics.beginStroke("black");
      guy1.graphics.beginFill("#cccccc");
      guy1.graphics.moveTo(0,0).lineTo(23,0).lineTo(23,23).lineTo(0,23).lineTo(0,0);
      guy1._name = "guy1";
      guy1.isCollision = false;
      
      guy1.width = 23;
      guy1.height = 23;
      guy1.x = startposx2;
      guy1.y = startposy2;
      arr1.push(guy1);
      
      
      guy2 = new createjs.Shape();
            guy2.graphics.beginStroke("black");
      guy2.graphics.beginFill("#cccccc");
      guy2.graphics.moveTo(0,0).lineTo(23,0).lineTo(23,23).lineTo(0,23).lineTo(0,0);
      guy2._name = "guy2";
      guy2.isCollision = false;
     
      guy2.width = 23;
      guy2.height = 23;
      guy2.x = startposx;
      guy2.y = startposy;
            arr1.push(guy2);
        
        
          stage.addChild(footer2,box1,box2,box3,box4,box5,platform1,platform2,platform3,platform4,guy1,guy2);
            createjs.Ticker.on("tick", tick);
        }
        var coll = false;
        
        
        function hitTestPoint(x1, y1) {
 
 
 
           for(var i = 0; i<arr1.length; i++)
           {
             if(arr1[i].isCollision)
             {
               if (x1 >= arr1[i].x-guy2.width && x1 <= arr1[i].x+arr1[i].width-guy2.width
                    && y1 >= arr1[i].y-guy2.height && y1 <= arr1[i].y+arr1[i].height) {
                   return true;
                } 
             }
            }
            return false;
 
 
        }
        
        function tick(event) {
      if (computer == 0) {
                    humanfunction();
                } else {
                    computerfunction();
                }
                if (alive2 == 1) {
                    if (jumptrigger == 1) {
                        if (jump2 == 1) {
                            if (firetrigger != 1) {
                                if (canjump2 == 1) {
                                    yspeed2 = 0 - jumpheight;
                                    canjump2 = 0;
                                }
                            }
                        }
                    } else {
                        canjump2 = 1;
                    }
                    if (firetrigger == 1) {
 
 
                    } else {
 
                        if (lefttrigger == 1) {
                            dir2 = 1;
                            xspeed2 = xspeed2 - 1;
 
                        } else {
                            if (righttrigger == 1) {
                                dir2 = 2;
                                xspeed2 = xspeed2 + 1;
 
                            } else {
 
                            }
                        }
                    }
                    if (0 != xspeed2 > 0 & 0 != xspeed2 < threshold) {
                        xspeed2 = 0;
                    } else {
                        if (0 != xspeed2 < 0 & 0 != xspeed2 > 0 - threshold) {
                            xspeed2 = 0;
                        }
                    }
                    xspeed2 = xspeed2 * 0.9;
                    yspeed2 = yspeed2 + grav;
                    i = 0;
                    while (i <= Math.sqrt(yspeed2 * yspeed2)) {
                        if (yspeed2 > 0) {
 
                            if (0 != hitTestPoint(guyposx2 + guywidth - 4, guyposy2 + guyheight, true) |
                                0 != hitTestPoint(guyposx2 - guywidth + 4, guyposy2 + guyheight, true)) {
                                //trace(yspeed2);
                                yspeed2 = 0;
                                jump2 = 1;
                            } else {
                                jump2 = 0;
                                guyposy2 = guyposy2 + speed;
                            }
                        } else {
                            if (yspeed2 < 0) {
                                jump2 = 0;
                                if (0 != hitTestPoint(guyposx2 + guywidth - 4, guyposy2 - guyheight, true) |
                                    0 != hitTestPoint(guyposx2 - guywidth + 4, guyposy2 - guyheight, true)) {
                                    yspeed2 = 0;
                                } else {
                                    guyposy2 = guyposy2 - speed;
                                }
                            }
                        }
                        ++i;
                    }
                    i = 0;
                    while (i <= Math.sqrt(xspeed2 * xspeed2)) {
                        if (xspeed2 > 0) {
                           
 
 
 
                            if (hitTestPoint(guyposx2 + guywidth, guyposy2 + guyheight - 1, true) |
                                hitTestPoint(guyposx2 + guywidth, guyposy2 - guyheight + 1, true))
                            {
                                xspeed2 = 0;
                            } else {
                                guyposx2 = guyposx2 + speed;
                            }
                        } else {
                            if (xspeed2 < 0) {
                                if (0 != hitTestPoint(guyposx2 - guywidth, guyposy2 + guyheight - 1, true) |
                                    0 != hitTestPoint(guyposx2 - guywidth, guyposy2 - guyheight + 1, true)) {
                                    xspeed2 = 0;
                                } else {
                                    guyposx2 = guyposx2 - speed;
                                }
                            }
                        }
                        ++i;
                    }
                    arr1[11].x = guyposx2;
                    arr1[11].y = guyposy2 + 7;
 
 
                }
      stage.update(event);
        }
        
        
        function humanfunction() {
            
        }
 
        function computerfunction() {
            if (firetrigger == 0) {
                lefttrigger = 0;
                righttrigger = 0;
            }
            ++testcount;
            if (testcount > testevery) {
                testcount = 0;
                if (guyposy < guyposy2 + 10) {
                    if (guyposy > guyposy2 - 10) {
                        if (guyposx < guyposx2 - 10) {
                            if (testfunction(-1, 0)) {
                                startshoot = 1;
                                firetrigger = 1;
                                lefttrigger = 1;
                            }
                        } else {
                            if (guyposx > guyposx2 + 10) {
                                if (testfunction(1, 0)) {
                                    startshoot = 1;
                                    righttrigger = 1;
                                    firetrigger = 1;
                                }
                            }
                        }
                    }
                    if (guyposx > guyposx2 - 10) {
                        if (guyposx < guyposx2 + 10) {
                            if (testfunction(0, -1)) {
                                startshoot = 1;
                                jumptrigger = 1;
                                firetrigger = 1;
                            }
                        } else {
                            if (testfunction(1, -1)) {
                                startshoot = 1;
                                righttrigger = 1;
                                jumptrigger = 1;
                                firetrigger = 1;
                            }
                        }
                    } else {
                        if (testfunction(-1, -1)) {
                            startshoot = 1;
                            lefttrigger = 1;
                            jumptrigger = 1;
                            firetrigger = 1;
                        }
                    }
                }
            }
            if (startshoot > 0) {
                ++startshoot;
                if (startshoot > randomreflex) {
                    randomreflex = minimumreflex + random(reflex);
                    startshoot = 0;
                    firetrigger = 0;
                }
            } else {
                righttrigger = 1;
                lefttrigger = 0;
                settarget();
                if (hitTestPoint(guyposx2 - guywidth - 1, guyposy2 + guyheight + 2, true)) {
                   
                    if (0 != hitTestPoint(guyposx2 - guywidth - 1, guyposy2, true) & 0 != !hitTestPoint(guyposx2 - guywidth - 1, guyposy2 - 16, true)) {
                        if (lefttrigger == 1) {
                            if (jumptrigger == 0) {
                                jumptrigger = 1;
                            } else {
                                jumptrigger = 0;
                            }
                        } else {
                            jumptrigger = 0;
                        }
                    } else {
 
                        if (hitTestPoint(guyposx2 + guywidth + 1, guyposy2 + guyheight + 2, true)) {
                            if (0 != hitTestPoint(guyposx2 + guywidth + 1, guyposy2, true) &
                                0 != !hitTestPoint(guyposx2 + guywidth + 1, guyposy2 - 16, true)) {
                                if (righttrigger == 1) {
                                    if (jumptrigger == 0) {
                                        jumptrigger = 1;
                                    } else {
                                        jumptrigger = 0;
                                    }
                                } else {
                                    jumptrigger = 0;
                                }
                            } else {
                                jumptrigger = 0;
                            }
                        } else {
                           jumptrigger = 1;
                        }
                    }
                } else {
                    jumptrigger = 0;
                }
            }
            ++count;
        }
 
        function testfunction() {
 
        }
        
        function settarget() {
            i = 1;
            while (i <= sections) {
                if (!hitTestPoint(guyposx, guyposy)) {
                    if (hitTestPoint(guyposx, guyposy)) {
                        guy1section = i;
                        targetnum = 1;
                        optionnum = 1;
                    }
                }
                if (!hitTestPoint(guyposx2, guyposy2)) {
                    if (hitTestPoint(guyposx2, guyposy2)) {
                        guy2section = i;
                        targetnum = 1;
                        optionnum = 1;
                    }
                }
                ++i;
            }
            if (0 != (guy1section == guy2section) & 0 != (gotshield == 0)) {
                currenttarget = arr1[10];
            } else {
 
            }
 
 
            if (alive == 0) {
 
            }
            if (alive2 == 0) {
                guy2section = 0;
            }
        }
        
        
        
    </script>
</head>
<body onload="init();">
  
    <canvas id="demoCanvas" width="800" height="600">
        alternate content
    </canvas>
    <input type="text" id="debug"/>
</body>
</html>
0
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
06.05.2024, 21:24
Phaser использует собственный физический движок Arcade Physics для определения столкновений. Физический движок Box2D является более продвинутым, распространённым и универсальным. То есть Arcade Physics может быть использован только вместе с Phaser, а Box2D можно использовать с любыми игровыми фреймворками. Даже можно использовать Box2D вместе Three.js в 3D. В таком платформере объекты можно сделать 3D, а физику 2D. Я запускал Box2D (точнее порты на JS: box2d/core и Box2D-WASM) на серверной части на Node.js на бесплатном хостинге https://render.com/ Можно сделать физику на стороне сервера, а игру с мультиплеером.

Заменил Arcade Physics на @box2d/core в примерах туториала Making your first Phaser 3 game

Ссылки на примеры в песочнице:

GitHub репозиторий с руководством на Rollup

А также заменил Arcade Physics на Box2D-WASM. Мне этот порт больше понравился. Точнее, это не порт, а сборка С++ исходников Box2D в WebAssembly с помощью Emscripten. Понравилась эта сборка тем, что класс, которые отвечает за отрисовку коллайдеров предоставляет координаты вершин коллайдеров напрямую, а box2d/core использует save/restore. Я экспериментировал с передачей координат вершин коллайдеров от сервера клиентам через вебсокеты, чтобы проще было отлаживать демки с мультиплеером с физикой на серверной части.

Ссылки на примеры в песочнице:

GitHub репозиторий с руководством на Rullup



Миниатюра
Вложения
Тип файла: zip port-to-box2dcore-of-making-your-first-game-rollup-phaser3-js.zip (229.7 Кб, 0 просмотров)
Тип файла: zip port-to-box2dwasm-of-making-your-first-game-rollup-phaser3-js.zip (257.2 Кб, 0 просмотров)
0
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
07.05.2024, 11:42
Цитата Сообщение от Katerina1993 Посмотреть сообщение
я все равно не понимаю как это сделать столкновение на Phaser
Постараюсь шаг за шагом объяснить, как сделать определение столкновений (collision detection) на Arcade Physics. У вас в демке все объекты это квадраты и прямоугольники. За основу стартового примера возьму пример из первого урока Part 01: Introduction туториала Making your first Phaser 3 game

index.html

PHP/HTML
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
<!DOCTYPE html>
 
<html>
 
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Part 01. Introduction | Making your first Phaser 3 Game</title>
    <link rel="stylesheet" type="text/css" href="./css/style.css">
</head>
 
<body>
    <p style="position: absolute; top: 10px; left: 10px;"><a href="https://github.com/8Observer8/making-your-first-game-rollup-phaser3-js" target="_blanck">GitHub repository with Rollup guide</a> | Tutorial: <a href="https://phaser.io/tutorials/making-your-first-phaser-3-game/part1" target="_blank">Part 01. Introduction</a></p>
 
    <!-- Since import maps are not yet supported by all browsers, its is
        necessary to add the polyfill es-module-shims.js -->
    <script async src="https://unpkg.com/es-module-shims@1.9.0/dist/es-module-shims.js"></script>
 
    <script type="importmap">
        {
            "imports": {
                "phaser3": "https://cdn.jsdelivr.net/npm/phaser@3.80.1/dist/phaser.esm.min.js"
            }
        }
    </script>
 
    <script type="module" src="./js/index.js"></script>
</body>
 
</html>
js/index.js

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { WEBGL, Game, Scale } from "phaser3";
 
const config = {
    type: WEBGL,
 
    width: 800,
    height: 600,
    scaleMode: Scale.ScaleModes.FIT,
    autoCenter: Scale.Center.CENTER_BOTH,
 
    autoFocus: true,
    scene: { preload, create, update },
    backgroundColor: "#eee"
};
 
const game = new Game(config);
 
function preload() {}
 
function create() {}
 
function update() {}
css/style.css

CSS
1
2
3
4
* {
    padding: 0;
    margin: 0;
}
Можете пока прочитать текст первого урока: Part 01. Introduction
0
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
07.05.2024, 12:23
Почему-то сегодня очень долго загружается файл "phaser.esm.min.js" из "jsdelivr", поэтому заменил на "unpkg":

PHP/HTML
1
2
3
4
5
6
7
    <script type="importmap">
        {
            "imports": {
                "phaser3": "https://unpkg.com/phaser@3.80.1/dist/phaser.esm.min.js"
            }
        }
    </script>
Добавил элемент <canvas> в "index.html" и добавил "canvas" в "config" в "index.js". А так же добавил "overflow: hidden;" в "style.css", чтобы скрыть вертикальный scroll bar:

index.html

PHP/HTML
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
<!DOCTYPE html>
 
<html>
 
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple platformer AI in Phaser 3 and JavaScript</title>
    <link rel="stylesheet" type="text/css" href="./css/style.css">
</head>
 
<body>
    <canvas id="renderCanvas"></canvas>
 
    <!-- Since import maps are not yet supported by all browsers, its is
        necessary to add the polyfill es-module-shims.js -->
    <script async src="https://unpkg.com/es-module-shims@1.9.0/dist/es-module-shims.js"></script>
 
    <script type="importmap">
        {
            "imports": {
                "phaser3": "https://unpkg.com/phaser@3.80.1/dist/phaser.esm.min.js"
            }
        }
    </script>
 
    <script type="module" src="./js/index.js"></script>
</body>
 
</html>
index.js

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { WEBGL, Game, Scale } from 'phaser3';
 
const config = {
    type: WEBGL,
 
    canvas: document.getElementById('renderCanvas'),
    width: 800,
    height: 550,
    scaleMode: Scale.ScaleModes.FIT,
    autoCenter: Scale.Center.CENTER_BOTH,
 
    autoFocus: true,
    scene: { preload, create, update },
    backgroundColor: '#eee'
};
 
const game = new Game(config);
 
function preload() {}
 
function create() {}
 
function update() {}
style.css

CSS
1
2
3
4
5
* {
    padding: 0;
    margin: 0;
    overflow: hidden;
}
0
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
07.05.2024, 12:38
Земля и статическая платформа

В примере выше я активировал внутренний физический движок Arcade Physics путём добавления следующего кода в "config":

JavaScript
1
2
3
4
5
6
7
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 200 },
            debug: false
        }
    },
Здесь указано какой физический движок активировать - это 'arcade'. Указал значение гравитации = 200. Ось Y направлена сверху вниз, поэтому положительный знак гравитации говорит о том, что гравитация будет вниз холста. Настройка "debug: false" означает, что коллайдеры и лучи не будут рисоваться. Эта настройка сделана для отладки физики, чтобы визуализировать коллайдеры и лучи.

Я добавил землю и платформу в функции "create":

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
function create() {
    const ground = this.add.rectangle(361, 348, 721.35, 48.4, 0xcccccc);
    ground.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(ground);
    ground.body.immovable = true;
    ground.body.allowGravity = false;
 
    const platform = this.add.rectangle(350, 250, 100, 50, 0xcccccc);
    platform.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(platform);
    platform.body.immovable = true;
    platform.body.allowGravity = false;
}
Получился следующий код:

index.html

PHP/HTML
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
<!DOCTYPE html>
 
<html>
 
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple platformer AI in Phaser 3 and JavaScript</title>
    <link rel="stylesheet" type="text/css" href="./css/style.css">
</head>
 
<body>
    <canvas id="renderCanvas"></canvas>
 
    <!-- Since import maps are not yet supported by all browsers, its is
        necessary to add the polyfill es-module-shims.js -->
    <script async src="https://unpkg.com/es-module-shims@1.9.0/dist/es-module-shims.js"></script>
 
    <script type="importmap">
        {
            "imports": {
                "phaser3": "https://unpkg.com/phaser@3.80.1/dist/phaser.esm.min.js"
            }
        }
    </script>
 
    <script type="module" src="./js/index.js"></script>
</body>
 
</html>
index.js

JavaScript
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
import { WEBGL, Game, Scale } from 'phaser3';
 
const config = {
    type: WEBGL,
 
    canvas: document.getElementById('renderCanvas'),
    width: 800,
    height: 550,
    scaleMode: Scale.ScaleModes.FIT,
    autoCenter: Scale.Center.CENTER_BOTH,
 
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 200 },
            debug: false
        }
    },
 
    autoFocus: true,
    scene: { preload, create, update },
    backgroundColor: "#eee"
};
 
const game = new Game(config);
 
function preload() {}
 
function create() {
    const ground = this.add.rectangle(361, 348, 721.35, 48.4, 0xcccccc);
    ground.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(ground);
    ground.body.immovable = true;
    ground.body.allowGravity = false;
 
    const platform = this.add.rectangle(350, 250, 100, 50, 0xcccccc);
    platform.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(platform);
    platform.body.immovable = true;
    platform.body.allowGravity = false;
}
 
function update() {}


Миниатюра
0
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
07.05.2024, 13:19
Добавление главного героя (ГГ) и управления героем с помощью клавиш-стрелок: влево, вправо, вверх (прыжок)

На основе примера Part 07. Controlling the player with the keyboard из этого урока сделал пример с квадратами и прямоугольниками. ГГ может двигаться с помощью клавиш-стрелок и прыгать за счёт установки линейной скорости тела:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
function update() {
    if (cursors.left.isDown) {
        player.body.setVelocityX(-100);
    } else if (cursors.right.isDown) {
        player.body.setVelocityX(100);
    } else {
        player.body.setVelocityX(0);
    }
 
    if (cursors.up.isDown && player.body.touching.down) {
        player.body.setVelocityY(-220);
    }
}
Настройка столкновений ГГ с землёй и платформой сделана в функции "create":

JavaScript
1
2
    this.physics.add.collider(player, ground);
    this.physics.add.collider(player, platform);
Код из "index.js" целиком:

JavaScript
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
import { WEBGL, Game, Scale } from 'phaser3';
 
const config = {
    type: WEBGL,
 
    canvas: document.getElementById('renderCanvas'),
    width: 800,
    height: 550,
    scaleMode: Scale.ScaleModes.FIT,
    autoCenter: Scale.Center.CENTER_BOTH,
 
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 200 },
            debug: false
        }
    },
 
    autoFocus: true,
    scene: { preload, create, update },
    backgroundColor: '#eee'
};
 
const game = new Game(config);
let cursors, player;
 
function preload() {}
 
function create() {
    const ground = this.add.rectangle(361, 348, 721.35, 48.4, 0xcccccc);
    ground.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(ground);
    ground.body.immovable = true;
    ground.body.allowGravity = false;
 
    const platform = this.add.rectangle(350, 250, 100, 50, 0xcccccc);
    platform.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(platform);
    platform.body.immovable = true;
    platform.body.allowGravity = false;
 
    player = this.add.rectangle(100, 250, 30, 30, 0x33ee00);
    player.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(player);
    player.body.setBounce(0.2);
    player.body.setCollideWorldBounds(true);
 
    this.physics.add.collider(player, ground);
    this.physics.add.collider(player, platform);
 
    cursors = this.input.keyboard.createCursorKeys();
}
 
function update() {
    if (cursors.left.isDown) {
        player.body.setVelocityX(-100);
    } else if (cursors.right.isDown) {
        player.body.setVelocityX(100);
    } else {
        player.body.setVelocityX(0);
    }
 
    if (cursors.up.isDown && player.body.touching.down) {
        player.body.setVelocityY(-220);
    }
}


Миниатюра
0
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
07.05.2024, 13:37
Определение столкновений

На основе примера Part 08. Stardust из этого урока, где ГГ собирает звёзды, сделал пример, где ГГ касается двух кубиков, а в консоль выводится к какому кубу прикоснулся игрок: к правому или к левому



Создаём в функции "create" левый и правый кубики:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
    const leftBox = this.add.rectangle(100, 297, 50, 50, 0xcccccc);
    leftBox.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(leftBox);
    leftBox.body.immovable = true;
    leftBox.body.allowGravity = false;
 
    const rightBox = this.add.rectangle(300, 297, 50, 50, 0xcccccc);
    rightBox.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(rightBox);
    rightBox.body.immovable = true;
    rightBox.body.allowGravity = false;
Создаём две функции, которые будут срабатывать, когда ГГ будет касаться левого или правого кубиков:

JavaScript
1
2
3
4
5
6
7
function leftBoxCollision() {
    console.log('left box');
}
 
function rightBoxCollision() {
    console.log('right box');
}
Настраиваем в функции "create", что если ГГ касается левого кубика, то вызываем функцию "leftBoxCollision", а если ГГ касается правого кубика, то вызываем функцию "rightBoxCollision":

JavaScript
1
2
    this.physics.add.overlap(player, leftBox, leftBoxCollision, null, this);
    this.physics.add.overlap(player, rightBox, rightBoxCollision, null, this);
Код в "index.js" целиком:

JavaScript
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
import { WEBGL, Game, Scale } from 'phaser3';
 
const config = {
    type: WEBGL,
 
    canvas: document.getElementById('renderCanvas'),
    width: 800,
    height: 550,
    scaleMode: Scale.ScaleModes.FIT,
    autoCenter: Scale.Center.CENTER_BOTH,
 
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 200 },
            debug: false
        }
    },
 
    autoFocus: true,
    scene: { preload, create, update },
    backgroundColor: '#eee'
};
 
const game = new Game(config);
let cursors, player;
 
function preload() {}
 
function create() {
    const ground = this.add.rectangle(361, 348, 721.35, 48.4, 0xcccccc);
    ground.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(ground);
    ground.body.immovable = true;
    ground.body.allowGravity = false;
 
    const platform = this.add.rectangle(450, 250, 100, 50, 0xcccccc);
    platform.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(platform);
    platform.body.immovable = true;
    platform.body.allowGravity = false;
 
    player = this.add.rectangle(200, 250, 30, 30, 0x33ee00);
    player.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(player);
    player.body.setBounce(0.2);
    player.body.setCollideWorldBounds(true);
 
    this.physics.add.collider(player, ground);
    this.physics.add.collider(player, platform);
 
    cursors = this.input.keyboard.createCursorKeys();
 
    const leftBox = this.add.rectangle(100, 297, 50, 50, 0xcccccc);
    leftBox.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(leftBox);
    leftBox.body.immovable = true;
    leftBox.body.allowGravity = false;
 
    const rightBox = this.add.rectangle(300, 297, 50, 50, 0xcccccc);
    rightBox.setStrokeStyle(1, 0xff0000);
    this.physics.world.enable(rightBox);
    rightBox.body.immovable = true;
    rightBox.body.allowGravity = false;
 
    this.physics.add.overlap(player, leftBox, leftBoxCollision, null, this);
    this.physics.add.overlap(player, rightBox, rightBoxCollision, null, this);
}
 
function leftBoxCollision() {
    console.log('left box');
}
 
function rightBoxCollision() {
    console.log('right box');
}
 
function update() {
    if (cursors.left.isDown) {
        player.body.setVelocityX(-100);
    } else if (cursors.right.isDown) {
        player.body.setVelocityX(100);
    } else {
        player.body.setVelocityX(0);
    }
 
    if (cursors.up.isDown && player.body.touching.down) {
        player.body.setVelocityY(-220);
    }
}
index.html

PHP/HTML
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
<!DOCTYPE html>
 
<html>
 
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple platformer AI in Phaser 3 and JavaScript</title>
    <link rel="stylesheet" type="text/css" href="./css/style.css">
</head>
 
<body>
    <canvas id="renderCanvas"></canvas>
 
    <!-- Since import maps are not yet supported by all browsers, its is
        necessary to add the polyfill es-module-shims.js -->
    <script async src="https://unpkg.com/es-module-shims@1.9.0/dist/es-module-shims.js"></script>
 
    <script type="importmap">
        {
            "imports": {
                "phaser3": "https://unpkg.com/phaser@3.80.1/dist/phaser.esm.min.js"
            }
        }
    </script>
 
    <script type="module" src="./js/index.js"></script>
</body>
 
</html>
style.css

CSS
1
2
3
4
5
* {
    padding: 0;
    margin: 0;
    overflow: hidden;
}
Миниатюры
0
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
07.05.2024, 15:09
Цитата Сообщение от 8Observer8 Посмотреть сообщение
Почему-то сегодня очень долго загружается файл "phaser.esm.min.js" из "jsdelivr", поэтому заменил на "unpkg"
Были почти одинаковые проблемы с "jsdelivr" и "unpkg", но с "unpkg" поменьше. Но в Discord'e Phaser мне ответил Mike, что:

For whatever it is worth, unpkg is not actively maintained anymore and has outages pretty often, I do not rely on them anymore, see issues: https://github.com/mjackson/unpkg/issues
Перевод https://translate.google.com/

Что бы это ни стоило, unpkg больше не поддерживается активно и довольно часто имеет сбои, я больше на них не полагаюсь, см. проблемы: https://github.com/mjackson/unpkg/issues
PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<body>
    <canvas id="renderCanvas"></canvas>
 
    <!-- Поскольку карты импорта пока поддерживаются не всеми браузерами,
        необходимо добавить полифилл es-module-shims.js -->
    <script async src="https://cdn.jsdelivr.net/npm/es-module-shims@1.10.0/dist/es-module-shims.js"></script>
 
    <script type="importmap">
        {
            "imports": {
                "phaser3": "https://cdn.jsdelivr.net/npm/phaser@3.80.1/dist/phaser.esm.min.js"
            }
        }
    </script>
 
    <script type="module" src="./js/index.js"></script>
</body>
0
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
10.05.2024, 12:25
Цитата Сообщение от 8Observer8 Посмотреть сообщение
Были почти одинаковые проблемы с "jsdelivr" и "unpkg", но с "unpkg" поменьше.
Вчера много было сбоев в работе "jsdelivr", при которых библиотеки грузились больше 2-х минут. Находил сообщения, что другие тоже это замечали. Я для себя решил, что лучше завести свой сайт на бесплатном хостинге GitHub Pages (тоже самое можно сделать на Bitbucket, Gitlab и т.д.), создать папку libs и закидывать в неё библиотеки. Удобно копировать библиотеки из папки "node_modules". Для этого надо создать репозиторий (это работает для Bitbucket и Gitlab), где первая часть будет ваши ник, вторая часть "github", а третья - "io". В моём случае получается такой адресс сайта: https://8observer8.github.io А ещё проще создать сайт на бесплатном хостинге https://www.netlify.com/, где можно просто перетащить свои файлы мышкой. Правда, будет длинный адресс сайта, но его можно сократить сервисом по сокращению имен (погуглите "short url"). Но лучше создать сайт для библиотек на GitHub Pages, Bitbucket, Gitlab и т.д.

Например, так можно подключить Phaser 3 и Box2D-WASM со своего сайта:

PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    <!-- Since import maps are not yet supported by all browsers, its is
        necessary to add the polyfill es-module-shims.js -->
    <script async src="https://8observer8.github.io/libs/es-module-shims@1.10.0/es-module-shims.js"></script>
 
    <script type="importmap">
        {
            "imports": {
                "box2d-wasm": "https://8observer8.github.io/libs/box2d-wasm@7.0.0/es/entry.js",
                "phaser3": "https://8observer8.github.io/libs/phaser@3.80.1/phaser.esm.min.js"
            }
        }
    </script>
 
    <script type="module" src="./js/index.js"></script>
А так - Three.js и OrbitControls:

PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    <!-- Since import maps are not yet supported by all browsers, its is
        necessary to add the polyfill es-module-shims.js -->
    <script async src="https://8observer8.github.io/libs/es-module-shims@1.10.0/es-module-shims.js"></script>
 
    <script type="importmap">
        {
            "imports": {
                "three": "https://8observer8.github.io/libs/three@0.164.1/build/three.module.min.js",
                "orbit-controls": "https://8observer8.github.io/libs/three@0.164.1/examples/jsm/controls/OrbitControls.js"
            }
        }
    </script>
 
    <script type="module" src="./js/index.js"></script>
А потом уже в index.js, подключенным с типом "модуль", можно импортировать библиотеки с помощью "import":

JavaScript
1
2
import Box2DLib from 'box2d-wasm';
import { Display, WEBGL, Game, Scale } from 'phaser3';
JavaScript
1
2
import * as THREE from 'three';
import { OrbitControls } from 'orbit-controls';
0
383 / 23 / 2
Регистрация: 12.06.2021
Сообщений: 211
Записей в блоге: 2
13.05.2024, 21:18
В EaselJS есть функция hitTest для столкновения объектов только я непоняла как ей пользоваться и написала свою функцию. Назвала hitTestPoint – так же как на Flash.
Функция hitTest реализована хуже чем похожая функция во Flash поэтому можно вызвать ее два раза, чтобы столкновение проверять при заходе квадрата в область сверху и снизу.
HTML5
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
<!DOCTYPE html>
<html>
    <head>
        <title>Пример hitTest</title>
        <style>
        body {
          width: 100%;
          height: 100%;
          background-color: #000;
        }
 
        #drawingCanvas {
          width: 75%;
          height: 75%;
          display: block;
          margin: auto;
          background-color: #000;
          padding-top: 10%;
        }
        </style>
          <script src='https://code.createjs.com/easeljs-0.8.2.min.js'></script>
   </head>
    <body>
        <canvas id="drawingCanvas" width="800" height="800"></canvas>
<script>
var stage = new createjs.Stage("drawingCanvas");
createjs.Ticker.on("tick", stage);
 
var shapeW = 50, hitW = 100;
 
var hit1 = new createjs.Shape().set({x:50, y:150});
hit1.color = hit1.graphics.s("blue").command;
hit1.graphics.ss(3, "round").sd([12,12]).f("#ddd").dr(0,0,hitW,hitW);
 
var hit2 = new createjs.Shape().set({x:250, y:150});
hit2.color = hit2.graphics.s("blue").command;
hit2.graphics.ss(3, "round").sd([12,12]).f("#ddd").dr(0,0,hitW,hitW);
 
var shape = new createjs.Shape().set({x:175, y:10, cursor:"pointer", alpha:0.75});
shape.graphics.f("#906").dr(0,0,shapeW,shapeW);
shape.on("pressmove", handleDrag);
 
stage.addChild(hit1, hit2, shape);
 
function handleDrag(event) {
 
    shape.x = event.stageX-shapeW/2;
  shape.y = event.stageY-shapeW/2;
  
 
  var pt1 = hit1.globalToLocal(shape.x, shape.y);  
  var pt2 = hit1.globalToLocal(shape.x+50, shape.y+50);  
  
  if (hit1.hitTest(pt1.x, pt1.y) || hit1.hitTest(pt2.x, pt2.y)) {
    hit1.color.style = "green";
  } else {
    hit1.color.style = "blue";
  }
  if (shape.x >= hit2.x-shapeW && shape.x <= hit2.x+hitW 
        && shape.y >= hit2.y-shapeW && shape.y <= hit2.y+hitW) {
    hit2.color.style = "green";    
  } else {
    hit2.color.style = "blue";
  }
} 
</script>
 
</body>
</html>
Но есть проблема. Если зайти в область второго квадрата с угла то hitTest не срабатывает. Пример можно видеть в Gif картинки.

Поэтому другое решение дополнить библиотеку Easelj используя extend и добавить новые функции.

Вот пример 3 разных способа столкновения (можно просто скопировать код в html и запустить через браузере). Особое внимание следует обратить на функции hitRect и hitTestPoint, они наследуют функцию Shape из библиотеки Easeljs.
HTML5
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
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Столкновение объектов</title>
</head>
 
<body>
<canvas id="canvas1" width="700" height="400"></canvas>
<input type="text" value="" id="debug"/>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script src='https://code.createjs.com/easeljs-0.8.2.min.js'></script>
<script>
 
 
(function (window) {
function hitObject(x,y,hitW,hitH) {
    this.hitW = hitW;
    this.hitH = hitH;
        this.Shape_constructor(); // super call
 
        this.activate(x,y,hitW,hitH);
}
 
 
 
 
 
var p = createjs.extend(hitObject, createjs.Shape);
 
 
p.activate = function (x,y,hitW,hitH) {
        this.getShape(x,y,hitW,hitH);
}
 
p.getShape = function (x,y,hitW,hitH) {
    this.graphics.clear();
    this.set({x:x, y:y});
    this.color = this.graphics.s("blue").command;
    this.graphics.ss(3, "round").sd([12,12]).f("#ddd").dr(0,0,hitW,hitH);
}
 
 
p.hitRect = function (shape) {
 
    if (shape.x >= this.x-shape.width && shape.x <= this.x+this.hitW 
        && shape.y >= this.y-shape.height && shape.y <= this.y+this.hitW) {
       return true;
    } 
   return false;
 
}
 
p.hitTestPoint = function (x,y,shape) {
 
if((-x < shape.width) && (0 <= -x+this.hitW) && (-y < shape.height) && (0 <= -y+this.hitH))
  {
        return true;    
  }
return false;
 
    
}
 
window.hitObject = createjs.promote(hitObject, "Shape");
}(window));
 
 
$(document).ready(function init() {
  var canvas = document.getElementById('canvas1'),
  stage = new createjs.Stage(canvas);
  
  
    var shapeW = 50, hitW = 100;
    
    var hit1 = new hitObject(100,150,hitW,hitW);
    
    var hit2 = new hitObject(250,150,hitW,hitW);
    
    var hit3 = new hitObject(400,150,hitW,hitW);
    
 
  
    var shape = new createjs.Shape().set({x:175, y:10, cursor:"pointer", alpha:0.75});
    shape.graphics.f("#906").dr(0,0,shapeW,shapeW);
    shape.width = shapeW;
    shape.height = shapeW;
    shape.on("pressmove", handleDrag);
  
 
 
    stage.addChild(hit1,hit2,hit3, shape);
    stage.update();
  function handleDrag(event) {
   
    shape.x = event.stageX-shapeW/2;
    shape.y = event.stageY-shapeW/2;
    
    
   var pt1 = hit1.localToLocal(shape.x-hit1.x,shape.y-hit1.y,hit1);
    
  
  
   if (hit1.hitTestPoint(pt1.x, pt1.y,shape)) {
      hit1.color.style = "green";
    } else {
      hit1.color.style = "blue";
    }
   
   
    if (hit2.hitRect(shape)) {
      hit2.color.style = "green";
    } else {
     hit2.color.style = "blue";
    }
    
    if (shape.x >= hit3.x-shapeW && shape.x <= hit3.x+hitW 
        && shape.y >= hit3.y-shapeW && shape.y <= hit3.y+hitW) {
      hit3.color.style = "green";    
    } else {
      hit3.color.style = "blue";
    }
  }
 
 
  function onTick() {
    
 
 
    stage.update();
  }
 
  createjs.Ticker.setFPS(60);
  createjs.Ticker.addEventListener("tick", onTick);
 
});
 
    </script>
 
  
</body>
 
</html>
Еще более года назад я делала платформер без использования библиотек. Там есть пример столкновение объектов. Может пригодиться. Вот репост кода: Платформер на Canvas API и WebGL
0
383 / 23 / 2
Регистрация: 12.06.2021
Сообщений: 211
Записей в блоге: 2
14.05.2024, 10:22
Взяв за основу столкновение объектов из 25 поста я сделала небольшой платформер. Здесь один уровень, но есть трамплин, который увеличивает дальность прыжка.


Вот исходники. Анимация трамплина находитя в папке assets.
Platformer.zip
1
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
14.05.2024, 18:56
Доделал демку на Phaser 3 и JavaScript по глобальной сети с мультиплеером. Можно походить и попрыгать в браузере: https://walk-and-jump-with-mul... glitch.me/ Сервер авторитарный. На сервере физика на Box2D-WASM и вся игровая логика, а клиент просто отображает картинки и спрайтовую анимацию. На клиенте может быть что-угодно: EaselJS, Phaser, Three.js, libGDX, SFML, Godot, Unity, Unreal Engine и т.д. Туториал по платформеру на Phaser 3 на официальном сайте: Making your first Phaser 3 game

Исходники сервера и клиента на бесплатном хостинге Glitch

Вложения
Тип файла: zip walk-and-jump-with-multiplayer-box2dwasm-phaser3-js.zip (198.5 Кб, 2 просмотров)
2
403 / 19 / 5
Регистрация: 17.01.2017
Сообщений: 572
22.05.2024, 11:41  [ТС]
8Observer8, я еще не использовала JavaScript для написания игры с мультиплеерном режимом. Зато использовала пример платформер который привели в 36 посте. Сделала игру.
Код не слишком складно написано, в функциях много разных ненужных свойств. Это все потому, что при написании я меняла структуру добавляя новые возможности. Перепишу код позже.
Описание игры:
Два игрока на одной локации, почти как в посте выше (37 пост). Только без мультиплеера. Игра на одном компьютере. Два робота стреляют смертельным лазером способный за один залп уничтожить технику врага.
Управление:
Игрок 1:
Стрелки – перемещение.
Стрельба – пробел.
Игрок 2:
WASD – перемещение.
Стрельба – клавиша F, от слова (Fire).
Особенности.
Луч стреляет вперед, вверх под углом 45 градусов. Это сделано на тот случай если противник будет в прыжке и чтобы его ЭФФЕКТНО сбить.
Чтобы направить луч в определенную сторону, нужно удерживать клавишу управление например: стрелка вверх и огонь у “игрока 1” луч будет направлен в потолок.
Под углом 45 градусов: вверх + вправо + огонь.
Как в файтинги, типа Mortal Kombat, для выполнения крутого удара нужно нажать комбинацию клавиш. Собственно вот пример игры (анимация) который выполнен с библиотекой Easeljs.

А вот код. Он слишком объемный (почти 1500 строк) поэтому опубликую как файл.
PlatformerForTwo.zip
1
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
22.05.2024, 16:34
Я вчера доделал игру с мультиплеером. Смысл её в том, чтобы набрать звёзд больше, чем соперники. Нужно было бы ещё вывести рекордный счёт на сеанс, чтобы было видно, кто набрал больше всех. Когда все звёзды собраны, то падают новые, а ещё появляется бомба, которая летает по всему экрану и если игрок с ней столкнётся, то он потеряет все очки и ему придётся собирать их заново. В этой игре нет предсказаний на клиенте и интерполяции других клиентов, а вообще надо. Для предсказаний клиента надо, чтобы на клиенской части тоже была запущена игра на Box2D-WASM, а спустя промежутки проводилась синхронизация с сервером. Но я решил пока не тратить на это время. Лучше подераю игровые демки для тренировки без предсказаний на клиенте и интерполяции других игроков.

На Node.js сервере использую библиотеку "ws": ws: a Node.js WebSocket library. Это невероятно популярная библиотека. За неделю её скачивают 74 милиона раз!



Игра на бесплатном хостинге Node.js Glitch и исходники:

Игра получилась в результате перевода следующиго туториала на Box2D-WASM и мультиплеер: Making your first Phaser 3 game



Миниатюры
Вложения
Тип файла: zip making-your-first-multiplayer-game-box2dwasm-phaser3-js-main.zip (518.4 Кб, 0 просмотров)
1
9953 / 2954 / 497
Регистрация: 05.10.2013
Сообщений: 8,075
Записей в блоге: 242
22.05.2024, 17:44
Следующую демку с Марио на бесплатных ассетах я написал на С++ на чистом OpenGL ES 2.0 с использованием C++-фреймворка Qt 6. Собрал исполняемые файлы для Android, Windows и WebAssembly (для запуска в браузере). В демке использую Box2D для: передвижения, прыжка, определения столкновений и пуска лучей. Добавил Box2D в проект прямо исходниками. Box2D имеет класс b2Draw переопределив методы которого можно рисовать коллайдеры имея координаты вершин, которые выдают методы класса b2Draw. Добавление Box2D исходниками позволяет собирать из одной кодовой базы для Android, Desktop и APK. Подключил библиотеку OpenAL-Soft для музыки и звуков. Подключил OpenAL-Soft для Desktop можно собрать в WebAssembly и будет работать на Web - видимо OpenAL транслируется в Web Audio API. На OpenAL и Web Audio API можно делать 3D звуки, то есть можно слышать где находится источник звука в том числе на Android если телефон поддерживает стерио - особенно это хорошо работает в наушниках. Спрайты упаковал в один атлас с помощью бесплатной программы Free Texture Packer (сайт открывается через VPN), а карту нарисовал и расставил статические коллайдеры в бесплатном редакторе игровых карт Tiled Map Editor. Очень рекомендую скачать эти программы. Особенно Tiled - очень упращает и ускоряет создание игровых уровней. Их можно использовать для любых игровых библиотек, фреймворков и движков. Эти программы экспортируют в JSON, для которого есть встроенный парсер в Qt. Кнопки нарисовал на чистом OpenGL ES 2.0. Шрифт тоже рисуется на чистом OpenGL ES 2.0. Здесь текст с distance field. Можете в YouTube набрать "thinmatrix distance field" и найдете следующие видео: OpenGL 3D Game Tutorial 33: Distance Field Text Rendering, в начале которого на первых нескольких минутах поймёте, что это. Выводится текст на английском руссском и китайском языках.

Для записи gif-анимации вывел экран телефона на ноутбук с помощью бесплатной программы scrcpy, а анимацию записал с помощью бесплатной программы ScreenToGif



В демке используются бесплатные ассеты:

Миниатюры
Вложения
Тип файла: zip mario-2d-jumps-webfussel-opengles2-qt6-cpp.zip (9.19 Мб, 0 просмотров)
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
22.05.2024, 17:44

Столкновение объектов на странице
Всем привет! Предположим у меня есть два шарика, один статичный, просто стоит в определенном месте, а другой бегает по странице от...

JavaScript: столкновение объектов
Прошу спецов по Java подсказать или помочь доработать скрипт Зинковского (написан на Java и VBScript). Описание: игра-стрелялка,...

Как сделать столкновение объектов?
Как проверять, столкнулся ли один шар с другим? Первый шар двигается нажатием клавиши, а остальные находятся на рандомных позициях, как...

Как сделать, чтобы столкновение объектов было абсолютно неупругим
Нашел пример попиксельного столкновения. Работает прекрасно, но что делать в момент столкновения, если нужно, чтоб оно было абсолютно...

Столкновение объектов. Как правильно реализовать?
Здравствуйте! Пишу игру в танчики. Borland C++ 3.1. Сейчас реализовал работу с клавиатурой, ознакомиться можно здесь :...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
40
Ответ Создать тему
Новые блоги и статьи
сукцессия 25. Хронология ошибок
anaschu 12.07.2026
# От 50-тонного гриба до устойчивого леса: хроника ошибок при построении модели вековой сукцессии микоризы ## О чём эта статья В процессе построения ОДУ-модели (система дифференциальных. . .
сукцессия 24. Промежуточное общее описание модели
anaschu 12.07.2026
Хендофф: модель АМ→ЭКМ сукцессии микоризы (ризосфера, 50 лет) Содержание проекта Симуляция вековой (50 лет) экологической сукцессии в почве леса Основные участники: АМ-гриб, ЭКМ-гриб,. . .
сукцессия 23. Более физиологичная физиология, более экологичная экология, более диффурные диффуры.
anaschu 12.07.2026
Что реально нашли и починили за эти 5 часов Правило Линдемана (КПД конверсии сахара в тело, kEff) — раньше 100% полученного углерода шло прямо в биомассу гриба; теперь только kEff=0. 5 (после. . .
сукцессия 22. От артефактов к физиологии: калибровка агентной модели грибной сукцессии для воспроизведения сезонной динамики и pH-плато
anaschu 11.07.2026
Аннотация В данной работе представлена калибровка агентной модели динамики грибных сообществ (fungal-succession), направленная на устранение нефизичных артефактов (коллапс биомассы, мгновенное. . .
Сукцессия 20. Война автоботов. Делаем ставки. Лёд против "пш-пш!".
anaschu 11.07.2026
Битва ИИ в ризосфере: Как мы скрестили жесткие ОДУ, закон Фика и «подземный шантаж» Уважаемые коллеги! Хочу поделиться уникальным опытом ведения междисциплинарной компьютерной разработки. Прямо. . .
Сукцессия 19. Какие выводы я сделал из модели? Часть 2.Внутримикоризный стехиометрический буфер и хроно-дискретные зоны экспансии
anaschu 11.07.2026
Био-Инженерный Ликбез: Архитектура Модели Ризосферы Математический аппарат моделирования
Сукцессия 18. Какие выводы я сделал из войны грибов с деревьями? Часть 1- рассказ и немного про термины
anaschu 11.07.2026
Био-Инженерный Ликбез: Архитектура Модели Ризосферы Математический аппарат моделирования Система ОДУ описывает динамику изменения массы различных компонентов системы во времени. Ключевой. . .
Просветление в 5 секунд
kumehtar 10.07.2026
Андрей Веретенников выдал фразу недавно: "Вам не обязательно кем-то себя считать"
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru