Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:在运行时将类作为参数传递_Java_Game Engine - Fatal编程技术网

Java:在运行时将类作为参数传递

Java:在运行时将类作为参数传递,java,game-engine,Java,Game Engine,我在写一种游戏引擎。我的所有对象都是从GameObject类扩展而来的。我需要能够检查一个对象是否与另一个对象接触,并指定类型。因此,我的代码是: public boolean collidesWith(GameObject caller, Class collideType) { for( /* the array of all GameObjects */ ) { // only check against objects of type collideType

我在写一种游戏引擎。我的所有对象都是从
GameObject
类扩展而来的。我需要能够检查一个对象是否与另一个对象接触,并指定类型。因此,我的代码是:

public boolean collidesWith(GameObject caller, Class collideType) {
    for( /* the array of all GameObjects */ ) {

        // only check against objects of type collideType
        // this line says "cannot find symbol: collideType"
        if(gameObjects[i] instanceof collideType) {
            // continue doing collision checks
            // return true in here somewhere
        }
        else continue;
    }
    return false;
}
我不明白的是如何将类似于
BouncyBall
的东西传递给
collidesWith()
。理想情况下,我不想为
collidesWith()
的每次调用都创建一个实例,尽管如果我绝对必须,我可以使用它

这里大量的问题和答案都涉及到一些愚蠢的事情,比如:

  • 使用
    instanceof
  • 我是否想通过一门课
  • 我是否真的想通过一门课

我需要使用反射吗?我必须获取类的名称并将其与
equals()
进行比较吗?是否需要创建实例?

instanceof运算符需要类的文字名称。例如:

if(gameObjects[i] instanceof BouncingBall) {
collidesWith(caller, BouncingBall.class)
由于希望它是动态的,因此必须使用Class.isInstance()方法,该方法检查其参数是否是调用该方法的Class对象的实例:

public boolean collidesWith(GameObject caller, Class<? extends GameObject> collideType) {
    for ( /* the array of all GameObjects */ ) {
        if(collideType.isInstance(gameObjects[i])) {
            // continue doing collision checks
            // return true in here somewhere
        }
        else continue;
    }
    return false;
}

如果需要进行碰撞检测,请定义一个通用接口,该接口将为算法提供检查碰撞对象所需的几何信息;然后让每个可碰撞类实现该接口。然后,您的
CollizeSwith()
可以检查实现该接口的任何类型的冲突。如果你想检查几种碰撞类型,我认为你最好创建几种方法,而不是使用反射:这是一个游戏,因此速度至关重要。为什么不在GameObjects中实现一个“collideswith”方法,并将其视为“equals”(即,如果父级实现不正确,则每个类都必须实现?@watery在我的引擎中,所有游戏对象都有一个精灵,其中包含一个Frame[]字段。每个Frame都有一个Hitbox字段(如果我以后需要每帧多个Hitbox,则可能是一个Hitbox[]字段)。Hitbox包含用于检测点(x,y)的方法在hitbox中。这样,碰撞检测的实现就是它所属的位置(此外,它可以被覆盖的位置-比如说,如果我需要HitEllipse或HitPolygon)。太好了!感谢您的快速响应:)