"내 총알을 x, y 좌표로 이동하는 방법"을 찾고 있지만 도움말이나 유용한 주제를 찾지 못했습니다 .. : |
글쎄, 내 코드가 있습니다.
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;
}
물론 매 60ms마다 직사각형을 그립니다!
따라서 코드는 rect가 0,0에서 시작될 때 작동하지만 총알이 시작될 때 예를 들어 10,10은 덜 정확하고 시작점이 클수록 시작점이 낮을수록 총알이 정확합니다.
감사 ! :)
다음은 애니메이션 튜토리얼 입니다. 화면 전체에서 그림 (예 : 글 머리 기호)을 애니메이션하는 방법을 예제로 볼 수 있습니다.
벡터를 사용하여 [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>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다