[英]How to move an object in some defined angle?
"I am making a game in which I need to move an object to a target position. I am half the way but the ball has many defects like: “我正在做一个需要将物体移动到目标位置的游戏。我走了一半,但是球有很多缺陷,例如:
1) If you keep tx=ty then it works fine but when you change it, the object is displaced, but why? 1)如果保持tx = ty,则可以正常工作,但是当您更改它时,该对象将移位,但是为什么呢?
2) If you keep the target behind the object, the object does not move, why?" 2)如果将目标保持在对象后面,则对象不会移动,为什么?”
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var cx = 100;
var cy = 100;
var r1 = 25;
var r2 = 50;
var a = 10;
var tx = 500;
var ty = 400;
function draw() {
var vx = Math.cos(Math.atan2(ty, tx));
var vy = Math.sin(Math.atan2(ty, tx));
if(cx < tx && cy < ty){
cx += vx + a;
cy += vy + a;
}
ctx.clearRect(0, 0, c.width, c.height);
// target
ctx.fillStyle = "blue";
ctx.strokeStyle = "rgb(0, 0, 179)";
ctx.lineWidth = 20;
ctx.beginPath();
ctx.arc(tx, ty, r2, 0, 2 * Math.PI);
ctx.stroke();
ctx.fill();
// ball
ctx.fillStyle = "red";
ctx.strokeStyle = "rgb(179, 0, 0)";
ctx.lineWidth = 20;
ctx.beginPath();
ctx.arc(cx, cy, r1, 0, 2 * Math.PI);
ctx.stroke();
ctx.fill();
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
1 => Can you give an example in an edit to your question? 1 =>您能举例说明您的问题吗?
2 => This is probably because you check in your if statement this: cx < tx && cy < ty
. 2 =>这可能是因为您在以下if语句中签入了: cx < tx && cy < ty
。
That means when cx
and cy
are both smaller then tx
and ty
. 这意味着当cx
和cy
都小于 tx
和ty
。
Working snippet: 工作片段:
var c = document.getElementById("canvas"); var ctx = c.getContext("2d"); var cx = 100; var cy = 100; var r1 = 25; var r2 = 50; var a = 0.5; // Made edit to 0.5 to move it slower var tx = 500; // Made edit from t_x to tx var ty = 400; // Made edit from t_y to ty function draw() { var vx = Math.cos(Math.atan2(ty, tx)); var vy = Math.sin(Math.atan2(ty, tx)); if(cx < tx && cy < ty){ cx += vx + a; cy += vy + a; } ctx.clearRect(0, 0, c.width, c.height); // target ctx.fillStyle = "blue"; ctx.strokeStyle = "rgb(0, 0, 179)"; ctx.lineWidth = 20; ctx.beginPath(); ctx.arc(tx, ty, r2, 0, 2 * Math.PI); // Edit t_x and t_y to tx and ty ctx.stroke(); ctx.fill(); // ball ctx.fillStyle = "red"; ctx.strokeStyle = "rgb(179, 0, 0)"; ctx.lineWidth = 20; ctx.beginPath(); ctx.arc(cx, cy, r1, 0, 2 * Math.PI); ctx.stroke(); ctx.fill(); requestAnimationFrame(draw); } requestAnimationFrame(draw);
<canvas id="canvas"></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.