简体   繁体   中英

How can I make my character move diagonally?

I am trying to create a game using HTML5 Canvas and Javascript and I am unable to figure out how to (correctly) make the character move diagonally after clicking the canvas with the mouse. I did manage to make the character move diagonally, but I can't set a speed so that regardless of the distance, it will move at the same speed... the further away you click, the faster it moves and the closer you click, the slower it moves. I want the speed to be the same regardless of where you click.

Here is what I have so far: http://pastebin.com/hUJBiQHq

How can I move the character diagonally on the canvas?

I actually went ahead and made quite a few changes. Ill try and go over each one.

The first thing I did was remove a lot of the setTimout calls. You don't really need a seperate one for movement and rendering. I also made it stop checking if the game was loaded after its actually loaded. Now once the game is loaded it will begin rendering.

You also had your onclick event inside of the timeout which wasn't needed. I moved it outside. A better approach and a subject for future reading would be using addEventListener explained nicely here

Another thing I added right at the top is a shim for requestAnimationFrame it is much better to use this over setTimeout and if you notice if it runs on a browser that doesn't support animation frame it will fallback on a timeout. There are many benefits to using it explained here .

Now onto the issue at hand!

 var tx = newX - posX,
     ty = newY - posY,

tx and ty are target x, and target y. They are the mouse coords subtracted from the player coords. You then can use these to perform a distance check like so,

dist = Math.sqrt(tx * tx + ty * ty);

Next I check if the distance is greater than the speed, if it is we need to move closer to our position.

if (dist >= speed) {

The next part calculates the velocity needed. We take the target x, and target y, and divide those by the distance which will give use the amount of pixels we need to travel to get to the target essentially. We then multiply this number by speed which gives us distance to move per tick. You then add these velocities to the players position to move the player (better explanation needed.. im terrible at explaining any math concepts :?)

    velX = (tx / dist) * speed;
    velY = (ty / dist) * speed;
    posX += velX;
    posY += velY;

Live Demo of it all working

Full Code

(function () {
  var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  window.requestAnimationFrame = requestAnimationFrame;
})();

var canvas = document.getElementById('game');
var context = canvas.getContext('2d');

canvas.width = canvas.height = 500;

var gameReady = true;
var players = [];
var posX = 350;
var posY = 200;
var newX = 350;
var newY = 200;

// new vars needed for movement
var velX = 0;
var velY = 0;
var speed = 5;

function movePlayer() {

  var tx = newX - posX,
    ty = newY - posY,
    dist = Math.sqrt(tx * tx + ty * ty);

  if (dist >= speed) {
    velX = (tx / dist) * speed;
    velY = (ty / dist) * speed;
    posX += velX;
    posY += velY;
  }
}

function isGameReady() {
  if (gameReady) {
    drawCanvas();
  } else {
    setTimeout(isGameReady, 100);
  }
}

canvas.onmousedown = function (e) {
  newX = e.offsetX; // -33;
  newY = e.offsetY; // - 55.25;
}


function drawCanvas() {
  movePlayer();
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.fillRect(posX, posY, 10, 10);
  requestAnimationFrame(drawCanvas);
}

isGameReady();

You should do a distance measurement from origin point to destination point, and then work out the duration for the move based on that.

Distance measurement:

function lineDistance( point1, point2 )
{
  var xs = 0;
  var ys = 0;
  xs = point2.x - point1.x;
  xs = xs * xs;
  ys = point2.y - point1.y;
  ys = ys * ys;
  return Math.sqrt( xs + ys );
}

The time to animate is the result * speed. Experiment with speed values till you get what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM