**3**

# Need tips on collision response for a 2D ball hitting another 2D ball that is controlled by an accelerometer

###
#1
Members - Reputation: **608**

Posted 15 July 2012 - 12:20 PM

Our main point of interest is how I should write the code that will give the ball that is hit by the cue ball its collision response; A feedback after the cue ball hits the targeted ball. All balls mentioned do not have mass, are not affected by gravity, and have the same radius/diameter/rigid body.

My little idea was formed by relying on Math.Alan2(), which I can use to translate Cartesian coordinates (the coordinates we normally associate with (x, y)) to polar coordinates (the line of collision P, the normal of the line N). From that static method, I can obtain the Theta value. Then I continue onwards by doing sine and cosine on the Theta.

What I got confused with, is how should I calculate the new velocity on the line of collision after I have gotten the the sine and cosine of Theta for the targeted ball? And how does that integrates fully with the aforementioned accelerometer, which I am able to get the cue ball's acceleration?

If anyone can enlighten me, I will be truly grateful. Thanks in advance.

###
#2
Members - Reputation: **235**

Posted 15 July 2012 - 06:04 PM

http://en.wikipedia.org/wiki/Collision_detection

It even has this lovely illustration to go with it:

http://en.wikipedia.org/wiki/File:Elastischer_sto%C3%9F_2D.gif

Try rephrasing your post if this doesn't answer your question

###
#3
Members - Reputation: **608**

Posted 16 July 2012 - 01:17 AM

I have two balls, A and C.

C is our cue ball, a ball that is controlled by an accelerometer in which a player tilts the phone for it to accelerate in the direction of the incline of the tilted slope.

A is the ball that is not controlled by the player. Its purpose is to let the cue ball C hit A, thus A acts as a movable obstacle. We name A as our targeted ball.

I have understood the principle of collision detection, in which it checks if the cue ball C and the targeted ball A overlaps each other's area. Now, I wanted to know what I should do with how the balls C and A both should react after a collision has been detected. This event is called the collision response, something that I Googled upon.

Upon further research, so far, when the balls C and A were to collide, there is a line connecting to the centers of the two balls. This line connects the two positions that registers the collision as true. By Google search, this line is called the "line of collision." Another line goes through the line of collision, and becomes both balls' tangent lines. This is known as the "normal" of the line of collision.

The last ingredient is the collision angle, or the angle from the X axis to the line of collision. This angle is named Theta. According to the research on Google, adding all of these together, we are converting the Cartesian coordinates (x, y) to its equivalent polar coordinates (p, n).

Now, this is where I lost my way, and I'll try to rephrase my question as nicely as possible. We have two balls, C and A. Both of these balls have positions and velocities known by the program. Both of these balls do not have any mass, and are not affected by gravity (because gravity is facing down on the Z axis, into the screen). We have the line of collision and its normal. And we have the Theta angle and a way to convert to the balls' Cartesian coordinates to polar coordinates.

My guess is that we can use the Theta angle and its polar coordinates to "rotate" the line of collision, so that the line of collision is on the X axis, which makes it easier to work with.

From here, I am confused with how I should write the Java code, so that I can calculate how both balls should react. In short, I can picture both balls bumping one another at different speeds on the X axis.

The problem is, when implementing the physics, I see that it requires mass from the two balls, and assumes that both balls do not go through one another. I didn't give these balls a definite mass, nor did I wrote the code that makes them unable to overlap one another.

How should I improvise so that the physics become ideal enough?

I see that I have to post my code, but I unable to, due to my circumstances of me on the phone. *sigh*

###
#4
Members - Reputation: **735**

Posted 16 July 2012 - 03:49 AM

edit: To be a bit more specific, lets say u1 and u2 are the velocities before the collision and n is the normalized vector from ball 1 to ball 2 at the point of collision. The velocity changes are along the direction of n, and to conserve the momenta they have to be the same, i.e.,

v1 = u1 - a*n

v2 = u2 + a*n

for an elastic collision the parameter a can be calculated with the conservation of the energies. The result I calculated is

a = <u1 - u2,n>

where < . ,. > denotes the inner product. That is, the total change in velocity a*n is the projection of the difference u1 - u2 onto the 'line of collision'

**Edited by Inferiarum, 16 July 2012 - 07:20 AM.**

###
#5
Members - Reputation: **608**

Posted 16 July 2012 - 06:39 AM

**NOTE: THERE ARE TWO VERSIONS, BOTH OF THESE FAILED FOR THE REASON OF OVERLAPPING ISSUES**)

private void collisionResponse(Ball b) { // TODO: Work more on ball-to-ball collision response. double theta = Math.atan2(this.position[1] - b.position[1], this.position[0] - b.position[0]); double sin = Math.sin(theta); double cos = Math.cos(theta); double p1 = b.speed[0] * cos + b.speed[1] * sin; double p2 = -b.speed[0] * sin + b.speed[1] * cos; double P1 = this.speed[0] * cos + this.speed[1] * sin; double P2 = -this.speed[0] * sin + this.speed[1] * cos; double pAfter = p1 + 2 * P1; double PAfter = 2 * p1 + P1; sin = Math.sin(-theta); cos = Math.cos(-theta); b.speed[0] = (float) (pAfter * cos + p2 * sin); b.speed[1] = (float) (-pAfter * sin + p2 * cos); this.speed[0] = (float) (PAfter * cos + P2 * sin); this.speed[1] = (float) (-PAfter * sin + P2 * cos); } private void collisionResponse2(Ball b) { double xVelocity = this.speed[0] - b.speed[0]; double yVelocity = this.speed[1] - b.speed[1]; double xDist = this.position[0] - b.position[0]; double yDist = this.position[1] - b.position[1]; double distSquared = xDist * xDist + yDist * yDist; double dotProduct = xDist * xVelocity + yDist * yVelocity; if (dotProduct > 0) { double collisionScale = dotProduct / distSquared; double xCollision = xDist * collisionScale; double yCollision = yDist * collisionScale; b.speed[0] += xCollision * 10; b.speed[1] += yCollision * 10; this.speed[0] -= xCollision * 10; this.speed[1] -= yCollision * 10; } }

The only main issue is balls can overlap one another easily. Here's a diagram of what I want, and what it really happened. (Purple text = What really happened)

I don't know the algorithm for the overlapping issue. If anyone can enlighten me this, I'm deeply grateful. Thanks in advance.

###
#7
Members - Reputation: **887**

Posted 16 July 2012 - 07:03 AM

Anyway a simple collision resolution for this case is to simply offset each ball by half the penetration.

void resolveCollision(Ball &a, Ball &b) { vec2 diff = a.position-b.position; double dist = length(diff); double penetration = max(0, a.radius + b.radius - dist); a.position += 0.5*penetration*diff/length; b.position -= 0.5*penetration*diff/length; }Then you just apply that iteratively to all colliding pairs of balls and either have "multi collision" being sorted out over multiple time steps, or iterate this until there is no collisions anymore.

This doesn't handle velocity yet but I didn't really get how you want that resolved anyway? just cancel out relative movement? elastic collision

**Edited by japro, 16 July 2012 - 07:14 AM.**

###
#9
Members - Reputation: **735**

Posted 16 July 2012 - 07:51 AM

###
#10
Members - Reputation: **322**

Posted 16 July 2012 - 09:56 AM

1. I would find the center of the ball and the radius

2. When a ball move I would loop through all balls and check if the ball 1's radius + ball 2's radius < magnitute(ball 2's pos - ball 1's pos)

3. If the balls are moving with speed higher than ball 1's diameter + ball 2's diameter, I would make the same checks like in 2 but this time with half the current speed (creating temp location and then checking for collisions... also this is bad idea to be hard coded. I mean divide ur speed by the diameter to find out how many checks u need and use loop to check all needed positions so u are sure u won't miss the ball)

4. if collision occurs ( 2. returns true ), get the reverse vector and find out the best position so they don't overlap.

Lame try to show u whats in my mind..

###
#11
Members - Reputation: **608**

Posted 17 July 2012 - 07:18 AM

Not sure why everyone is so fascinated by working with angles. It usually makes things more complicated. Anyway a simple collision resolution for this case is to simply offset each ball by half the penetration.

void resolveCollision(Ball &a, Ball &b) { vec2 diff = a.position-b.position; double dist = length(diff); double penetration = max(0, a.radius + b.radius - dist); a.position += 0.5*penetration*diff/length; b.position -= 0.5*penetration*diff/length; }Then you just apply that iteratively to all colliding pairs of balls and either have "multi collision" being sorted out over multiple time steps, or iterate this until there is no collisions anymore. This doesn't handle velocity yet but I didn't really get how you want that resolved anyway? just cancel out relative movement? elastic collision

This. You are God! Well, actually, I have never thought about penetration and try to re-offset (or "onset") the position back. It just didn't pop into my mind until your post showed up. Deeply grateful, indeed.

Is there a reason you don't want to use a physics library for this?

Well yes. This is my assignment. We have to learn how the physics behind collision crash courses work and we need ot fully grasp the concepts of it. If I were to rely on a physics library, it would destroy the main purpose of my assignment, even if everything in my program works flawlessly. Another factor is I'm more biased on technique rather than reliance on libraries and avoiding "reinventing the wheel."

All of that is of another topic, I guess. I hoped this answers your question.

I'm not really experienced programmer but heres' what I would do: 1. I would find the center of the ball and the radius 2. When a ball move I would loop through all balls and check if the ball 1's radius + ball 2's radius < magnitute(ball 2's pos - ball 1's pos) 3. If the balls are moving with speed higher than ball 1's diameter + ball 2's diameter, I would make the same checks like in 2 but this time with half the current speed (creating temp location and then checking for collisions... also this is bad idea to be hard coded. I mean divide ur speed by the diameter to find out how many checks u need and use loop to check all needed positions so u are sure u won't miss the ball) 4. if collision occurs ( 2. returns true ), get the reverse vector and find out the best position so they don't overlap. Lame try to show u whats in my mind..

Your GIF work actually helped me out more than you think; Along with japro's algorithm, his theory, and your GIF, when combined, it really taught me a lot more. Without your GIF, I wouldn't be able to think up on what japro's meaning of "penetration" and what is its usefulness.

In short, your GIF taught me what penetration really means. Japro's algorithm is what taught me how I should execute it. Combined, on my Android phone, it tells me how objects react to the cue ball with the accelerometer, and noticed that the effects seen is the same as how Mario uses the backward long jump to glitch through most of the stages. The effect is basically pushing two overlapping objects apart.

I learned a lot from you guys. Thank you! Deeply appreciated.

###
#12
Members - Reputation: **608**

Posted 01 August 2012 - 09:51 AM

I have found another solution on Google by chance, and I decided to help others who are also looking for collision responses by linking directly and save time Googling for one.

The link is here.

The alternate solution (Author: eBusiness):

public void handleCollisions(){ double xDist, yDist; for(int i = 0; i < balls.size(); i++){ Ball A = balls.get(i); for(int j = i+1; j < balls.size(); j++){ Ball B = balls.get(j); xDist = A.getCenterX() - B.getCenterX(); yDist = A.getCenterY() - B.getCenterY(); double distSquared = xDist*xDist + yDist*yDist; //Check the squared distances instead of the the distances, same result, but avoids a square root. if(distSquared <= (A.radius + B.radius)*(A.radius + B.radius)){ double xVelocity = B.xVel - A.xVel; double yVelocity = B.yVel - A.yVel; double dotProduct = xDist*xVelocity + yDist*yVelocity; //Neat vector maths, used for checking if the objects moves towards one another. if(dotProduct > 0){ double collisionScale = dotProduct / distSquared; double xCollision = xDist * collisionScale; double yCollision = yDist * collisionScale; //The Collision vector is the speed difference projected on the Dist vector, //thus it is the component of the speed difference needed for the collision. double combinedMass = A.mass + B.mass; double collisionWeightA = 2 * B.mass / combinedMass; double collisionWeightB = 2 * A.mass / combinedMass; A.xVel += collisionWeightA * xCollision; A.yVel += collisionWeightA * yCollision; B.xVel -= collisionWeightB * xCollision; B.yVel -= collisionWeightB * yCollision; } } } } }

**Edited by tom_mai78101, 01 August 2012 - 09:52 AM.**