iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 25
0
自我挑戰組

學習 canvas 日記系列 第 25

第 25 天 練習畫遊戲場地 三

場地除了有可以給在圖形物件活動的地方
也可以設定某些區域是不能進入
這就可以設定當物件 "碰撞" 到某個邊界時就不能再前進
所以先作一個簡單的例子
建立一個 300x300 的矩形的區域和一個在區域內的物件
https://ithelp.ithome.com.tw/upload/images/20181107/20107496D4Qk0nAsru.jpg

物件是不是有出界
就用 if 判斷物件 box 的 (x, y) 上下左右是不是已經超過四個邊
因為矩形是從左上角向右下拉出一個區域填色
所以只要找出 右邊的x值和下邊的x值

box_x + box_width // 右
box_y + box_height // 下

再用 if 判斷 box 有沒有碰到邊界

if(box_x == 0){ ... } // 碰到左邊
if(box_x + box_width == 0){ ... } // 碰到右邊
if(box_y == 0){ ... } // 碰到上邊
if(box_y + box_height == 0){ ... } // 碰到下邊

就可以設定使用鍵盤的 上下左右、WSAD
讓物件碰到邊時就不能繼續

window.addEventListener('keydown', function(e){
    if(e.code === 'KeyW')  {
      if(box_y !== 0){
        ctx.clearRect(0, 0, area, area);
        box_y = box_y - 10;
        ctx.fillRect(box_x, box_y, box_size, box_size);
      }
    }
    if(e.code === 'KeyD')  {
      if(box_x + box_size !== area){
        ctx.clearRect(0, 0, area, area);
        box_x = box_x + 10;
        ctx.fillRect(box_x, box_y, box_size, box_size);
      }
    }
    if(e.code === 'KeyS')  {
      if(box_y + box_size !== area){
        ctx.clearRect(0, 0, area, area);
        box_y = box_y + 10;
        ctx.fillRect(box_x, box_y, box_size, box_size);
      }
    }
    if(e.code === 'KeyA')  {
      if(box_x !== 0){
        ctx.clearRect(0, 0, area, area);
        box_x = box_x - 10;
        ctx.fillRect(box_x, box_y, box_size, box_size);
      }
    }
},true);

上一篇
第 24 天 練習畫遊戲場地 二
下一篇
第 26 天 迷宮 一
系列文
學習 canvas 日記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言