بتل کد Battle Codeدارد باز می‌شود…

جواب «My Own hit» چالش 4 از جلسه‌ی 9

سؤال

تابع touching(a, b) را خودت بنویس، بدون salam.hit: با همان چهار مقایسه، اگر دو جعبه روی هم افتاده‌اند true بده و اگر نه false.
جعبه‌هایی که فقط لبه‌به‌لبه کنار هم‌اند (مثلاً یکی تا x = 10 است و دیگری از x = 10 شروع می‌شود) به هم نخورده‌اند.
بعد قهرمان را با کلیدها به جعبه برسان: جعبه باید طلایی شود.

راهنما

return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y; از < و > استفاده کن، نه <=، تا لبه‌به‌لبه برخورد حساب نشود.

یک جواب درست

<script>
  const ctx = salam.canvas(360, 480);
  const hero = { x: 40, y: 220, w: 40, h: 40 };
  const box = { x: 160, y: 200, w: 80, h: 80 };
  salam.touchKeys(["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"]);

  function touching(a, b) {
    return a.x < b.x + b.w &&
           a.x + a.w > b.x &&
           a.y < b.y + b.h &&
           a.y + a.h > b.y;
  }

  salam.loop(function (dt) {
    if (salam.keys.ArrowLeft) hero.x = hero.x - 200 * dt;
    if (salam.keys.ArrowRight) hero.x = hero.x + 200 * dt;
    if (salam.keys.ArrowUp) hero.y = hero.y - 200 * dt;
    if (salam.keys.ArrowDown) hero.y = hero.y + 200 * dt;

    ctx.fillStyle = "skyblue";
    ctx.fillRect(0, 0, 360, 480);
    if (touching(hero, box)) {
      ctx.fillStyle = "gold";
    } else {
      ctx.fillStyle = "white";
    }
    ctx.fillRect(box.x, box.y, box.w, box.h);
    ctx.fillStyle = "tomato";
    ctx.fillRect(hero.x, hero.y, hero.w, hero.h);
  });
</script>

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن