使用javascript进行碰撞检测

时间:2014-10-14 06:04:53

标签: javascript collision-detection

我是日本的高中生,正在学习如何编程。我最近查看了https://vimeo.com/105955605这个视频,并决定我可以使用开头部分开始在javascript中构建pong。

我几乎是编程和/或javascript的新手,我还有很长的路要走。

我进入了碰撞检测部分,我似乎无法正确识别语法,因为事情停止加载,或者球离开屏幕。

视频中的女士一旦发生碰撞就会删除物品,但我希望球朝相反的方向移动。在这一点上,我没有考虑根据桨叶或桨叶速度的部分来改变球的速度。

这是我的HTML

<html>
 <head>
  <meta charset="UTF-8">
  <title>Pong</title>
  <link type="text/css" rel="stylesheet" href="css/stylesheet.css">
 </head>
 <body>
  <h1>Pong</h1><br/>
  <input type="button" id="start" value="Click To Begin"/> <br/>
  <canvas id="screen" width="310" height="210"></canvas>
  <script src="js/pong.js"></script>
 </body>
</html>

这是我的js代码。

(function(){ // It was there all along, just not formated correctly for the code block thingie on SO
    //Main game function
    //tells objects in bodies array to update.
    //stores gameSize pulled from canvasId
    var Game = function(canvasId){
        var canvas = document.getElementById(canvasId);
        var screen = canvas.getContext('2d');
        var gameSize = {x: canvas.width, y: canvas.height};
        var self = this;
//bodies array
        this.bodies = [new Player1(this, gameSize), new Player2(this, gameSize),new Ball(self, gameSize)];
//update function
        var tick = function(){
        self.update();
        self.draw(screen,gameSize);
        requestAnimationFrame(tick);
        };
        tick();
    };
//constructor for game() function. tells bodies to update, and draw
    Game.prototype = {
        update: function(){
 //           new collision(this.bodies[2],this.bodies[1]);
 //           new collision(this.bodies[2],this.bodies[0]);
            for(var i =0 ; i < this.bodies.length; i++){
                this.bodies[i].update();
            }
        },
        draw:function(screen,gameSize){
            screen.clearRect(0,0,gameSize.x,gameSize.y);
            for(var i =0 ; i < this.bodies.length; i++){
                drawRect(screen, this.bodies[i]);
            }
        }
    };
//P1 object, declares size and start position of P1
    var Player1= function(game, gameSize){
        this.size = {x:30,y:gameSize.y / 3};
        this.game = game;
        this.gameSize = gameSize;
        this.center = {x: 0, y:gameSize.y/2};
        this.keyboarder = new Keyboarder();
       requestAnimationFrame(this.update);
    };
//constructor for P1, updates position based on keyboard input
    Player1.prototype = {
        update:function(){
            if (this.keyboarder.isDown(this.keyboarder.KEYS.S) && this.center.y < (5*this.gameSize.y / 6)){
               this.center.y += 4;
            }else if(this.keyboarder.isDown(this.keyboarder.KEYS.W) && this.center.y > this.size.y /2 ){
                this.center.y -= 4;
            }
        }
    };
//P2, same as P1 aside from position
    var Player2= function(game, gameSize){
        this.size = {x:30,y:gameSize.y / 3};
        this.game = game;
        this.gameSize = gameSize;
        this.center = {x: gameSize.x, y:gameSize.y/2};
        this.keyboarder = new Keyboarder();
        requestAnimationFrame(this.update);
    };
//constructor for P2, same as P1
    Player2.prototype = {
        update:function(){
            if (this.keyboarder.isDown(this.keyboarder.KEYS.DOWN) && this.center.y < (5*this.gameSize.y / 6)){
                this.center.y += 4;
            }else if(this.keyboarder.isDown(this.keyboarder.KEYS.UP) && this.center.y > this.size.y /2 ){
                this.center.y -= 4;
            }
        }
    };
//Ball function, gives ball random velocity, tells it to start at the center.
    var Ball = function(game , gameSize){
        var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
        var rand = Math.random();
        this.velocity = {x: plusOrMinus * (3 + Math.random()) * rand , y: plusOrMinus * (1 + Math.random()) * rand };
        this.size = {x : 15, y : 15 };
        this.center = {x: gameSize.x /2 , y: gameSize.y /2};
        this.gameSize = gameSize;

    };
//Ball constructor, tells ball to bounce and add velocity.
    Ball.prototype = {
        update: function () {
            if(this.center.x < 0 || this.center.x > this.gameSize.x) {
                this.velocity.x = -this.velocity.x + (-this.velocity.x * 0.1);
            };
        this.center.x += this.velocity.x;
        if(this.center.y < 0 || this.center.y > this.gameSize.y) {
            this.velocity.y = -this.velocity.y + (-this.velocity.y * 0.1);
        };
        this.center.y += this.velocity.y;
         requestAnimationFrame(this.update);
        }
    };

//Draw function, draws object
    var drawRect = function(screen, body){
        screen.fillRect(body.center.x - body.size.x /2,
                body.center.y - body.size.y /2, body.size.x,body.size.y);
    };
//Keyboard input function
    //reads if keys are being pressed and takes the event code
    //isDown() returns boolean of key down = true, key up = false
    var Keyboarder = function(
        ){
        var keyState = {};

        window.addEventListener('keydown' , function(e){
            keyState[e.keyCode] = true;
        });
        window.addEventListener('keyup' , function(e){
            keyState[e.keyCode] = false;
        });
        this.KEYS = {DOWN: 40, UP:38,W:87 , S: 83};

        this.isDown = function(keyCode){
            return keyState[keyCode] === true;
        };

    };

/*    var collision = function (b1, b2) {
       if(
           b1 === b2 ||
           b1.center.x + this.size.x /2 < b2.center.x + b2.size.x /2 ||
           b1.center.y + this.size.y /2 < b2.center.y + b2.size.y /2 ||
           b1.center.x - this.size.x /2 > b2.center.x - b2.size.x /2 ||
           b1.center.y - this.size.y /2 > b2.center.y - b2.size.y /2
           ){

            }else{
                b1.velocity.x = -b1.velocity.x + (-b1.velocity.x * 0.1);
            };

    };
*/
//calls game() function when button is pressed
    var start = document.getElementById('start');
    start.addEventListener('click' , function(e){
       new Game('screen');
    });
})();

我已经评论了视频中女士使用的碰撞功能,因为我不太清楚如何根据我的需要使用它。如果有人能指出我的思考方向,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

这很简单。

在某些时候(通常当您的对象的位置发生变化时),您需要检查是否有碰撞。为此,您可以使用给定的功能。

<强> DEMO

var collision = function (ball, paddle) {      
   if(
      ((ball.center.y +  (ball.size.y / 2)) < (paddle.center.y - (paddle.size.y / 2))) || //ball is under paddle
      ((ball.center.y -  (ball.size.y / 2)) > (paddle.center.y + (paddle.size.y / 2))) || //ball is over paddle
      ((ball.center.x +  (ball.size.x / 2)) < (paddle.center.x - (paddle.size.x / 2))) || //ball is left from the paddle
      ((ball.center.x -  (ball.size.x / 2)) > (paddle.center.x + (paddle.size.x / 2))) //ball is right from the paddle 
   ){
        //no collision
   }else{
     alert("collision");
     ball.velocity.x = -ball.velocity.x + (-ball.velocity.x * 0.1);
   }
};

一些提示:

  • 使用专有名称(球比b1更易读,比b2更多)
  • 调试代码(理解JS如何工作的好方法以及为什么你的代码不应该使用调试器并逐步检查什么是错误的。每个浏览器都有一些内置的功能,以及大多数情况下,按F12即可访问它。)