微信小程序 多个小球根据手机重力感应运动且不重叠,如何实现

微信小程序 多个小球根据手机重力感应运动且不重叠,如何实现,已知微信获取重力方法和canvas

在wxml文件中添加canvas画布,设置宽高和id:


<canvas canvas-id="canvas" style="width: 100%; height: 100%;"></canvas>

在js文件中获取canvas对象和重力感应对象:

const ctx = wx.createCanvasContext('canvas');
wx.onAccelerometerChange(function(res) {
  // 获取手机重力感应数据
  const x = res.x;
  const y = res.y;
});

定义小球的数据结构和生成小球的函数:


const balls = []; // 存储所有小球的数组
const radius = 20; // 小球半径
function createBall(x, y) {
  const ball = {
    x: x,
    y: y,
    r: radius,
    color: 'red'
  };
  // 判断新生成的小球是否与已有的小球重叠
  for (let i = 0; i < balls.length; i++) {
    const dx = balls[i].x - ball.x;
    const dy = balls[i].y - ball.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    if (distance < balls[i].r + ball.r) {
      return null; // 重叠,返回null
    }
  }
  balls.push(ball); // 不重叠,将新小球加入数组
  return ball;
}

在重力感应回调函数中更新每个小球的位置,并在canvas画布上绘制:


wx.onAccelerometerChange(function(res) {
  const x = res.x;
  const y = res.y;
  for (let i = 0; i < balls.length; i++) {
    const ball = balls[i];
    // 根据重力感应数据更新小球位置
    ball.x += x * 2;
    ball.y -= y * 2;
    // 判断小球是否超出画布边界,超出则反弹回来
    if (ball.x - ball.r < 0 || ball.x + ball.r > canvasWidth) {
      x = -x;
    }
    if (ball.y - ball.r < 0 || ball.y + ball.r > canvasHeight) {
      y = -y;
    }
    // 在canvas画布上绘制小球
    ctx.beginPath();
    ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);
    ctx.setFillStyle(ball.color);
    ctx.fill();
    ctx.closePath();
  }
  ctx.draw();
});

在页面加载时调用createBall函数生成多个不重叠的小球:

const canvasWidth = wx.getSystemInfoSync().windowWidth;
const canvasHeight = wx.getSystemInfoSync().windowHeight;
for (let i = 0; i < 10; i++) {
  let x = Math.random() * canvasWidth;
  let y = Math.random() * canvasHeight;
  while (!createBall(x, y)) { // 如果生成的小球与已有的小球重叠,则重新生成
    x = Math.random() * canvasWidth;
    y = Math.random() * canvasHeight;
  }
}