“”我正在制作一个游戏,需要将一个物体移动到目标位置。虽然我只走了一半,但是球有很多缺陷,例如:
1)如果保持tx = ty,那么它就可以了很好,但是当您更改它时,该对象已移位,但为什么呢?
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);
答案 0 :(得分:0)
1 =>您能举例说明您的问题吗?
2 =>这可能是因为您在以下if语句中签入了:cx < tx && cy < ty
。
这意味着当cx
和cy
都小时,则tx
和ty
。
工作片段:
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>