gpt4 book ai didi

javascript - 使用 Canvas 进行无限图像移动

转载 作者:行者123 更新时间:2023-12-04 14:50:11 24 4
gpt4 key购买 nike

class Obstacle {
constructor(image, x, y, w, h) {
this.image = image;
this.x = x;
this.y = y;
this.w = w;
this.h = h;

this.dx = gameSpeed;
}

animate() {
this.x += this.dx;
this.draw();
this.dx = gameSpeed;
}

draw() {

//////1
var pat = ctx.createPattern(landImage, "repeat-x");
ctx.fillStyle = pat;
ctx.fillRect(this.x, this.y, this.w, this.h);
//////2
ctx.drawImage(pat, this.x, this.y, this.w, this.h);
}
}

function update() {
requestAnimationFrame(update);
ctx.clearRect(0, 0, canvas.width, canvas.height);

... etc code...

terrain.animate();
}

function start() {

...etc code...

terrain = new Obstacle(landImage, 0, canvas.height - 20, 20000, 20);
update();
}
start();

地形图

terrain

问题

我正在尝试制作霸王龙游戏。我想让地面在 Dino(运行者)移动时不断移动。

在我的代码中移动图片的不是ctx.translate()函数,而是使用requestAnimationframe()函数移动了Class的'this.dx'坐标值。

写成'/////2'的第一个代码不会无限期地移动地面。
写成'/////1'的解决方案代码,但它没有工作。

如何实现无限移动的土地?

最佳答案

我自己找到了答案。我希望这个问题对阅读它的人有所帮助。

enter image description here

Reference : https://jongbeom-dev.tistory.com/109

将背景图像消失的部分尽可能多地存储在偏移量变量中并尽可能多地绘制相应的坐标值是一个问题。//left//right 分为两部分,画了背景图。

  animate() {
this.x += this.dx;
this.draw();
this.dx = gameSpeed;
//그림의 최대길이는 2380 * 23 (px)
if (offset > 2300) offset = 0;
else offset += this.dx;
}

draw() {
// left
ctx.drawImage(
this.image,
2380 - offset,
0,
offset,
23,
0,
canvas.height - this.h,
offset,
this.h
);
// right
ctx.drawImage(
this.image,
0,
0,
2380 - offset,
23,
offset,
canvas.height - this.h,
2380 - offset,
this.h
);
}

关于javascript - 使用 Canvas 进行无限图像移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69224758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com