Comparing x/y of two positions on a canvas

前端 未结 1 367
野的像风
野的像风 2020-12-12 06:32

im using a canvas to visualize a small game of mine. Basicly i have two objects that represent space ships, each of them has a \"Location\" array which holds the ships curre

相关标签:
1条回答
  • 2020-12-12 07:02

    You can fire a bullet from shooter to target using linear interpolation.

    1. Calculate the difference in the original X & Y positions of the shooter and target.

      // save the starting position of the bullet (== shooter's original position)
      // (these original X & Y are needed in the linear interpolation formula)
      bulletOriginalX=shooter.x;
      bulletOriginalY=shooter.y;
      
      // calc the delta-X & delta-Y of the shooter & target positions
      // (these deltas are needed in the linear interpolation formula)
      dx=target.x-shooter.x;
      dy=target.y-shooter.y;
      
    2. Move the bullet towards the target using the interpolation formula

      // where percent == the percent you want the bullet to be between 
      // it's starting & ending positions
      // (between starting shooter & starting target positions)
      currentBulletX=bulletOriginalX+dx*percent;
      currentBulletY=bulletOriginalY+dy*percent;
      

    Here's an example:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    
    shooter={x:50,y:50};
    target={x:100,y:100};
    effect={x:50,y:50,dx:0,dy:0,pct:0,speedPct:0.25};
    
    draw();
    fire();
    
    $('#test').click(function(){
      moveEffect();
      draw();
    });
    
    function fire(){
      effect.x=shooter.x;
      effect.y=shooter.y;
      effect.dx=target.x-shooter.x;
      effect.dy=target.y-shooter.y;
      effect.pct=0;
    }
    
    function moveEffect(){
      effect.pct+=effect.speedPct;
    }
    
    function draw(){
      ctx.clearRect(0,0,cw,ch);
    
      ctx.beginPath();
      ctx.arc(shooter.x,shooter.y,15,0,Math.PI*2);
      ctx.closePath();
      ctx.strokeStyle='green';
      ctx.stroke();
    
      ctx.beginPath();
      ctx.arc(target.x,target.y,15,0,Math.PI*2);
      ctx.closePath();
      ctx.strokeStyle='red';
      ctx.stroke();
    
      if(effect.pct>1){return;}
    
      var x=effect.x+effect.dx*effect.pct;
      var y=effect.y+effect.dy*effect.pct;
    
      ctx.beginPath();
      ctx.arc(x,y,3,0,Math.PI*2);
      ctx.closePath();
      ctx.fillStyle='black';
      ctx.fill();
    
    }
    body{ background-color: ivory; padding:10px; }
    #canvas{border:1px solid red;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <button id=test>Animate 1 frame</button>
    <br><canvas id="canvas" width=300 height=300></canvas>

    0 讨论(0)
提交回复
热议问题