جواب «Tap Left, Tap Right» چالش 4 از جلسهی 8
سؤال
یک کنترل ساده برای گوشی: اگر نیمهی چپ صحنه لمس شد (x < 180)، قهرمان ۶۰ پیکسل به چپ برود؛ اگر نیمهی راست، ۶۰ پیکسل به راست.
قهرمان نباید از صحنه بیرون برود (hero.x بین ۰ و ۳۲۰).
راهنما
داخل salam.tap: if (x < 180) hero.x = hero.x - 60; else hero.x = hero.x + 60; و بعدش همان خط Math.max(0, Math.min(360 - hero.w, hero.x)).
یک جواب درست
<script>
const ctx = salam.canvas(360, 480);
const hero = { x: 160, y: 420, w: 40, h: 40 };
salam.tap(function (x, y) {
if (x < 180) hero.x = hero.x - 60;
else hero.x = hero.x + 60;
hero.x = Math.max(0, Math.min(360 - hero.w, hero.x));
});
salam.loop(function (dt) {
ctx.fillStyle = "skyblue";
ctx.fillRect(0, 0, 360, 480);
ctx.fillStyle = "tomato";
ctx.fillRect(hero.x, hero.y, hero.w, hero.h);
});
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن