本片文章是android仿摩拜貼紙碰撞|氣泡碰撞的補(bǔ)充苞轿。
好多同學(xué)私信問我茅诱,圓形邊界如何創(chuàng)建,今天就寫篇文章一起學(xué)習(xí)下搬卒。
在android仿摩拜貼紙碰撞|氣泡碰撞中的評論中瑟俭,給大家提供了一種思路,就是通過繪制正多邊形的方式契邀,近似看做圓形摆寄,實際上當(dāng)邊足夠多時,就是一個圓坯门。
現(xiàn)在需要做的就是確定正多邊形的每一個頂點(diǎn)的坐標(biāo)(x,y)以及正多邊形邊的長度和角度微饥。
/**
* 根據(jù)半徑獲取多邊形每個點(diǎn)的坐標(biāo)位置
*
* @param n 多邊形邊數(shù)
* @param r 半徑
* @return
*/
public ArrayList polygon2(int n, int r) {
float segmentlength = Double.valueOf(r * Math.sin(Math.PI / n)).floatValue(); // 計算邊長
ArrayList<float[]> doubles = new ArrayList<>();
double theta = 2 * Math.PI / n; // 角度
for (int i = 0; i < n + 1; i++) {
float x, y = 0f;
x = Double.valueOf(r * Math.cos(theta * i)).floatValue();
y = Double.valueOf(r * Math.sin(theta * i)).floatValue();
float[] xy = new float[4];
xy[0] = x + r;
xy[1] = y + r;
xy[2] = segmentlength;
xy[3] = Double.valueOf(theta * i).floatValue();
doubles.add(xy);
}
return doubles;
}
生成圓形邊界,這里使用polygonShape.setAsBox(height, width, new Vec2(x,y), angle)繪制每一條邊古戴,具體看下面代碼欠橘。(這里重點(diǎn)需要關(guān)注物理單位和像素單位的區(qū)別,創(chuàng)建物理模型需要使用物理單位现恼,繪制到屏幕上時肃续,需要使用像素單位)
/**
* 設(shè)置世界邊界 圓形
*/
private void initCircleWorldBounds(Canvas canvas) {
// 繪制圓形邊框
canvas.drawCircle(pWidth / 2, pHeight / 2, pHeight / 2, paint);
if (isInitWorld) {
return;
}
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.STATIC;//設(shè)置零重力,零速度
bodyDef.position.set(0, 0);
Body bodyTop = world.createBody(bodyDef);//世界中創(chuàng)建剛體
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.density = 1f;//物質(zhì)密度
fixtureDef.friction = 0.3f;//摩擦系數(shù)
fixtureDef.restitution = 0.5f;//恢復(fù)系數(shù)
//設(shè)置圓形剛體邊界
ArrayList positions = polygon2(36, Double.valueOf(pHeight / 2).intValue());
for (int i = 0; i < positions.size(); i++) {
float[] xy = (float[]) positions.get(i);
float x = xy[0];
float y = xy[1];
float segmentlength = xy[2];
float angle = xy[3];
PolygonShape polygonShape = new PolygonShape();
// 設(shè)置具有方向的shape
polygonShape.setAsBox(0, pixelsToMeters(segmentlength), new Vec2(pixelsToMeters(x), pixelsToMeters(y)), angle);
fixtureDef.shape = polygonShape;
bodyTop.createFixture(fixtureDef);//剛體添加夾具
}
isInitWorld = true;
}