我的碰撞检测在java小程序中生成低fps
这是我第一次尝试碰撞算法。我尝试用边界检查对象的矩形大小。现在,在这个应用程序中,我制作了运行子弹并检查碰撞是否在无延时的while循环中。问题是,当我产生大约30-40发子弹时,fps变得很低。如果有人能教我写碰撞检测的健壮方法,我会很高兴 顺便说一下,我使用了一个java向量集合(可能迭代不够快,或者我的代码太乱)我的碰撞检测在java小程序中生成低fps,java,applet,collision-detection,Java,Applet,Collision Detection,这是我第一次尝试碰撞算法。我尝试用边界检查对象的矩形大小。现在,在这个应用程序中,我制作了运行子弹并检查碰撞是否在无延时的while循环中。问题是,当我产生大约30-40发子弹时,fps变得很低。如果有人能教我写碰撞检测的健壮方法,我会很高兴 顺便说一下,我使用了一个java向量集合(可能迭代不够快,或者我的代码太乱) public void checkBoundary(int-width,int-height)//小程序的宽度和高度 { 对于(int i=0;i0&& 元素x
public void checkBoundary(int-width,int-height)//小程序的宽度和高度
{
对于(int i=0;i
此向量存储子弹的对象,左下角为(x,y),左下角为(宽度,高度)。remove()
是一个非常昂贵的操作,创建新列表、将所需元素复制到列表中并用新列表替换原始列表要快得多
我还建议您使用ArrayList
而不是Vector
。如果需要同步,请在Collections.synchronizedList()中包装ArrayList
试试这个,几乎可以立即工作-0&&
元素.y+元素.height>0&&
元素x<宽度和
元素y<高度){
新增(要素);
}
}
vec=newVec;
}
首先,您的算法不正确,因为当您使用vec.remove(i)进行删除时
,则i+1
元素成为i
元素,因此跳过一个元素
性能问题源于这样一个事实:在最坏的情况下,由于每个后续元素都需要向左移动,因此每个元素都会删除成本O(n)
。试试这个:
public void checkBoundary(int width, int height) //width and height of the applet
{
LinkedList<T> outofbounds = new LinkedList<T>();
for(int i = 0; i < vec.size(); i++)
{
if(vec.get(i).x + vec.get(i).width <= 0 ||
vec.get(i).y + vec.get(i).height <= 0 ||
vec.get(i).x >= width ||
vec.get(i).y >= height)
outofbounds.add(vec.at(i));
}
vec.removeAll(outofbounds);
}
我在java集合中的一个主要困惑是ArrayList和Vector有何不同?顺便说一下,我个人还没有理解“同步”这个术语,所以你能帮我澄清一下java中的同步吗?我认为它只适用于线程方法…“synchronized”方法是一种在任何时间只能由一个线程同时执行的方法。与同步类相同,只是它的所有方法都作为一个同步。这有助于防止一些未定义的行为,即。然而,同步意味着成本:与常规方法调用相比,对同步方法的每次调用花费的时间更长。因此,如果您不打算在多个线程之间使用同一实例,请尽量避免使用同步。为了更快地获得更好的帮助,请发布一个。
removeAll()
是一个昂贵的操作:函数需要25秒来处理100k个元素。
public static void checkBoundary(int width, int height) // width and height of the applet
{
int size = vec.size();
List <YourObjectType> newVec = new ArrayList <YourObjectType>(size);
for (int i = 0; i < size; i++) {
YourObjectType element = vec.get(i);
if (element.x + element.width > 0 &&
element.y + element.height > 0 &&
element.x < width &&
element.y < height) {
newVec.add(element);
}
}
vec = newVec;
}
public void checkBoundary(int width, int height) //width and height of the applet
{
LinkedList<T> outofbounds = new LinkedList<T>();
for(int i = 0; i < vec.size(); i++)
{
if(vec.get(i).x + vec.get(i).width <= 0 ||
vec.get(i).y + vec.get(i).height <= 0 ||
vec.get(i).x >= width ||
vec.get(i).y >= height)
outofbounds.add(vec.at(i));
}
vec.removeAll(outofbounds);
}
public void checkBoundary(int width, int height) //width and height of the applet
{
LinkedList<T> newvec = new LinkedList<T>();
for(int i = 0; i < vec.size(); i++)
{
if(vec.get(i).x + vec.get(i).width <= 0 ||
vec.get(i).y + vec.get(i).height <= 0 ||
vec.get(i).x >= width ||
vec.get(i).y >= height)
continue;
newvec.add(vec.at(i));
}
vec.clear();
// or vec = newvec if there are no others reference sharing the same object as vec
vec.addAll(newvec);
}