请问 canvas 画人物移动要怎么写才能让人物走得比较丝滑

2021-08-06 14:32:56 +08:00
 zxCoder

例如这个 h5 游戏 https://h5mota.com/games/24/

我自己参考了网上的一些写法,写出来走得要不就特别卡,要不就特别灵敏

let fx={
            left:false,
            right:false,
            up:false,
            down:false,
        };
        draw(index, dir, x, y);
        let timer=setInterval(()=>{
            if(fx.down){
                    y++;
            }else if(fx.left){
                    x--; 
            }else if(fx.right){
                    x++;  
            }else if(fx.up){
                    y--;   
            }
            draw(index, dir, x, y);
        },50);
        document.onkeydown = (e) => {
            let key = e.key;
            if (key === "ArrowDown") {
                dir = 0;
                index++;
                fx.down=true;
            } else if (key === "ArrowLeft") {
                dir = 1;
                index++;
                fx.left=true;
            } else if (key === "ArrowRight") {
                dir = 2;
                index++;
                fx.right=true;
            } else if (key === "ArrowUp") {
                dir = 3;
                index++;
                fx.up=true;
            }
            if (index >= 3) {
                index = 0;
            }
        }

        document.onkeyup=(e)=>{
            fx={
                left:false,
                right:false,
                up:false,
                down:false,
            };
        }
1162 次点击
所在节点    问与答
6 条回复
yushiro
2021-08-06 14:50:28 +08:00
不要写死 50ms 重绘一次,浏览器有提供原生的动画重绘方法,只有老旧浏览器不支持,才需要用定时器重绘。
zxCoder
2021-08-06 15:21:24 +08:00
@yushiro requestAnimationFrame 吗?不知道怎么控制灵敏度,按键一次跑了好长一段距离。。。
yushiro
2021-08-06 16:58:13 +08:00
首先, 你不能假设每秒 redraw 运行多少次, 因为不同设备 fps 会不一样, 你现在 redraw 里面每次++, 老旧设备就会移动的慢, 新机器就跑的快。
VDimos
2021-08-06 18:58:14 +08:00
运动速度要和时间相关才能感觉流畅
Exuanbo
2021-08-06 19:40:48 +08:00
可以参考一下我之前写的基于时间的 render

https://github.com/exuanbo/dungeon-trine/blob/main/src/engine/gameRenderer.js#L39

```
render(game) {
this.animationFrameRequestId = window.requestAnimationFrame(() =>
this.render(game)
)

let delta = performance.now() - this.lastUpdateTime

if (delta < this.timeStep) {
return
}

while (delta > 0) {
game.update()
delta -= this.timeStep
}

this.lastUpdateTime = performance.now()
game.render()
}
```
3dwelcome
2021-08-06 21:38:54 +08:00
这游戏真好玩,汗😓

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/794086

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX