This site requires JavaScript, please enable it in your browser!
Greenfoot back
ASVBVV
ASVBVV wrote ...

2015/4/16

Testing classes

ASVBVV ASVBVV

2015/4/16

#
I have a 3 different classes, named class 1, class 2 and class 3 respectivly. Can i test if class 1 is touching class 2 in class 3
davmac davmac

2015/4/16

#
First: classes do not touch. Only objects (instances of classes) can touch other objects. You can test if an object is touching any instance of a particular class using the 'isTouching' method. It is perfectly possible to use this method from any class (including another actor subclass) so long as you have a reference to the object that you want to test collisions on.
danpost danpost

2015/4/16

#
davmac wrote...
First: classes do not touch. Only objects (instances of classes) can touch other objects. You can test if an object is touching any instance of a particular class using the 'isTouching' method. It is perfectly possible to use this method from any class (including another actor subclass) so long as you have a reference to the object that you want to test collisions on.
The 'isTouching' method has 'protected' access. You can only call the method on objects of the same class you are calling the method from. In other words, you cannot call 'isTouching' to check if an object of Class1 is touching an object of any class (Class2 -- which could also be Class1 or Class3) from Class3 (which is not Class1). You would have to override the 'isTouching' method in Class3 and give it 'public' access to be able to do that:
// in Class1, add the overriding method
public boolean isTouching(Class cls)
{
    return super.isTouching(cls);
}
// then, in Class3
Class1 class1 = (Class1) getWorld().getObjects(Class1.class).get(0); // this line added just to show what 'class3' may refer to
if (class1.isTouching(Class2.class)) // this would now work
davmac davmac

2015/4/16

#
danpost wrote...
The 'isTouching' method has 'protected' access
I forgot that was the case - good catch.
You need to login to post a reply.