جواب «Solid Wall» چالش 5 از جلسهی 9
سؤال
قهرمان (hero، پهنای ۴۰) از x = 40 با سرعت ۲۰۰ پیکسل در ثانیه راه میرود، ولی از وسط دیوار (wall، از x = 200) رد میشود.
دیوار را سفت کن: وقتی قهرمان به دیوار خورد، او را درست کنار دیوار بگذار: hero.x = wall.x - hero.w. قهرمان باید هنوز بتواند به چپ برگردد.
راهنما
بعد از حرکت: if (salam.hit(hero, wall)) hero.x = wall.x - hero.w; یعنی ۲۰۰ منهای ۴۰، پس قهرمان در x = 160 میایستد.
یک جواب درست
<script>
const ctx = salam.canvas(360, 480);
const hero = { x: 40, y: 380, w: 40, h: 40 };
const wall = { x: 200, y: 300, w: 30, h: 120 };
salam.touchKeys(["ArrowLeft", "ArrowRight"]);
salam.loop(function (dt) {
if (salam.keys.ArrowLeft) hero.x = hero.x - 200 * dt;
if (salam.keys.ArrowRight) hero.x = hero.x + 200 * dt;
hero.x = Math.max(0, hero.x);
if (salam.hit(hero, wall)) hero.x = wall.x - hero.w;
ctx.fillStyle = "skyblue";
ctx.fillRect(0, 0, 360, 480);
ctx.fillStyle = "green";
ctx.fillRect(0, 420, 360, 60);
ctx.fillStyle = "sienna";
ctx.fillRect(wall.x, wall.y, wall.w, wall.h);
ctx.fillStyle = "tomato";
ctx.fillRect(hero.x, hero.y, hero.w, hero.h);
});
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن