te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>Smooth keydown animation on Canvas in JavaScript - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Smooth keydown animation on Canvas in JavaScript - Stack Overflow

programmeradmin1浏览0评论

I'm very new to programming and I'm trying to create some code that will allow me to move a square around the Canvas by pressing arrow keys. I'm able to get the square to move, but its motion isn't very smooth. I have it moving by increments of 10 pixels at a time, so I understand why it feels kind of jerky, because there isn't any animation between each position of 10-frames-difference, but having it move by smaller increments makes it far too slow. What I've done so far is below:

window.onload = function init() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    setInterval(gameLoop,50);
    window.addEventListener('keydown',whatKey,true);
}

avatarX = 400
avatarY = 300

function gameLoop() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    canvas.width = 800
    canvas.height = 600
    ctx.fillRect(avatarX,avatarY,50,50);
}

function whatKey(e) {
    switch(e.keyCode) {
    case 37:
        avatarX = avatarX - 10;
        break;
    case 39:
        avatarX = avatarX + 10;
        break;
    case 40:
        avatarY = avatarY + 10;
        break;
    case 38:
        avatarY = avatarY - 10;
        break;
    }
}

Every time I press the arrow key right, I would like for the square to move smoothly in that direction at a constant rate. Thanks in advance for any help at all!

I'm very new to programming and I'm trying to create some code that will allow me to move a square around the Canvas by pressing arrow keys. I'm able to get the square to move, but its motion isn't very smooth. I have it moving by increments of 10 pixels at a time, so I understand why it feels kind of jerky, because there isn't any animation between each position of 10-frames-difference, but having it move by smaller increments makes it far too slow. What I've done so far is below:

window.onload = function init() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    setInterval(gameLoop,50);
    window.addEventListener('keydown',whatKey,true);
}

avatarX = 400
avatarY = 300

function gameLoop() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    canvas.width = 800
    canvas.height = 600
    ctx.fillRect(avatarX,avatarY,50,50);
}

function whatKey(e) {
    switch(e.keyCode) {
    case 37:
        avatarX = avatarX - 10;
        break;
    case 39:
        avatarX = avatarX + 10;
        break;
    case 40:
        avatarY = avatarY + 10;
        break;
    case 38:
        avatarY = avatarY - 10;
        break;
    }
}

Every time I press the arrow key right, I would like for the square to move smoothly in that direction at a constant rate. Thanks in advance for any help at all!

Share Improve this question asked Jan 6, 2013 at 2:45 trevnewttrevnewt 1411 gold badge3 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 15

Added a few things, the first is requestAnimationFrame for reasons explained here.

I then added a keyup and keydown event handler, these will keep track of what keys are currently being pushed by using an array. If the key is true in the array its currently being pushed, if false it isn't. This method also allows you to press and hold multiple keys at once.

I then added velocity variables which increase or decreased based on whats being pressed, and a maxSpeed variable so you don't go faster than a certain speed. The maxSpeed variable could be removed and the incrementing and decrementing velX and velY could also be removed, you would just need to unment the lines I left. It just seemed to go too fast at 10 thats why I added the gradual speed up.

Live Demo

The above will seem jerky, because the frame is scrolling with the up and down arrows since the canvas is a bit bitter, use the full screen link to fully test the movement.

Full Screen link

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


window.onload = function init() {
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  gameLoop();
}

window.addEventListener("keydown", function (e) {
  keys[e.keyCode] = true;
});
window.addEventListener("keyup", function (e) {
  keys[e.keyCode] = false;
});


var avatarX = 400,
  avatarY = 300,
  velX = 0,
  velY = 0,
  keys = [],
  maxSpeed = 10;

function gameLoop() {
  whatKey();
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  canvas.width = 800;
  canvas.height = 600;

  avatarX += velX;
  avatarY += velY;

  ctx.fillRect(avatarX, avatarY, 50, 50);
  requestAnimationFrame(gameLoop);
}

function whatKey() {
  if (keys[37]) {
    //velX = -10;
    if (velX > -maxSpeed) {
      velX -= 0.5;
    }
  }

  if (keys[39]) {
    //velX = 10;
    if (velX < maxSpeed) {
      velX += 0.5;
    }
  }
  if (keys[40]) {
    //velY = 10;
    if (velY < maxSpeed) {
      velY += 0.5;
    }
  }
  if (keys[38]) {
    //velY = -10;
    if (velY > -maxSpeed) {
      velY -= 0.5;
    }
  }
}

Massive shout out to @Loktar for answering this a decade ago. I'm currently making a game using React and this answer is still relevant. Here's my React adaptation for anyone that stumbles across this in the future!

import { useEffect, useState } from "react";

function Player(){
  const [x, setX] = useState(0);
  const [y, setY] = useState(0);
  let keys = [];
  let velocity = [0,0];
  const maxSpeed = 3;

  useEffect(() => {
    window.addEventListener("keydown", keyDown);
    window.addEventListener("keyup", keyUp );
    gameLoop();
    return () => {
      window.removeEventListener("keydown", keyDown);
      window.removeEventListener("keyup", keyUp);
    };
  }, [])

  function keyDown(e){
    keys[e.code] = true;
  }
  function keyUp(e){
    keys[e.code] = false;
  }

  function handleInput(){
    if(keys["KeyA"] && velocity[0] > -maxSpeed) velocity[0] -= 0.15;
    if(keys["KeyD"] && velocity[0] <  maxSpeed) velocity[0] += 0.15;
    if(keys["KeyS"] && velocity[1] <  maxSpeed) velocity[1] += 0.15;
    if(keys["KeyW"] && velocity[1] > -maxSpeed) velocity[1] -= 0.15;
    if(!keys["KeyA"] && !keys["KeyD"]){
      if((velocity[0] < 0.1 && velocity[0] > 0) || (velocity[0] > -0.1 && velocity[0] < 0)) velocity[0] = 0;
      if(velocity[0] < 0) velocity[0] += 0.1;
      if(velocity[0] > 0) velocity[0] -= 0.1;
    } 
    if(!keys["KeyW"] && !keys["KeyS"]){
      if((velocity[1] < 0.1 && velocity[1] > 0) || (velocity[1] > -0.1 && velocity[1] < 0)) velocity[1] = 0;
      if(velocity[1] < 0) velocity[1] += 0.1;
      if(velocity[1] > 0) velocity[1] -= 0.1;
    } 
  }

  function gameLoop() {
    handleInput();
    if(velocity[0]) setX(prev => prev + velocity[0])
    if(velocity[1]) setY(prev => prev + velocity[1])
    requestAnimationFrame(gameLoop);
  }

  const characterMover = {
    transform: `translate(${x}px, ${y}px)`
  }

  return <div id="player" style={characterMover}></div>
}

export default Player;

I'm still yet to implement sprite animations, and reserve the right to tweak this later, but this is a great base for me to start with!

发布评论

评论列表(0)

  1. 暂无评论