جواب «Phone Hero» چالش 7 از جلسهی 8
سؤال
قهرمانی بساز که روی کامپیوتر و گوشی بازی شود:
- دو دکمهی لمسی ArrowLeft و ArrowRight.
- با کلید یا دکمه، ۲۵۰ پیکسل در ثانیه راه برود؛ وقتی راه میرود، targetX هم با او بیاید (targetX = hero.x).
- با لمس صحنه، targetX = x - hero.w / 2 شود و قهرمان با ۲۵۰ پیکسل در ثانیه به آنجا راه برود.
- هیچ وقت از صحنه بیرون نرود (hero.x بین ۰ و ۳۲۰).
راهنما
سه تکه: salam.touchKeys و salam.tap بیرون از حلقه؛ در حلقه، اول کلیدها (هر کدام با targetX = hero.x)، بعد راه رفتن به سمت targetX با Math.min / Math.max، و آخر دیوارها.
یک جواب درست
<script>
const ctx = salam.canvas(360, 480);
const hero = { x: 160, y: 420, w: 40, h: 40 };
let targetX = 160;
salam.touchKeys(["ArrowLeft", "ArrowRight"]);
salam.tap(function (x, y) {
targetX = x - hero.w / 2;
});
salam.loop(function (dt) {
if (salam.keys.ArrowLeft) {
hero.x = hero.x - 250 * dt;
targetX = hero.x;
}
if (salam.keys.ArrowRight) {
hero.x = hero.x + 250 * dt;
targetX = hero.x;
}
if (hero.x < targetX) hero.x = Math.min(targetX, hero.x + 250 * dt);
if (hero.x > targetX) hero.x = Math.max(targetX, hero.x - 250 * dt);
hero.x = Math.max(0, Math.min(360 - hero.w, hero.x));
ctx.fillStyle = "skyblue";
ctx.fillRect(0, 0, 360, 480);
ctx.fillStyle = "tomato";
ctx.fillRect(hero.x, hero.y, hero.w, hero.h);
});
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن