首页 > 解决方案 > 如何使用键盘输入根据 x 和 y 坐标使画布中的对象移动?

问题描述

这是我第一次在 StackOverflow 上提问。我想知道如何通过键盘输入根据其 x 和 y 坐标移动对象。我正在为我的游戏制作基于网格的运动。对于任何错误的代码或格式,我深表歉意。我正在为学校项目制作网页游戏。如果您需要我的 html 代码,请发表评论。下面是我的代码:

 $(function(){
  var health = 800;
  var fuel = 100;
  var tankX = 25;
  var tankY = 530;

  var c = document.getElementById("gameCanvas");
  var ctx = c.getContext('2d');
  ctx.beginPath();
  ctx.fillStyle = "grey";
  ctx.fillRect(0,600,1110,100);
  ctx.stroke();

  for (i = 100; i < 600; i += 100) 
  {
     ctx.moveTo(0, i);
     ctx.lineTo(c.width, i);
     ctx.stroke();
  }

  for (i = 100; i < 1110; i += 100) 
  {
     ctx.moveTo(i, 0);
     ctx.lineTo(i,600);
     ctx.stroke();
  }

  ctx.fillStyle ="black";
  ctx.font = "20px  Lucida Sans Typewriter ";
  ctx.fillText("Health:",500,630);
  ctx.fillText("Fuel:", 100,630);
  ctx.fillStyle = "green";
  ctx.fillRect(500,640,(health/800)*250,40);

  function fuelGauge(){
   ctx.fillStyle="yellow";
   ctx.fillRect(100,640,(fuel/100)*250,40);
   console.log(fuel);
 }

 function drawTank(){
     ctx.fillStyle = "#283618"
     ctx.fillRect(tankX,tankY,50,50);
     ctx.moveTo(tankX,tankY);
 }

 drawTank();
 fuelGauge();

});

标签: javascript

解决方案


我不做很多jquery,但由于没有人回答,这里有一个例子。它使用该keydown事件来监听箭头键。我敢肯定还有很大的改进空间,但它应该让你开始。

var c = document.getElementById("gameCanvas");
var ctx = c.getContext('2d');

var tankX = 25;
var tankY = 530;
var health = 800;
var fuel = 100;

$('html').keydown(function(e){
  eraseTank();

  if (e.key == "ArrowUp") {
    if (tankY > 15) tankY -= 102;
  }
  else if (e.key == "ArrowDown") {
    if (tankY < 530) tankY += 102;
  }
  else if (e.key == "ArrowLeft") {
    if (tankX > 25) tankX -= 100;
  }
  else if (e.key == "ArrowRight") {
    if (tankX < 525) tankX += 100;
  }

  drawTank();
});

function fuelGauge(){
 ctx.fillStyle="yellow";
 ctx.fillRect(100,640,(fuel/100)*250,40);
 console.log(fuel);
}

function drawTank(){
   ctx.fillStyle = "#283618"
   ctx.fillRect(tankX,tankY,50,50);
   ctx.moveTo(tankX,tankY);
}
function eraseTank(){
   ctx.fillStyle = "white"
   ctx.fillRect(tankX,tankY,50,50);
   ctx.moveTo(tankX,tankY);
}

function drawGame()
{
  ctx.beginPath();
  ctx.fillStyle = "grey";
  ctx.fillRect(0,600,1110,100);
  ctx.stroke();

  for (i = 100; i < 600; i += 100) 
  {
     ctx.moveTo(0, i);
     ctx.lineTo(c.width, i);
     ctx.stroke();
  }

  for (i = 100; i < 1110; i += 100) 
  {
     ctx.moveTo(i, 0);
     ctx.lineTo(i,600);
     ctx.stroke();
  }

  ctx.fillStyle ="black";
  ctx.font = "20px  Lucida Sans Typewriter ";
  ctx.fillText("Health:",500,630);
  ctx.fillText("Fuel:", 100,630);
  ctx.fillStyle = "green";
  ctx.fillRect(500,640,(health/800)*250,40);
}

$(function(){
  drawGame();
  fuelGauge();
  drawTank();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<canvas id="gameCanvas" width="600" height="1100"></canvas>

运行代码段时,请确保先单击游戏板。


推荐阅读