模拟onmouseup事件到画布

时间:2017-09-25 18:18:29

标签: html5 html5-canvas

我有一个带有canvas对象的简单HTML5,我只需要在代码下面的按钮上添加相同的事件复制 -
正如你可以看到按下按钮,画布调用 accele() onmouseUp 事件再次使用不同的参数调用该函数,画布停止向上并从重力开始
我想在触摸屏中使用,唯一的问题是 OnmuseUp ,我不知道如何管理

这是代码:

var myGamePiece;
var myObstacles = [];
var myScore;

function startGame() {
    myGamePiece = new component(30, 30, "red", 10, 120);
    myGamePiece.gravity = 0.05;
    myScore = new component("30px", "Consolas", "black", 280, 40, "text");
    myGameArea.start();
}

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.frameNo = 0;
        
        	this.canvas.addEventListener('click', function() {accelerate(-0.2);}, false); 
          
        updateGameArea();
        },
    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

function component(width, height, color, x, y, type) {
    this.type = type;
    this.score = 0;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;    
    this.x = x;
    this.y = y;
    this.gravity = 0;
    this.gravitySpeed = 0;
    this.update = function() {
        ctx = myGameArea.context;
        if (this.type == "text") {
            ctx.font = this.width + " " + this.height;
            ctx.fillStyle = color;
            ctx.fillText(this.text, this.x, this.y);
        } else {
            ctx.fillStyle = color;
            ctx.fillRect(this.x, this.y, this.width, this.height);
        }
    }
    this.newPos = function() {
        this.gravitySpeed += this.gravity;
        this.x += this.speedX;
        this.y += this.speedY + this.gravitySpeed;
        this.hitBottom();
    }
    this.hitBottom = function() {
        var rockbottom = myGameArea.canvas.height - this.height;
        if (this.y > rockbottom) {
            this.y = rockbottom;
            this.gravitySpeed = 0;
        }
    }
    this.crashWith = function(otherobj) {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);
        var crash = true;
        if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
            crash = false;
        }
        return crash;
    }
}

function updateGameArea() {
    var x, height, gap, minHeight, maxHeight, minGap, maxGap;
    for (i = 0; i < myObstacles.length; i += 1) {
        if (myGamePiece.crashWith(myObstacles[i])) {
            return;
        } 
    }
    myGameArea.clear();
    myGameArea.frameNo += 1;
    if (myGameArea.frameNo == 1 || everyinterval(150)) {
        x = myGameArea.canvas.width;
        minHeight = 20;
        maxHeight = 200;
        height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
        minGap = 50;
        maxGap = 200;
        gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
        myObstacles.push(new component(10, height, "green", x, 0));
        myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
    }
    for (i = 0; i < myObstacles.length; i += 1) {
        myObstacles[i].x += -1;
        myObstacles[i].update();
    }
    myScore.text="SCORE: " + myGameArea.frameNo;
    myScore.update();
    myGamePiece.newPos();
    myGamePiece.update();
}

function everyinterval(n) {
    if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
    return false;
}

function accelerate(n) {
    if (!myGameArea.interval) {myGameArea.interval = setInterval(updateGameArea, 20);}

    myGamePiece.gravity = n;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
    border:1px solid #d3d3d3;
    background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">

<br>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p>Click the ACCELERATE button to start the game</p>
<p>How long can you stay alive? Use the ACCELERATE button to stay in the air..</p>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

不是使用事件监听器来驱动游戏,而是使用事件监听器来跟踪输入状态。

例如

canvas.addEventListener("mousedown",inputEvent);
canvas.addEventListener("touchstart",inputEvent);
const input = {
   active : false;
}
function inputEvent(){
   input.active = true;
}

然后,而不是使用setInterval(你不应该用于动画)创建一个主循环函数

function mainLoop(){
    // see answer below
    requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame

这将每1/60秒开始调用一次。在此,您可以监视输入并根据游戏状态执行所需操作。

const thrust = -0.4;
const gravity = 0.1;
var inplay = false; // when true game is playing.
function mainLoop(){
    if(input.active && !inplay){
        inplay = true;
        input.active = false;  // clear the input
    }
    if(inplay){
        if(input.active){  // input 
            myGamePiece.speedY += thrust;
            input.active = false; // clear input
        }
        updateGameArea();  // call the render game function.
    }

    requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame

您需要更改移动功能

你有

this.newPos = function() {
    this.gravitySpeed += this.gravity;
    this.x += this.speedX;
    this.y += this.speedY + this.gravitySpeed;
    this.hitBottom();
}

更改为

this.newPos = function() {
    this.speedY += gravity;
    this.x += this.speedX;
    this.y += this.speedY;
    this.hitBottom();
}

或者您可以更改输入以推动某些帧

const input = {
   active : 0;
}
const thrustFrameCount = 4;
function inputEvent(){
   input.active = thrustFrameCount;
}

并将主循环更改为

const thrust = -0.1;
const gravity = 0.1;
var inplay = false; // when true game is playing.
function mainLoop(){
    if(input.active > 0 && !inplay){
        inplay = true;
        input.active = 0;  // clear the input
    }
    if(inplay){
        if(input.active > 0){  // input 
            myGamePiece.speedY += thrust * input.active;
            input.active -= 1; // count down input on.
        }
        updateGameArea();  // call the render game function.
    }

    requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame

一切都有点像这样,你的游戏代码有点过于复杂,所以我已经破解了一个快速模式给你一个例子,说明我在上面的答案中的含义。

&#13;
&#13;
var myGamePiece;
var myObstacles = [];
var myScore;

function startGame() {
    myGamePiece = new component(30, 30, "red", 10, 120);

    myScore = new component("30px", "Consolas", "black", 280, 40, "text");
    myGameArea.start();
}

var myGameArea = {
    canvas : canvas,
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        
        this.frameNo = 0;
        updateGameArea();
        },
    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

function component(width, height, color, x, y, type) {
    this.type = type;
    this.score = 0;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;    
    this.x = x;
    this.y = y;
    this.gravity = 0;
    this.gravitySpeed = 0;
    this.update = function() {
        ctx = myGameArea.context;
        if (this.type == "text") {
            ctx.font = this.width + " " + this.height;
            ctx.fillStyle = color;
            ctx.fillText(this.text, this.x, this.y);
        } else {
            ctx.fillStyle = color;
            ctx.fillRect(this.x, this.y, this.width, this.height);
        }
    }
    this.newPos = function() {
        this.speedY += gravity;
        this.x += this.speedX;
        this.y += this.speedY;
        this.hitBottom();
    }
    this.hitBottom = function() {
        var rockbottom = myGameArea.canvas.height - this.height;
        if (this.y > rockbottom) {
            this.y = rockbottom;
            if(this.speedY > 0){
              this.speedY = 0;
            }
        }
    }
    this.crashWith = function(otherobj) {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);
        var crash = true;
        if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
            crash = false;
        }
        return crash;
    }
}

function updateGameArea() {
    var x, height, gap, minHeight, maxHeight, minGap, maxGap;
    for (i = 0; i < myObstacles.length; i += 1) {
        if (myGamePiece.crashWith(myObstacles[i])) {
            return;
        } 
    }
    myGameArea.clear();
    if (myGameArea.frameNo % wallFrameCount === 0 ) {
        x = myGameArea.canvas.width;
        minHeight = 20;
        maxHeight = 200;
        height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
        minGap = 50;
        maxGap = 200;
        gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
        myObstacles.push(new component(10, height, "green", x, 0));
        myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
    }
    for (i = 0; i < myObstacles.length; i += 1) {
        myObstacles[i].x += -1;
        myObstacles[i].update();
    }
    myScore.text="SCORE: " + myGameArea.frameNo;
    myScore.update();
    myGamePiece.newPos();
    myGamePiece.update();
    myGameArea.frameNo += 1;
    
}



canvas.addEventListener("mousedown",inputEvent);
canvas.addEventListener("touchstart",inputEvent);
const input = {active : 0 };
const thrustFrameCount = 4;
function inputEvent(){

    input.active = thrustFrameCount;
}
const wallFrameCount = 200;
const thrust = -0.4;
const gravity = 0.2;
var inplay = false; // when true game is playing.
function mainLoop(){
    if(input.active > 0 && !inplay){
        startGame();
        inplay = true;
        input.active = 0;  // clear the input
    }
    if(inplay){

    
        if(input.active > 0){  // input 
            myGamePiece.speedY += thrust * input.active;
            input.active -= 1; // count down input on.
        }
        updateGameArea();  // call the render game function.
    }

    requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame
&#13;
canvas {
    border:1px solid #d3d3d3;
    background-color: #f1f1f1;
}
&#13;
<canvas id="canvas" width="480" height="270"></canvas><br>
Click touch canvas to start.
&#13;
&#13;
&#13;