我正在嘗試為從一個位置到另一個位置的移動圓圈設定影片。在下面的示例中,從 (10, 10) 到 (50, 50) 下面是我的 Bullet 類的代碼。當用戶單擊空格時,我創建了一個新的 Bullet 物件并嘗試為其設定影片。如何創建流暢的影片?
class Bullet{
constructor(x, y){
this.x = x;
this.y = y;
this.size = 10;
}
draw(){
ctx.fillStyle = "green";
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI)
ctx.fill();
}
fire(locationX, locationY){
}
}
document.addEventListener('keydown', function(e){
if(e.key == ' '){
var currBullet = new Bullet(10, 10);
currBullet.fire(50, 50);
}
});
function reset(){
ctx.clearRect(0, 0, w, h);
}
uj5u.com熱心網友回復:
您可以使用requestAnimationFrame影片子彈。這樣做的總體目標是什么?你打算從 (10, 10) 到 (50, 50) 發射子彈嗎?需要限制行駛距離嗎?還是會根據玩家面對的方向朝某個方向射擊?你想限制子彈的數量嗎?
此代碼執行您的要求,但非常有限。
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = 200;
canvas.height = 200;
let bullets = [];
class Bullet{
constructor(x, y){
this.x = x;
this.y = y;
this.size = 10;
}
draw(){
ctx.fillStyle = "green";
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI)
ctx.fill();
}
update(){
this.x = 1
this.y = 1
}
}
document.addEventListener('keydown', function(e){
if(e.code === 'Space'){
fire()
}
});
function fire() {
bullets.push(new Bullet(10, 10))
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i=0; i < bullets.length; i ) {
bullets[i].draw()
bullets[i].update()
if (bullets[i].x >= 50 && bullets[i].y >= 50) {
bullets.splice(i, 1)
}
}
requestAnimationFrame(animate)
}
animate()
<canvas id='canvas'></canvas>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/399092.html
標籤:javascript 动画片 html5-canvas
上一篇:添加逗號作為用戶型別編號(例如:1,000/10,000/100,000/1,000,000/10,000,000等
下一篇:將資訊從txt檔案匯入類
