对于学校来说,我需要做一个游戏,所以我想制作一个类似于“魔幻触摸:出租向导”的游戏,这是一个气球从天空中坠落的游戏,你需要绘制图画才能弹出它们,这就是我想要的想法。
但现在,我的问题是:我想让气球在x轴上随机出现(所以它总是在y=0上产卵,x轴是随机的),但这就是我的问题所在。我为它创建了树函数:这是创建随机数的函数:
function aleatorizar() {
let random= Math.floor(Math.random()*canvas.width);
return random;
}
这是绘制气球的函数,气球上有文字:
function desenharbombas(x){
ctx.beginPath();
ctx.arc(x,posição,50,0,2*Math.PI);
ctx.stroke();
ctx.fillStyle= "#000000";
ctx.fill();
function escrever(){
ctx.font="17px Arial Black";
ctx.fillStyle="#ffffff";
ctx.fillText("texto",x,posição );
}
escrever()
}
这就是让气球下落的动画功能:
function animar(y){
ctx.clearRect(0,0,canvas.width,canvas.height);
posição=posição+1;
desenharbombas(y)
requestAnimationFrame(animar);
}
在我的逻辑(和测试时间的低谷)中,我不能把随机函数放入我的炸弹绘图函数中,因为它会使随机函数在每次调用绘图函数时发生变化,从而使炸弹在屏幕上左右发生故障。
所以我创建了这个逻辑,当动画函数被调用时,炸弹绘制函数只会接收一个随机数,但是它没有工作,因为现在炸弹是斜降的。我知道这真的很难理解,但是如果有人知道如何帮助我,或者想不愿意帮我.(caue#7600)
发布于 2022-05-05 14:18:53
像这样的事怎么样:
const canvas = document.getElementById("c");
const ctx = canvas.getContext("2d");
ctx.textAlign = 'center';
ctx.textBaseline = 'middle'
var bombas = []
class bomba {
constructor(name, x, y, speed, radius) {
this.name = name
this.x = x
this.y = y
this.speed = speed
this.radius = radius
}
draw() {
ctx.beginPath();
ctx.arc(this.x += this.speed, this.y, this.radius, 0, 2 * Math.PI);
ctx.stroke();
ctx.fillText(this.name, this.x, this.y);
}
}
function aleatorizar() {
return Math.floor(Math.random() * canvas.width);
}
bombas.push(new bomba("A", aleatorizar()/4, 10, 0.20, 8))
bombas.push(new bomba("B", aleatorizar()/4, 40, 0.25, 12))
bombas.push(new bomba("C", aleatorizar()/4, 70, 0.15, 10))
function animar() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
bombas.forEach(b => b.draw())
requestAnimationFrame(animar);
}
animar()
<canvas id="c"></canvas>
您可以看到,我们有一个class bomba
,在构造函数上,我们传递绘制所需的所有初始参数,然后在draw()
函数中,我们以给定的速度增加x的值,并绘制弧和文本。
有了这个新的类,你可以添加更多的随机参数,现在只是Y是随机的,但同样的方式,你可以做它的速度和半径。
如果你真的想建立一个游戏,你应该看看游戏引擎,有很多好的开源,github有一个很好的集合,众所周知:
https://github.com/collections/javascript-game-engines
当你的游戏变得越来越复杂,你会遇到已经在游戏引擎中解决的问题,这取决于你想在这个游戏中走多远。
https://stackoverflow.com/questions/72094476
复制相似问题