微信小程序-貪喫蛇關鍵代碼

首先說明一下,微信小程序是不能發佈遊戲的。

關鍵代碼一:手指按下,滑動,彈起,確定蛇頭轉的方向,代碼如下

//獲取手指按下座標
touchStart:function(e){
	startX = e.touches[0].x;
	startY = e.touches[0].y;
},
//獲取手指移動座標
touchMove:function(e){
	moveX = e.touches[0].x;
	moveY = e.touches[0].y;

	distX = moveX – startX;
	distY = moveY – startY;

	if(Math.abs(distX) > Math.abs(distY) && distX > 0){
		console.log(“right”);
		direction = “right”;
	}else if(Math.abs(distX) > Math.abs(distY) && distX < 0){
		console.log(“left”);
		direction = “left”;
	}else if(Math.abs(distX) < Math.abs(distY) && distY > 0){
		console.log(“bottom”);
		direction = “bottom”;
	}else if(Math.abs(distX) < Math.abs(distY) && distY < 0){
		console.log(“top”);
		direction = “top”;
	}
},
touchEnd:function(){
	snakeDirection = direction;
},

關鍵代碼二:碰撞檢測

//碰撞函數
function collide(obj1,obj2){

	var l1 = obj1.x;
	var r1 = l1 + obj1.w;
	var t1 = obj1.y;
	var b1 = t1+obj1.h;

	var l2 = obj2.x;
	var r2 = l2 + obj2.w;
	var t2 = obj2.y;
	var b2 = t2 + obj2.h;

	if(r1>l2 && l1<r2 && b1>t2 && t1<b2){
		return true;
	}else {
		return false;
	}
}
關鍵代碼三:繪製矩形

function draw(obj){
	context.setFillStyle(obj.color);
	context.beginPath();
	context.rect(obj.x,obj.y,obj.w,obj.h);
	context.closePath();
	context.fill();
}

附帶一個簡單隨機數方法

//隨機函數
function rand(min,max){
	return parseInt(Math.random()*(max-min)+min);
}














發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章