微信小程序弹球游戏
枫渝浪天下 人气:0实验内容:
小球按照随机的角度直线运动,如果碰到四壁则反弹。你们不需要做游戏计时、设置小球及背景颜色等,只完成小球在方框内反弹运动的功能。这里主要考查绘图知识,数学计算能力,以及对定时器的应用。
实验效果(最简单版本):
实验代码:
index.js
// index.js Page({ data:{ cx:200, cy:50, destinaX:3, destinaY:2 }, //初次渲染触发 onReady:function(){ var c=wx.createCanvasContext("canvasTest"); // var c=wx.createSelectorQuery('canvasTest') var that=this; var timer=setInterval(canvasSize,20); function canvasSize(){ //画布数据 const width=300; const height=300; const speed=2; const r=7; //下面是相对左上角基点距离 和画布大小 c.rect(0,0,width,height); c.stroke(); //球会根据实时位置发生变化 c.beginPath(); var ox1=that.datacox; var oy1=that.datacoy; ox1=that.data.destinaX*speed+that.data.cx; oy1=that.data.cy-that.data.destinaY*speed; if(ox1>=width||ox1<=0){ var bounceX=-that.data.destinaX; that.setData({destinaX:bounceX}); ox1=that.data.destinaX*speed+that.data.cx; } if(oy1>=height||oy1<=0){ var bounceY=-that.data.destinaY; that.setData({destinaY:bounceY}); oy1=that.data.cy-that.data.destinaY*speed; } console.log(that.data.ox1,that.data.oy1); that.setData({cx:ox1,cy:oy1}); c.arc(that.data.cx,that.data.cy,r,0,2*Math.PI); c.fill(); c.stroke(); c.draw(); } } })
index.wxml
<!--index.wxml--> <view class="canvasStyle"> <canvas canvas-id="canvasTest" style="width: 300px;height: 300px;"></canvas> </view>
index.wxss
/**index.wxss**/ .canvasStyle{ display: flex; justify-content: center; margin: 10px; margin-top: 70px; background-color: aqua; }
加载全部内容