Javascript-帆布拍摄定位

时间:2014-04-06 10:59:33

标签: javascript canvas

我想在我正在制作的游戏中拍摄太空飞船,但我似乎无法正确加载拍摄位置。 我有一个名为shots []的数组,当玩家按住鼠标按钮时,我想每隔N刻度将Shot()对象推入其中。 所以基本上我希望Shot()的x属性等于我的ship.x属性和y = ship.y。 然后我希望它有一个Shot.dx属性,该属性会发生变化,具体取决于光标位于画布中间或下方(+ 3 / -3)或中心的左侧或右侧(dy = + 3 / -3) )。

// Shooting
        var shots = [] //Bullet array

//Object, which should be the position of the bullet.
        function Shot() {
         this.x=350
         this.y=250;
         this.dx=Shoot.x
         this.dy=Shoot.y
        }

//This keeps track of the cursor position in relation to the center of canvas.
        function Shoot() {
            started = false; 
            this.mousedown = function (ev) {
                started = true; 
            };

            this.mousemove = function (ev) {
                if (started) { 
                        if (ev.clientX>=350) this.x=3;
                            else this.x=-3;
                        if (ev.clientY>=250) this.y=3;
                            else this.y=-3;
                }
            };
            this.mouseup = function (ev) {
                started = false;
            };
        }
//The problem is, that when I set this.x in Shot() to be =ship.x the values
//dont get updated and it stays undefined after I push it into the array.
//Now I have it set to the center of canvas, but that it useless because it needs
//to move with the ship, but even now I am getting weird numbers and not the numbers
//that I actually put in. dx and dy dont get updated at all.

   // Ship Model
        var ship = {
            x: 350,
            y: 250,
            lives: 3,
            invulnerable: 0,
        }

//Main function- pushes the objects into the array
        function mainLoop() {
            tick++
            count()
            interval()
            chase()
            console.log(started)
            if (started && tick%20==0) 
                    shots.push(new Shot());
            keyboard()
            display()
            check()
            requestAnimationFrame(mainLoop);
        }

// Initialization
        window.onload = function() {
          // Setting variables
            button = document.getElementById("button")
            text = document.getElementById("text")
            canvas = document.getElementById("canvas")
            ctx = canvas.getContext("2d")
            weapon = new Shoot();
            canvas.onmousedown = weapon.mousedown;
            canvas.onmousemove = weapon.mousemove;
            canvas.onmouseup = weapon.mouseup;
            requestAnimationFrame(mainLoop);
        }

//I know this is a lot of code, but its all relevant. I am new to Javascript
//so I expect this to be some sort of a trivial error.

这是一个JSfiddle,但我不知道它是如何工作的,所以我不能画画布画,抱歉:http://jsfiddle.net/JH3M6/

1 个答案:

答案 0 :(得分:0)

以下是如何开枪的概要:

  • 创建一个数组来保存您的镜头对象

  • mousedown上的
  • :设置started标志(开始点火)

  • mousedown上的
  • :将任何新镜头的射击位置设置为当前鼠标位置

  • 鼠标移动时
  • :将任何新镜头的射击位置重置为当前鼠标位置

  • 鼠标上的
  • :清除started标志(停止发射)

在动画循环中:

  • 如果鼠标仍然按下,则在当前触发位置添加一个镜头
  • 按照dx,dy移动所有镜头
  • 如果镜头移出画布,则从镜头[]数组中删除任何镜头
  • 清除屏幕并以新位置拍摄

演示:http://jsfiddle.net/m1erickson/2f9sf/

以下是示例代码:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    // canvas related vars
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    var bb=canvas.getBoundingClientRect();
    var offsetX=bb.left;
    var offsetY=bb.top;
    ctx.fillStyle="blue";

    // vars related to firing position and Shot(s)
    var shotColor=ctx.fillStyle;
    var started,mouseX,mouseY,dx,dy;

    // Shots fired
    var shots = [] //Bullet array

    //Object, which should be the position of the bullet.
    function Shot(x,y,dx,dy) {
        this.x=x;
        this.y=y;
        this.dx=dx;
        this.dy=dy;
    }
    Shot.prototype.display=function(){
        // make fillstyle blue if it's not already blue
        if(!ctx.fillStyle==shotColor){ctx.fillStyle=shotColor;}
        // draw the shot on the canvas
        ctx.fillRect(this.x,this.y,5,5);
    }

    // listen for mouse events
    canvas.onmousedown=function(e){ started=true; setFirePosition(e); }
    canvas.onmouseup=function(e){ started=false; }
    canvas.onmousemove=function(e){
        if(started){setFirePosition(e);}
    }

    // start the animation loop
    requestAnimationFrame(animate);

    // set the firing position of the next shot
    function setFirePosition(e){
        mouseX=parseInt(e.clientX-offsetX);
        mouseY=parseInt(e.clientY-offsetY);
        dx=(mouseX>=canvas.width/2)?-3:3;
        dy=(mouseY>=canvas.height/2)?-3:3;        
    }

    // animation loop
    // add shots if the mouse is down
    // move shots until they move off-canvas
    function animate(){

        // request another frame
        requestAnimationFrame(animate);

        // if the mouse is down, add a shot
        if(started){
            shots.push(new Shot(mouseX,mouseY,dx,dy));
        }

        // if no work to do, return
        if(shots.length==0){return;}

        // new array of active shots
        // "active" == shot has not moved off-canvas
        var a=[];

        // clear the canvas for this frame
        ctx.clearRect(0,0,cw,ch);

        for(var i=0;i<shots.length;i++){

            // get a shot to process
            var shot=shots[i];

            // move this shot
            shot.x+=shot.dx;
            shot.y+=shot.dy;

            // if the shot hasn't moved offscreen
            // add the shot to "a" (the replacement shots array);
            // draw this shot
            if(shot.x>=0 && shot.x<=cw && shot.y>0 && shot.y<=ch){
                a.push(shot);
                shot.display();
            }
        }

        // if shots went off-canvas, remove them from shots[]
        if(a.length<shots.length){
            shots.length=0;
            Array.prototype.push.apply(shots,a);
        }

    }

}); // end $(function(){});
</script>
</head>
<body>
    <h4>Mousedown to fire shots</h4>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>