Note that there are some explanatory texts on larger screens.

plurals
  1. POhandling collisions - array look ups expensive
    primarykey
    data
    text
    <p>I have a collision detection method in my android program to detect when two balls have collided and to calculate their new velocities. Every ball is stored in an array <code>Ball[] ballArray</code>. To handle collisions, I iterate through each ball, take it's center coordinates and calculate a surrounding region. If the center of any other ball lies within this region, then I check the two balls for a collision.</p> <p>My method is basically as follows</p> <pre><code>public void handleCollisions(){ int size = ballArray.length; for(int i = 0; i &lt; size; i++){ Ball ball = ballArray[i]; int centerX = ball.centerX; int centerY = ball.centerY; int radius = ball.radius; //calculate box around ball int lowXLimit = (centerX - radius - largestPossibleRadius); int highXLimit = (centerX + radius + largestPossibleRadius); int lowYLimit = (centerY- radius - largestPossibleRadius); int highYLimit = (centerY+ radius + largestPossibleRadius); for(int j = j+1; j &lt; size; j++){ Ball ball2 = ballArray[j]; int centerX2 = ball.centerX; int centerY2 = ball.centerY; int radius2 = ball.radius; //if ball2 is inside the possible collision region around ball1 if (centerX2 &gt; lowXLimit &amp;&amp; centerX2 &lt; highXLimit &amp;&amp; centerY2 &gt; lowYLimit &amp;&amp; centerY2 &lt; highYLimit) { //do calculations to determine new velocities } } </code></pre> <p>I was getting pretty poor performance from my code and ran a traceview. To my surprise, only around 5% of the execution time in this method is spent doing the collision resolution calculations (quite a number of floating point divisions, multiplications). In fact, around 60-70% of time in this method is simply accessing the balls from the ball array (lines <code>Ball ball = ballArray[i]</code> and <code>Ball ball2 = ballArray[j]</code>). </p> <p>I've tried using an <code>ArrayList</code> but that is even worse. Is there something I can do to speed up this code? perhaps another data structure? It seems like a really long time to me. Should I try reduce the number of member variables in <code>Ball</code>?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload