当位图与另一个位图发生碰撞时停止它

时间:2014-12-05 21:47:42

标签: javascript collision-detection easeljs createjs

我目前正在学习CreateJS,并且正在处理我正在处理的游戏的问题。

我发现了键盘移动和碰撞检测,但没有发现位图碰撞后会发生什么。现在他们只是互相通过,控制台记录影响。我想要发生的是当玩家(位图)撞到墙壁(位图)时,玩家再也不能朝那个方向移动了。

有人可以帮忙吗?

<script type="text/javascript">

var stage;  //Big, root level container for all display objects

//Assign the keycodes to readable variables
var KEYCODE_A = 65;
var KEYCODE_D = 68;
var KEYCODE_W = 87;
var KEYCODE_S = 83;

alphaThreshold = 1;

function init(){
    stage = new createjs.Stage("myCanvas");

    startGame();
}

function startGame(){
    //Load the bitmaps
    player = new createjs.Bitmap("assets/player-square.jpg");
    player.x = 10;
    player.y = 200;
    stage.addChild(player);

    mazeSquare = new createjs.Bitmap("assets/maze-test.png");
    mazeSquare.x = 250;
    mazeSquare.y = 0;
    stage.addChild(mazeSquare);

    //move the player, by listening to what key is pressed
    window.addEventListener('keydown', keyPressed, true);

    stage.update();
}

function keyPressed(event) {

    switch(event.keyCode) {
        case KEYCODE_W:
            //console.log("move up");
            if(player.y > 0){
                player.y -= 10;
                }
            break;  
        case KEYCODE_S:
            //console.log("move down");
            if(player.y < 430){  //stage height - square height
                player.y += 10;
                }
            break;
        case KEYCODE_A:
            //console.log("move left");
            if(player.x > 0){  //stage height - square height
                player.x -= 10;
                }
            break;
        case KEYCODE_D:
            //console.log("move right");
            if(player.x < 730){  //stage height - square height
                player.x += 10;
                }
            break;
    }

    //check for collisions after button press
    checkCollision();

    stage.update();
}

function checkCollision(keyPressed) {
    //Collision-Detection-for-EaselJS
    var intersection = ndgmr.checkPixelCollision(player, mazeSquare, alphaThreshold);

    //If the the intersection is not empty, that's because there was a collision.
      if (!intersection) {
         console.log("No Impact");

      } else {
          console.log("Impact");

      } //end else
}
</script>

</head>

<body onLoad="init();">

<center>
<canvas id="myCanvas" width="800" height="500" style="border: 1px solid #000000; background-image: url(assets/grass.png);">
Your browser does not support the HTML5 canvas tag.
</canvas>
<br>
W  S  A  D - Moves the player
</center>

0 个答案:

没有答案