gpt4 book ai didi

java - 椭圆形碰撞检测无法正常工作

转载 作者:行者123 更新时间:2023-11-30 05:12:43 25 4
gpt4 key购买 nike

所以我试图实现一个测试,其中椭圆形可以与圆形连接,但它不起作用。

edist = (float) Math.sqrt(
Math.pow((px + ((pwidth/2) )) - (bx + (bsize/2)), 2 ) +
Math.pow(-((py + ((pwidth/2)) ) - (bx + (bsize/2))), 2 )
);

这是完整的代码(需要 Slick2D):

import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;

public class ColTest extends BasicGame{


float px = 50;
float py = 50;
float pheight = 50;
float pwidth = 50;



float bx = 200;
float by = 200;
float bsize = 200;

float edist;

float pspeed = 3;
Input input;

public ColTest()
{
super("ColTest");
}

@Override
public void init(GameContainer gc)
throws SlickException {

}

@Override
public void update(GameContainer gc, int delta)
throws SlickException
{
input = gc.getInput();

try{
if(input.isKeyDown(Input.KEY_UP))
py-=pspeed;

if(input.isKeyDown(Input.KEY_DOWN))
py+=pspeed;

if(input.isKeyDown(Input.KEY_LEFT))
px-=pspeed;

if(input.isKeyDown(Input.KEY_RIGHT))
px+=pspeed;
}

catch(Exception e){}
}

public void render(GameContainer gc, Graphics g)
throws SlickException
{
g.setColor(new Color(255,255,255));
g.drawString("col: " + col(), 10, 10);
g.drawString("edist: " + edist + " dist: " + dist, 10, 100);

g.fillRect(px, py, pwidth, pheight);
g.setColor(new Color(255,0,255));
g.fillOval(px, py, pwidth, pheight);
g.setColor(new Color(255,255,255));
g.fillOval(200, 200, 200, 200);

}

public boolean col(){

edist = (float) Math.sqrt(Math.pow((px + ((pwidth/2) )) - (bx + (bsize/2)), 2) + Math.pow(-((py + ((pwidth/2)) ) - (bx + (bsize/2))), 2));

if(edist <= (bsize/2) + (px + (pwidth/2)))
return true;

else
return false;
}

public float rotate(float x, float y, float ox, float oy, float a, boolean b)
{
float dst = (float) Math.sqrt(Math.pow(x-ox,2.0)+ Math.pow(y-oy,2.0));

float oa = (float) Math.atan2(y-oy,x-ox);

if(b)
return (float) Math.cos(oa + Math.toRadians(a))*dst+ox;

else
return (float) Math.sin(oa + Math.toRadians(a))*dst+oy;

}

public static void main(String[] args)
throws SlickException
{
AppGameContainer app =
new AppGameContainer( new ColTest() );

app.setShowFPS(false);
app.setAlwaysRender(true);
app.setTargetFrameRate(60);
app.setDisplayMode(800, 600, false);
app.start();
}
}

最佳答案

使用椭圆形是绝对要求吗?您可以通过用多个圆圈来表示更奇特的形状之间的碰撞。这样,您就可以在圆圈之间使用非常简单的碰撞检测,并且仍然为查看器实现较高的准确度。

collision(c1, c2) {
dx = c1.x - c2.x;
dy = c1.y - c2.y;
dist = c1.radius + c2.radius;

return (dx * dx + dy * dy <= dist * dist)
}

alt text
(来源:strd6.com)

关于java - 椭圆形碰撞检测无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2836184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com