EDIT上の座標:更新パスオブジェクトがXに移動している間に/ Yは、マウスクリック
こんにちは、
このコードは、X/Yのプレイヤオブジェクトの移動はマウスクリック上の座標のmake。目標が目標に達していなくても、新しい目標を更新できるように、コード内で何ができるのですか。このようにすれば、プレイヤーは自由にマウスを動かすことができますか?
私はまだjavascriptの基礎を学んでいるので、私はそれを行う方法がわかりません。私は助けていただければ幸いです。誰かがそれをどうやって行うのか、コードを単純化する方法を知っていたら?
var ctx = demo.getContext('2d'),
x, y, x1, y1, x2 = 0,
y2 = 0, /// positions
f = 0, /// "progress"
speed, /// speed based on dist/steps
dist, /// distance between points
steps = 3; /// steps (constant speed)
SPEED.onchange = function() {
steps = val.innerHTML = SPEED.value
}
demo.onclick = function(e) {
/// if we are moving, return
if (f !== 0) return;
/// set start point
x1 = x2;
y1 = y2;
/// get and adjust mouse position
var rect = demo.getBoundingClientRect();
x2 = e.clientX - rect.left,
y2 = e.clientY - rect.top;
/// calc distance
var dx = x2 - x1,
dy = y2 - y1;
dist = Math.abs(Math.sqrt(dx * dx + dy * dy));
/// speed will be number of steps/distance
speed = steps/dist;
/// move player
loop();
}
function loop() {
/// clear current drawn player
ctx.fillStyle = 'rgba(160, 160, 160, 0.5)';
ctx.fillRect(0, 0, demo.width, demo.height);
ctx.fillStyle = '#007';
/// move a step
f += speed;
/// calc current x/y position
x = x1 + (x2 - x1) * f;
y = y1 + (y2 - y1) * f;
/// at goal? if not, loop
if (f < 1) {
/// draw the "player"
ctx.fillRect(x - 4, y - 4, 8, 8);
requestAnimationFrame(loop);
} else {
/// draw the "player"
ctx.fillRect(x2 - 4, y2 - 4, 8, 8);
/// reset f so we can click again
f = 0;
}
}
body {
background: #333;
color: #aaa;
font: 14px sans-serif;
}
canvas {
background: rgba(255, 255, 255, 0.1);
}
#info {
position: fixed;
left: 80px;
top: 190px;
font-size: 20px;
color: #fff;
z-index: -1;
}
<canvas id="demo" width=400 height=400></canvas>
<br> Speed <input type="range" min=1 max=20 value=3 id="SPEED">
<span id="val">3</span>
<div id="info">Click somewhere on canvas</div>
質問自体に関連コードを含めてください。 –
こんにちは、このサイトを初めて使ったことはありますが、次回はもっと具体的にするつもりです。私は希望の方法で投稿を編集しました。ありがとう! – Knightwalker