首页 > 解决方案 > 物质JS空心圆体

问题描述

有什么方法可以在物质 js 中制作空心圆圈吗?我什么也没找到

在此处输入图像描述

如上图所示,黑色圆圈内有一个红色圆圈。这就是我想做的。

这是有效但不是我想要的代码。

// Black circle
Matter.Bodies.circle(120, 120, 180, {
    mass: 50
})

// Red circle
Matter.Bodies.circle(60, 60, 30, {
    mass: 50
})

标签: javascriptmatter.js

解决方案


我一直想做点什么。似乎影响中空形状的最佳方法是用一系列矩形近似其表面:https ://github.com/liabru/matter-js/issues/380 。

如果您希望外环能够与其他对象发生碰撞,您将需要创建一个Body并将每个矩形作为其“部分”之一。这是我用来创建各种容器多边形形状的函数;具有足够大的边数,这是一个相当好的近似环:

/**
 * Creates a polygon that can contain other objects by putting together
 * rectangles for each edge of the polygon.
 *
 * @param x, y: the center of the polygon
 * @param sides: the number of sides of the polygon
 * @param radius: the radius of the circumscribing circle
 * @param options: a set of properties applied to each edge of the polygon.
 * There are a few special options:
 *  'extraLength': The factor to increase the length of each rectangle by to
 *  avoid inner and outer gaps. Typically around 1.15.
 *  'width': the width of each rectangluar side. If this is too small, the
 *  matter-js engine will require a smaller interval to prevent objects from
 *  being pushed in / out of teh object.
 *  'initialRotation': The initital rotation to be applied to the shape.
 */
function containerPolygon(x: number, y: number, sides: number, radius: number, options): Body {
  const width = options.width || 20; delete options.width;
  const extraLength = options.extraLength || 1.15; delete options.extraLength;
  const initialRotation = options.initialRotation || 0; delete options.initialRotation;

  const theta = 2 * Math.PI / sides;
  const sideLength = 2 * radius * theta/2 * extraLength;

  const parts = [];
  for (let i = 0; i < sides; i++) {
    // We'll build thin sides and then translate + rotate them appropriately.
    const body = Bodies.rectangle(0, 0, sideLength, width);
    Body.rotate(body, i * theta);
    Body.translate(body, {x: radius * Math.sin(i * theta), y: -radius * Math.cos(i * theta)});
    parts.push(body);
  }
  const ret = Body.create(options);
  Body.setParts(ret, parts);
  if (initialRotation) {
    Body.rotate(ret, initialRotation);
  }
  Body.translate(ret, {x: x, y: y});

  return ret;
}

推荐阅读