Reputation: 179
For lack of a better title, I am looking for the best way to check this:
I have an arrow object. I also have objects that I want to code collision for, object1, object2, ... objectx, with objectx being the last object I am checking for.
In the collision system of the engine I am using, there is an x1 object, and an x2 object, which can vary for objects in a collision. For example if an arrow hits any object 1 through x, I don't know from the start if the arrow is x1 or x2, but it can be easily checked.
I want to write an if statement that is true if one object is an arrow, and the other is one of my many objects. This is what I have so far:
if ((x1Type.equals("arrow") || x2Type.equals("arrow")) && ((x1Type.equals("object1") || x1Type.equals("object2") || x1Type.equals("object3") || ... || x1Type.equals("objectx")) ||
x2Type.equals("object1") || x2Type.equals("object2") || x2Type.equals("object3") || ... || x2Type.equals("objectx")))
This code works, but I am pretty sure there is a better way to do it. And sorry for being kinda vague, this was a hard to state question.
Upvotes: 0
Views: 47
Reputation: 9618
Assuming that you can access the type of your object from the objects themselves, what do you think about using a Collection
(typically, a Set
) to check whether the colliding object is supposed to be impacted by your arrow or not?
I'm suggesting something like this:
public static final String TYPENAME_ARROW = "arrow";
public static final Set<String> impactedTypes = new HashSet<String>() {
{
add("object1");
add("object2");
add("object3");
add("objectx");
}
};
public static void collide(final Object x1, final Object x2) {
if (x1.getType().equals(ARROW_TYPE)) {
if (impactedTypes.contains(x2.getType())) {
// hit x2 with x1;
}
} else if (x2.getType().equals(ARROW_TYPE)) {
if (impactedTypes.contains(x1.getType())) {
// hit x1 with x2;
}
}
}
I wanted to put this as a comment but well, that's too big. I might be completely wrong, in which case, please kindly let me know and I'll just delete my answer :)
Upvotes: 1