失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 微信小程序-贪吃蛇关键代码

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

时间:2023-12-25 05:58:09

相关推荐

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

首先说明一下,微信小程序是不能发布游戏的。

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

//获取手指按下坐标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);}

如果觉得《微信小程序-贪吃蛇关键代码》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。