iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 6
1
Modern Web

以前端角度探討遊戲化的資訊設計系列 第 6

Day 06 - 切換場景(續)

今天花點時間研究昨日的切換場景,寫個簡易的場景管理器

簡易場景切換 Demo with ScenesManager

1.製作一個場景為四方形的物體場景

function drawRec(){
	var canvas = document.getElementById('canvas');
	if (canvas.getContext){
		 var ctx = canvas.getContext("2d");

			ctx.fillStyle = "rgb(200,0,0)";
			ctx.fillRect (10, 10, 55, 50);

			ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
			ctx.fillRect (30, 30, 55, 50);
	}
}

2.製作一個場景三角形的物體場景

function drawTri() {
  var canvas = document.getElementById('canvas');
  if (canvas.getContext){
    var ctx = canvas.getContext('2d');

    // Filled triangle
    ctx.beginPath();
    ctx.moveTo(25,25);
    ctx.lineTo(105,25);
    ctx.lineTo(25,105);
    ctx.fill();

    // Stroked triangle
    ctx.beginPath();
    ctx.moveTo(125,125);
    ctx.lineTo(125,45);
    ctx.lineTo(45,125);
    ctx.closePath();
    ctx.stroke();
  }
}

3.今日主角 ScenceManager

class ScenesManager {
	constructor() {
		this.scenes = {}  // 紀錄 create 過的場景
		this.currentScene = null // 當前場景
	}
	create = (width, height, scale=false) => {
        var canvas = document.getElementById('canvas')
        canvas.width = width
        canvas.height = height
        return this;
	}
	createScene(id, TScene) {
        scenesManager.scenes[id] = TScene;
	}

  clearScene() {
		var canvas = document.getElementById('canvas')
		var ctx = canvas.getContext('2d');
		ctx.clearRect(0, 0, canvas.width, canvas.height);
	}
	goToScene(id) {
		this.clearScene() // 清除上一個場景
		if (scenesManager.scenes[id]) {
            scenesManager.currentScene = scenesManager.scenes[id];
            scenesManager.scenes[id]()
            return true;
		}
            return false;
		}
}

4.使用過程

const scenesManager = new ScenesManager()
scenesManager.create(150, 150, true)

var rec = scenesManager.createScene('rectangle', drawRec);
var tri = scenesManager.createScene('triangle', drawTri);
	$('#goToRec').click(function () {
			scenesManager.goToScene('rectangle');
	});
	$('#goToTri').click(function () {
			scenesManager.goToScene('triangle');
	});
scenesManager.goToScene('rectangle');

5.Demo 結果


上一篇
Day 05 - 切換場景
下一篇
Day 07 - 調整程式內部的變數 Dat.gui
系列文
以前端角度探討遊戲化的資訊設計13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言