簡體   English   中英

使用JavaScript進行碰撞檢測

[英]Collision Detection using javascript

我是日本的一名高中生,試圖學習編程。 我最近觀看了此視頻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');
    });
})();

我已注釋掉視頻中女士使用的碰撞功能,因為我不太確定如何使用它來滿足我的需求。 如果有人能指出我的思考方向,將不勝感激。

這很簡單。

在某些時候(通常當對象的位置發生變化時),您需要檢查碰撞。 為此,您可以利用給定的功能。

演示

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比paddle更易讀)
  • 調試代碼(了解JS的工作方式以及代碼為什么不做應有的作用的一種好方法是使用調試器並逐步檢查出什么問題。每種瀏覽器都有一些內置的功能,大多數情況下,您可以按F12訪問它。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM