首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模拟onmouseup事件到画布

模拟onmouseup事件到画布
EN

Stack Overflow用户
提问于 2017-09-25 18:18:28
回答 1查看 84关注 0票数 0

我有一个带有画布对象的简单HTML5,我只需要在代码下面的按钮上添加相同的事件-

正如您所看到的按下按钮一样,画布调用 with ()onmouseUp事件,使用不同的参数再次调用该函数,画布停止上升,并以重力开始。

我想在触摸屏中使用,唯一的问题是我不知道如何管理的事件OnmuseUp

这是代码:

代码语言:javascript
复制
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;
}
代码语言:javascript
复制
<!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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-25 19:21:01

与其使用事件侦听器来驱动游戏,不如使用事件侦听器来跟踪输入状态。

例如

代码语言:javascript
复制
canvas.addEventListener("mousedown",inputEvent);
canvas.addEventListener("touchstart",inputEvent);
const input = {
   active : false;
}
function inputEvent(){
   input.active = true;
}

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

代码语言:javascript
复制
function mainLoop(){
    // see answer below
    requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame

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

代码语言:javascript
复制
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 =函数(){ this.gravitySpeed += this.gravity;this.y .x += this.speedX;this.y.y += this.speedY + this.gravitySpeed;this.hitBottom();}

变到

代码语言:javascript
复制
this.newPos = function() {
    this.speedY += gravity;
    this.x += this.speedX;
    this.y += this.speedY;
    this.hitBottom();
}

或者,您可以更改输入,使其在某些框架上具有推力。

代码语言:javascript
复制
const input = {
   active : 0;
}
const thrustFrameCount = 4;
function inputEvent(){
   input.active = thrustFrameCount;
}

并将主循环更改为

代码语言:javascript
复制
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

嗯,一切都是这样的,你的游戏代码有点过于复杂,所以我黑了一个快速的模式给你一个例子,我在上面的答案是什么意思。

代码语言:javascript
复制
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
代码语言:javascript
复制
canvas {
    border:1px solid #d3d3d3;
    background-color: #f1f1f1;
}
代码语言:javascript
复制
<canvas id="canvas" width="480" height="270"></canvas><br>
Click touch canvas to start.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46411713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档