جواب «Walk to My Finger» چالش 5 از جلسهی 8
سؤال
قهرمان باید به جایی که لمس شد راه برود، نه بپرد:
- targetX (مقصد) از ۱۶۰ شروع میشود.
- لمس فقط مقصد را عوض میکند: targetX = x - hero.w / 2.
- هر فریم قهرمان با سرعت ۲۰۰ پیکسل در ثانیه به سمت targetX برود و روی آن بایستد.
راهنما
در salam.tap فقط targetX = x - hero.w / 2;. در حلقه: if (hero.x < targetX) hero.x = Math.min(targetX, hero.x + 200 * dt); و برعکسش با Math.max.
یک جواب درست
<script>
const ctx = salam.canvas(360, 480);
const hero = { x: 160, y: 420, w: 40, h: 40 };
let targetX = 160;
salam.tap(function (x, y) {
targetX = x - hero.w / 2;
});
salam.loop(function (dt) {
if (hero.x < targetX) hero.x = Math.min(targetX, hero.x + 200 * dt);
if (hero.x > targetX) hero.x = Math.max(targetX, hero.x - 200 * dt);
ctx.fillStyle = "skyblue";
ctx.fillRect(0, 0, 360, 480);
ctx.fillStyle = "tomato";
ctx.fillRect(hero.x, hero.y, hero.w, hero.h);
});
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن