JS函数仅在按下键时运行

时间:2014-12-17 01:05:53

标签: javascript html5 html5-canvas

所以我在画布上放了一些简单的碰撞检测代码:如果我的障碍汽车精灵碰到我的用户汽车精灵,那么障碍汽车会停下来。出于某种原因,当汽车靠近时,只有当我按下用户汽车用来移动的键(向上,向下,向左和向右箭头键)时才会检测到碰撞。无论我是按下按键移动,我怎样才能让这个功能一直工作?

碰撞检测代码:

//Collide test
function firstObstaclecollideTest () {
    if (Math.abs(x1 - (usercar.width / 2) - x) < usercar.width && Math.abs(y1 - (usercar.height / 2) - y) < usercar.height) {
    mod1 = 0;
    speed1 = 0;
    }
    requestAnimationFrame(firstObstaclecollideTest);
}
requestAnimationFrame(firstObstaclecollideTest);

function secondObstaclecollideTest () {
    if (Math.abs(x2 - (usercar.width / 2) - x) < usercar.width && Math.abs(y2 - (usercar.height / 2) - y) < usercar.height) {
    mod2 = 0;
    speed2 = 0;
    }
    requestAnimationFrame(secondObstaclecollideTest);
}
requestAnimationFrame(secondObstaclecollideTest);

完整代码:http://jsbin.com/dofihiwize/1/edit?output

1 个答案:

答案 0 :(得分:1)

我害怕你的代码有点混乱:
- 您正在触发4个动画循环:只有一个循环以避免头痛 - 你正在复制相当多的代码:去找一个汽车课来清理东西 - 有几个令人担忧的混乱:例如,绘制汽车的功能是清除画布,并绘制时间。函数名称也具有误导性(gameStart是游戏循环,......)。

更新小提琴在这里:

http://jsbin.com/bafulazose/1/edit?js,output

//Setting the canvas and context
var canvas = document.getElementById('background');
var context = canvas.getContext('2d');

//================
// CAR Class
//================

//Uploading obstacle car
var carImage = new Image();
carImage.src = "http://www.i2clipart.com/cliparts/f/e/3/a/128135fe3a51f073730a8d561282d05b4f35ab.png";

function Car(x, y, speed, mod, angle) {
    this.x = x; // x center of car
    this.y = y; // y center of car
    this.speed = speed;
    this.mod = mod;
    this.angle = angle;

    this.move = function () {
        this.x += (this.speed * this.mod) * Math.cos(Math.PI / 180 * this.angle);
        this.y += (this.speed * this.mod) * Math.sin(Math.PI / 180 * this.angle);
        if (this.y > context.canvas.height + 150) {
            this.y = -carImage.height;
            this.x = Math.floor(Math.random() * canvas.width);
        }
    };

    this.draw = function () {
        context.save();
        context.translate(this.x, this.y);
        context.rotate(this.angle* Math.PI / 180);
        context.drawImage(carImage, -(carImage.width / 2), -(carImage.height / 2));
        context.strokeRect(-(carImage.width / 2), -(carImage.height / 2), carImage.width , carImage.height);
        context.restore();
    };

  this.testCollision = function(other) {
    var dx = Math.abs(this.x - other.x   );
    var dy = Math.abs(this.y - other.y   );
    if ( dx < carImage.width && dy < carImage.height) {
        this.mod = 0;
        this.speed = 0;
    }
   };
}

//================
//ENTER: USER CAR
//================
var userCar  = new Car(450, 550, 10, -1, -90);
setupKeys(userCar);

//=====================
//ENTER: OBSTACLE CAR 1
//=====================

var obstacleCar1 ;

//======================
//ENTER: OBSTACLE CAR 2 
//======================

var obstacleCar2 ;

function setupGame () {
  obstacleCar1 = new Car(200, 5, 5, 1, 90);
  obstacleCar2 = new Car(340, 5, 5, 1, 90);
  gameOver = false;
  startTime = Date.now();
  score = 0;
}

//=========================
//Properties for score keep
//=========================
var score;
var startTime;
var gameOver;
var spaceBarPressed = false;

//=========================
// Launch the game
//=========================
setupGame () ;
var gameLoopInterval = setInterval(gameLoop, 30);

//===========================
//Draw Final and Elasped Time
//===========================
function drawElapsedTime() {
    context.save();
    context.fillStyle = "black";
    context.font = "30px Verdana";
    context.fillText(parseInt((Date.now() - startTime) / 1000) + " secs", canvas.width - 120, 40);
    context.restore();
}

function drawFinalScore() {
    context.save();
    context.fillStyle = "black";
    context.font = "30px Verdana";
    context.fillText("Game Over: " + score + " secs", 100, 100);
    context.font = "12px Verdana";
    context.fillText("Press space to restart", 190, 150);
    context.restore();
}

//========================
// Game loop
//========================

function gameLoop() {
    context.clearRect(0, 0, canvas.width, canvas.height);

    if (gameOver) {
      drawFinalScore();
      if (spaceBarPressed) {
         setupGame ();
      }
      return;
    }

    obstacleCar1.move();
    obstacleCar2.move();
    obstacleCar1.testCollision(userCar);
    obstacleCar2.testCollision(userCar);

    if (obstacleCar1.speed===0 && obstacleCar2.speed===0) {
       score = parseInt((Date.now() - startTime) / 1000);
       gameOver = true;
       spaceBarPressed = false;
    }

    obstacleCar1.draw();
    obstacleCar2.draw();

    userCar.draw();

    drawElapsedTime();
}

//========================
//  Keys handling
//========================

function setupKeys(target) {
    var cancelledKeys = [32, 37, 38, 39, 40];

    function keyUpHandler(event) {
        if (event.keyCode == 38 || event.keyCode == 40) {
            mod = 0;
        }
    }

    function keyDownHandler(event) {
        var keyCode = event.keyCode;
        if (keyCode == 37) {
            target.x -= target.speed;
        }
        if (keyCode == 39) {
            target.x += target.speed;
        }
              if (keyCode == 32) {
           spaceBarPressed =  true;
        }


        // space and arrow keys
        if (cancelledKeys.indexOf(keyCode) > -1) {
            event.preventDefault();
        }
    }

    //Event listeners for keys
    window.addEventListener("keydown", keyDownHandler, false);
    window.addEventListener("keyup", keyUpHandler, false);
}

编辑:
早晨咖啡改良(:-)):
- 移动是平滑的(requestAnimationFrame + position + = speed * time逝去)
- 正确处理钥匙
- 汽车具有干净的产卵功能
- 汽车现在处于一个“场景图”中。 (数组)所以我们可以测试交叉点 - 路!! (与roadPos,roadSpeed)

http://jsbin.com/zujecerehe/1/edit?js,output