有没有一种方法可以使画布上的矩形仅向前移动但可以旋转并直线移动?

时间:2019-01-21 00:43:33

标签: javascript object canvas rotation

我正在创建一个太空入侵者类型的游戏,该游戏的飞船(现在只是矩形)只能向前和向后移动,但可以绕其中心旋转以转向。它也可以发射小子​​弹(我存储在阵列中的球形物体),但是它们似乎也“附着”在我的舰船上。我该如何做,使子弹沿直角移动,远离矩形的前面(短边),但不随其旋转,并且在运行并转动几秒钟后,它会开始在其自身上绘制并进行跟踪。请帮忙!

这是一个jsfiddle:https://jsfiddle.net/mattp15/2shbwc60/

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var ship = new Ship();
var bullets = [];
function allUpdate(){
    drawBackground();
    ship.update();
    //for loop to draw all bullets
    for(var i =0;i < bullets.length;i++){
        var bullet = bullets[i];
        bullet.update();
    }

    window.requestAnimationFrame(allUpdate);
}
window.requestAnimationFrame(allUpdate);

window.onkeydown = function(event){
    var left = 37;
    var up = 38;
    var right = 39;
    var down = 40;

    if(event.keyCode == up)
        ship.dY = -1;
    if(event.keyCode == down)
        ship.dY = 1;
    if(event.keyCode ==  left){
        ship.isRotating = true;
        ship.theta = -5;   
    }
    if(event.keyCode == right){
        ship.isRotating = true;
        ship.theta = 5;
    }
    if(event.key == " "){
        var x = ship.x + ship.width;
        var y = ship.y + ship.height/2;
        var bullet = new Bullet(x,y);
        bullets.push(bullet);
    }

}
window.onkeyup = function(event){
        var left = 37;
        var up = 38;
        var right = 39;
        var down = 40;
        if(event.keyCode == left || event.keyCode == right){
            ship.isRotating = false;
            ship.theta = 0;
        }

    }

var Bullet = function(x,y){
    this.x = x;
    this.y = y;
    this.r = 5;
    this.dX = 2;
    this.dY = 2;

    this.update = function(){
        ctx.fillStyle = "blue";
        ctx.beginPath();
        ctx.arc(this.x+=this.dX,this.y,this.r,0,Math.PI *2,false);
        ctx.closePath();
        ctx.fill();
    }

}


function Ship(){
    this.isRotating = false;
    this.theta = 0; //in degrees
    this.width = 30;
    this.height = 10;
    this.x = 0;
    this.y = canvas.height/2;
    this.dX = 1;
    this.dY = 0;
    this.fillStyle = "white";
    this.update = function() {
        ctx.fillStyle = "white";
        ctx.fillRect(this.x+=this.dX,this.y+=this.dY,this.width,this.height);
        ctx.translate(this.x,this.y+(this.height/2));
        ctx.rotate((this.theta) * Math.PI/180);
        ctx.translate(-this.x,-(this.y +this.height/2));   
    }

}

function drawBackground(){
    ctx.fillStyle = "black";
    ctx.fillRect(0,0,canvas.width,canvas.height);
}

0 个答案:

没有答案