0

I wasn't sure how to really ask this question so I just made a new thread. I'm trying to see if I can instantaneously check if my ball intersects with any rectangle in an array.

if(ball.getBounds2D().intersects(bricksEasy)) <-- bricks easy is a 2D array of rectangles

Right now I'm avoiding just iterating through the whole array to avoid delay. Any solutions I could use? Appreciate it.

1
  • "I'm avoiding just iterating through the whole array to avoid delay." - That reasoning makes no sense. Either you or some existing code needs to iterate and as you already found out, there is no such existing code. So there is only you left who can iterate that array. Commented Sep 30, 2017 at 11:18

1 Answer 1

1

Right now I'm avoiding just iterating through the whole array to avoid delay. Any solutions I could use?

It will not cause any delay if you stop iterating as soon as you detected a collision.

If you manipulate a Rectangle2D instance, you could use this overloaded instance method :

public boolean intersects(Rectangle2D r)

And to exit from the iteration as soon a match is done, you could use the anyMatch() predicate :

Rectangle2D ball2D = ...;
Rectangle2D[] bricksEasy = ...;
boolean isAnyIntersection = Arrays.stream(bricksEasy).anyMatch(brick -> brick.intersects(ball2D));

You can also do it by using a method reference with the ball2D variable as target of:

Rectangle2D ball2D = ...;
Rectangle2D[] bricksEasy = ...;
boolean isAnyIntersection = Arrays.stream(bricksEasy).anyMatch(ball2D::intersects);
Sign up to request clarification or add additional context in comments.

4 Comments

Is this part of Java 8?
@Daniel Yoon It is, indeed.
Yea I'm not too accustomed to Java 8 features besides lambda expressions :/
I understand. But I think that you should start to accustom to right now. Java 8 is not so young. Start with basics as Streams and predicates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.