Aby dodać strzelanie do poprzedniej aplikacji musimy

– dodać klawisz strzału w pliku keyboard.js (kod 32) na końcu,
– Musimy dodać teksturę strzału, ukryć strzał, zrobić dodatkową zmienną strzela:
– Dodać zmienną globalną

1
2
var strzela=false;
var szybkosc_strzalu=3;

-oprócz tego w zegarze (app.ticker.add na końcu) dodajemy:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
......
if (spacja.isDown && !strzela) //STRZAL
        {
                strzela = true;
                pocisk.x = hero.x;
                pocisk.y = hero.y;
                pocisk.visible = true;
        }
if (strzela)
        {
                pocisk.y-= szybkosc_strzalu;
                if (pocisk.y < -1000)
                {
                        pocisk.visible = false;
                        strzela = false;
                }
        }

Trafianie do celu zrobimy przy pomocy funkcji sprawdzającej KOLIZJĘ (ze strony kursu PIXIE):

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
function hitTestRectangle(r1, r2) {

  //Define the variables we'll need to calculate
  var hit, combinedHalfWidths, combinedHalfHeights, vx, vy;

  //hit will determine whether there's a collision
  hit = false;

  //Find the center points of each sprite
  r1.centerX = r1.x + r1.width / 2;
  r1.centerY = r1.y + r1.height / 2;
  r2.centerX = r2.x + r2.width / 2;
  r2.centerY = r2.y + r2.height / 2;

  //Find the half-widths and half-heights of each sprite
  r1.halfWidth = r1.width / 2;
  r1.halfHeight = r1.height / 2;
  r2.halfWidth = r2.width / 2;
  r2.halfHeight = r2.height / 2;

  //Calculate the distance vector between the sprites
  vx = r1.centerX - r2.centerX;
  vy = r1.centerY - r2.centerY;

  //Figure out the combined half-widths and half-heights
  combinedHalfWidths = r1.halfWidth + r2.halfWidth;
  combinedHalfHeights = r1.halfHeight + r2.halfHeight;

  //Check for a collision on the x axis
  if (Math.abs(vx) < combinedHalfWidths) {

    //A collision might be occuring. Check for a collision on the y axis
    if (Math.abs(vy) < combinedHalfHeights) {

      //There's definitely a collision happening
      hit = true;
    } else {

      //There's no collision on the y axis
      hit = false;
    }
  } else {

    //There's no collision on the x axis
    hit = false;
  }

  //`hit` will be either `true` or `false`
  return hit;
};