Matter JS hollow circle body

戏子无情 提交于 2021-01-29 13:00:33

问题


Is there any way to make hollow circle in matter js ? I didn't find anything

As you can see above image there is red circle which is located inside of black circle. That is what I want to do.

Here is the code which works but not as I want.

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

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

回答1:


I've been looking to do something. It seems like the best way to effect a hollow shape is to approximate its surface with a series of rectangles: https://github.com/liabru/matter-js/issues/380.

If you want to have the outer ring to be able to collide with other objects, you will want to create a single Body and make each rectangle one of its "parts". Here is the function I used to create various container polygon shapes; with a large enough side count, this is a fairly good approximation of a ring:

/**
 * 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;
}


来源:https://stackoverflow.com/questions/58507514/matter-js-hollow-circle-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!