我正在寻找“如何将我的子弹移动到x,y coords”,但我找不到任何帮助或有用的话题..:|
嗯,有我的代码:
GoToMouse()
{
this.goX = mouse.x;
this.goY = mouse.y;
this.dx = this.goX;
this.dy = this.goY;
}
UpdatePosition()
{
this.x += this.dx / 1000;
this.y += this.dy / 1000;
}
当然,每60分钟,我画一个矩形!
所以,代码工作,当rect从0,0开始 但是,当子弹开始时,例如10,10它不那么准确,而更大的起点更低的是子弹准确:|
谢谢! :)
答案 0 :(得分:1)
这是animation tutorial。您可以通过示例查看如何在屏幕上为图形(例如项目符号)设置动画。
使用向量计算从[startX,startY]到[endX,endY]的增量[x,y]
// dx is the total distance to move in the X direction
var dx = endX - startX;
// dy is the total distance to move in the Y direction
var dy = endY - startY;
// use a pct (percentage) to travel the total distances
// start at 0% which == the starting point
// end at 100% which == then ending point
var pct=0;
// use dx & dy to calculate where the current [x,y] is at a given pct
var x = startX + dx * pct/100;
var y = startY + dx * pct/100;
示例代码和演示,帮助您入门:
// canvas vars
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
// animating vars
var pct=101;
var startX,startY,endX,endY,dx,dy;
// canvas styles
ctx.strokeStyle='skyblue';
ctx.fillStyle='blue';
// start animation loop running
requestAnimationFrame(animate);
// listen for mouse events
window.onmousedown=(function(e){handleMouseDown(e);});
window.onmouseup=(function(e){handleMouseUp(e);});
// constantly running loop
// will animate bullet
function animate(time){
// return if there's no bullet to animate
if(++pct>100){requestAnimationFrame(animate);return;}
// update
x=startX+dx*pct/100;
y=startY+dy*pct/100;
// draw
ctx.clearRect(0,0,cw,ch);
ctx.beginPath();
ctx.moveTo(startX,startY);
ctx.lineTo(endX,endY);
ctx.stroke();
ctx.beginPath();
ctx.arc(x,y,5,0,Math.PI*2);
ctx.fill()
// request another animation loop
requestAnimationFrame(animate);
}
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// save ending position
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
// set flag
pct=101;
}
function handleMouseUp(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// save ending position and vector
endX=parseInt(e.clientX-offsetX);
endY=parseInt(e.clientY-offsetY);
dx=endX-startX;
dy=endY-startY;
// set pct=0 to start animating
pct=0;
}

body{ background-color: ivory; }
#canvas{border:1px solid red; }

<h4>Drag the mouse<br>Mousedown sets starting position,<br>Mouseup sets ending position and animates.</h4>
<canvas id="canvas" width=512 height=512></canvas>
&#13;