簡體   English   中英

Canvas Object 沿對角線移動,而不是垂直移動

[英]Canvas Object moving diagonally, not vertically

為了學校,我需要做一個游戲,所以我有了做一個類似於“魔法觸摸:出租向導”的游戲的想法,這是一個氣球從天而降的游戲,你需要畫圖來彈出它們,這就是我想要的想法。

但是現在,我的問題是:我有讓氣球隨機出現在 x 軸上的想法,(所以它總是在 y=0 處產生並且 x 軸是隨機的),但這就是我的問題所在。 我為它制作了樹函數:這是創建隨機數的 function:

function aleatorizar() {
let random= Math.floor(Math.random()*canvas.width);
return random;
}

這是繪制帶有文字的氣球的 function:

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:

function animar(y){
ctx.clearRect(0,0,canvas.width,canvas.height);
posição=posição+1;
desenharbombas(y)
requestAnimationFrame(animar);
}

在我的邏輯中(以及經過幾個小時的測試),我不能將隨機數 function 放入我的炸彈繪圖 function 中,因為它會在每次調用繪圖 function 時使隨機數 function 發生變化,從而使炸彈左右出現故障屏幕上。

所以我創建了這個邏輯,當調用動畫 function 時,炸彈繪圖 function 只會收到一個隨機數,但它不起作用,因為現在炸彈是斜着落的。 我知道這真的很難理解,但如果有人知道如何提供幫助或想跳上 discord 來幫助我...(caue#7600)

這樣的事情怎么樣:

 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() function 中我們將 x 的值增加給定的速度,並繪制弧線和文本。

使用這個新的 class,您可以添加更多隨機參數,現在只是 Y 是隨機的,但您可以用同樣的方式為速度和半徑做這件事


如果你真的想構建游戲,你應該研究游戲引擎,有很多好的開源,github 有一個很好的知名集合:
https://github.com/collections/javascript-game-engines
隨着您的游戲變得越來越復雜,您將遇到游戲引擎中已經解決的問題,這取決於您希望這款游戲達到 go 的程度

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM