首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Javascript画布“游戏”。英雄只移动一次

Javascript画布“游戏”。英雄只移动一次
EN

Stack Overflow用户
提问于 2018-10-09 04:50:50
回答 2查看 83关注 0票数 1

我试着在画布上做一个简单的游戏。我使用setTimeout()函数为英雄制作了动画。我用moove(E)功能检查按下的键:

当我第一次按下leftarrow或rightarrow时,一切都很正常,但是英雄没有移动。任何对代码的建议都是值得感谢的。

代码语言:javascript
复制
var cns = document.getElementById("can");
cns.height = 600;
cns.width = 300;
var ctx = cns.getContext("2d");
var hero = new Image();
hero.src = "images/hero.png";
hero.onload = function() {
  ctx.drawImage(hero, 120, 570);
  hero.xx = 120;
  hero.yy = 570;
};

var intervalL, intervalR, intervalLL, intervalRR;
var keys = [];

function moove(e) {
  keys[e.keyCode] = (e.type == "keydown");
  if (keys[37]) {
    clearTimeout(intervalR);
    clearTimeout(intervalRR);
    goLeft(hero);
  } else {
    clearTimeout(intervalL);
    clearTimeout(intervalLL);
  }
  if (keys[39]) {
    clearTimeout(intervalL);
    clearTimeout(intervalLL);
    goRight(hero);
  } else {
    clearTimeout(intervalR);
    clearTimeout(intervalRR);
  }
}

function goLeft(img) {
  var x = img.xx,
    y = img.yy;

  function f() {
    ctx.clearRect(img.xx, img.yy, img.width, img.height);
    ctx.drawImage(img, x, y);
    img.xx = x;
    img.yy = y;
    x -= 1.2;
    if (x < -35) {
      x = cns.width;
    }
  }
  if (!intervalL) {
    intervalL = setTimeout(function run() {
      f();
      intervalLL = setTimeout(run, 5);
    }, 5);
  }
}

函数goRight类似于goLeft。

在标记体onkeydown=' moove (event)‘onkeyup='moove(event)’中调用moove函数。

您可以在此处查看该项目:https://github.com/Fabulotus/Fabu/tree/master/Canvas%20game%20-%20dodge%20and%20jump

EN

回答 2

Stack Overflow用户

发布于 2018-10-09 05:16:42

第一次不起作用的原因是,第一次将位置设置为之前的位置(x = image.xx),然后在绘制后更新x。应该在调用drawImage之前更新x值x -= 1.2

票数 0
EN

Stack Overflow用户

发布于 2018-10-10 20:53:12

下面是你的代码的“工作”版本:

代码语言:javascript
复制
var cns = document.getElementById("can");
cns.height = 170;
cns.width = 600;
var ctx = cns.getContext("2d");
var hero = new Image();
hero.src = "http://swagger-net-test.azurewebsites.net/api/Image";
hero.onload = function() {
  ctx.drawImage(hero, cns.width-10, cns.height/2);
  hero.xx = cns.width-10;
  hero.yy = cns.height/2;
};

var intervalL, intervalR, intervalLL, intervalRR;
var keys = [];


function goLeft(img) {
  function f() {
    ctx.beginPath()
    ctx.clearRect(0, 0, cns.width, cns.height);
    ctx.drawImage(img, img.xx, img.yy);
    img.xx--;      
    if (img.xx < -img.width) {
      img.xx = cns.width;
    }
  }
  if (!intervalL) {
    intervalL = setTimeout(function run() {
      f();
      intervalLL = setTimeout(run, 5);
    }, 5);
  }
}

goLeft(hero)
代码语言:javascript
复制
<canvas id="can">

正如您所看到的,function goLeft已经大大简化了。

一个建议:避免太多的setTimeoutclearTimeout,而是使用一个setInterval来调用一个绘制函数,该函数负责绘制游戏上的所有内容,所有其他函数应该只更新gameObjects的位置。

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

https://stackoverflow.com/questions/52709927

复制
相关文章

相似问题

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