java - LibGDX - 正确使用多边形类

标签 java math libgdx collision-detection

我创建了 Polygon 对象来包裹我的飞机(飞机的 TextureRegion 的大小是 256x74,但这个在游戏中的大小是 70x20)。所以:

TextureRegion[] texRegsAirplane = TextureRegion.split(textureAirplane, 256, 74);
Rectangle bounds = new Rectangle(0, 0, 70, 20);
Polygon polygon = new Polygon(new float[]{0,0,bounds.width,0,bounds.width,bounds.height,0,bounds.height,0,0});

之后,在我的 update 函数中,我更新了它的位置:

public void update(float delta){
    Vector2 v = getPosition();      
    v.add(velocity);
    polygon.setPosition(v.x, v.y);
}

然后我渲染多边形来知道它在哪里:

public void render(SpriteBatch spriteBatch, float pixelPerUnitX, float pixelPerUnitY){
spriteBatch.draw(testTexture,polygon.getX()*pixelPerUnitX, polygon.getY()*pixelPerUnitY, 
            polygon.getBoundingRectangle().width*pixelPerUnitX,polygon.getBoundingRectangle().height*pixelPerUnitY);
}

最后,我创建了 2 架飞机并让它们相互飞行,每次迭代我都尝试检测碰撞,如下所示:

public void detectCollision(){
    for(Airplane airplane1 : Airplanes){
        for(Airplane airplane2 : Airplanes){
            if(Intersector.overlapConvexPolygons(airplane1.getPolygon(), airplane2.getPolygon())){
                //COLLISION DON'T HAPPEN!!!
            }
    }
}

我看到 2 个矩形相互移动并相交,但是 overlapConvexPolygons 函数不起作用!为什么?

最佳答案

我已经解决了这个问题。我错误地指定了顶点。我需要得到矩形多边形,所以我不得不使用以下内容:

polygon = new Polygon(new float[]{0,0,bounds.width,0,bounds.width,bounds.height,0,bounds.height});

如果要旋转多边形对象,请不要忘记设置原点:

polygon.setOrigin(bounds.width/2, bounds.height/2);

现在它完美运行了!

关于java - LibGDX - 正确使用多边形类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14359852/

相关文章:

python - 如何在约束规划中限制零的个数

java - 如何在 ScrollPane 中进行缩放

java - 从 LibGdx 中的 tmx 贴图 (TiledMap) 创建 Sprite 列表

java - Google Spreadsheets API 删除下划线

JavaFX - 音乐开/关切换按钮(不起作用)

java - 继承静态保护内部类,javac报错

matlab - Matlab 中的卷积实践

java - SpringBootTest : No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' available:

arrays - 随机数生成器过于频繁地重复某些数字

java - Libgdx 如何设置PerspectiveCamera的渲染距离?