您的位置:首页 > 移动开发 > 微信开发

微信小程序-贪吃蛇关键代码

2017-01-13 10:46 429 查看
首先说明一下,微信小程序是不能发布游戏的。

关键代码一:手指按下,滑动,弹起,确定蛇头转的方向,代码如下

//获取手指按下坐标
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息