• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
tom_mai78101

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

11 posts in this topic

I have written some lines of code that allows me to accelerate a user controlled cue ball. These lines of code has to do with Android and it's accelerometer. Now, ignore the Android. I am on my Android phone typing all of this.

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.
0

Share this post


Link to post
Share on other sites
I have to admit, I didn't really understood the situation and question. Is it the physics of the collision you're interested? In that case, I think this wikipedia article may help you:
[url="http://en.wikipedia.org/wiki/Collision_detection"]http://en.wikipedia.org/wiki/Collision_detection[/url]
It even has this lovely illustration to go with it:
[url="http://en.wikipedia.org/wiki/File:Elastischer_sto%C3%9F_2D.gif"]http://en.wikipedia.org/wiki/File:Elastischer_sto%C3%9F_2D.gif[/url]
Try rephrasing your post if this doesn't answer your question :)
0

Share this post


Link to post
Share on other sites
Again, I am typing on the phone.

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*
0

Share this post


Link to post
Share on other sites
To get the speed of the balls you have to work with the momenta. The sum of the momenta has to stay the same and if the collision is fully elastic also the movement energy. If the masses of all balls are the same you can just work with the velocities, i.e., the sum of all velocity vectors has to be the same before and after the collision.

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
0

Share this post


Link to post
Share on other sites
I'm back on my computer. Here's the source: ([b]NOTE: THERE ARE TWO VERSIONS, BOTH OF THESE FAILED FOR THE REASON OF OVERLAPPING ISSUES[/b])

[CODE]
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;
}

}[/CODE]

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)

[img]http://i.imgur.com/6ITch.png[/img]

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

Share this post


Link to post
Share on other sites
With 2 balls you could use some math when moving either of them to make sure they dont overlap, but once you add more balls/walls etc. it becomes more complicated.
0

Share this post


Link to post
Share on other sites
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.
[code]
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;
}
[/code]
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
1

Share this post


Link to post
Share on other sites
if the number of balls is low, you would get better results by never letting the balls overlap in the first place. That is you check for all pairs of balls if they will collide before the next time step. If you find a collision, move the balls to the collision point, resolve the velocities and continue the simulation.
0

Share this post


Link to post
Share on other sites
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.

[img]http://store.picbg.net/pubpic/5B/9D/f834487711105b9d.gif[/img]
Lame try to show u whats in my mind..
1

Share this post


Link to post
Share on other sites
[quote name='japro' timestamp='1342443782' post='4959576'] 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. [code] 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; } [/code] 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 [/quote]

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.

[quote name='rip-off' timestamp='1342444382' post='4959580'] Is there a reason you don't want to use a physics library for this? [/quote]

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. :D

[quote name='Nickie' timestamp='1342454185' post='4959624'] 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. [img]http://store.picbg.net/pubpic/5B/9D/f834487711105b9d.gif[/img] Lame try to show u whats in my mind.. [/quote]

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.
0

Share this post


Link to post
Share on other sites
Not necessarily a bump, but it's worth this post.

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.

[url="http://gamedev.stackexchange.com/questions/20516/ball-collisions-sticking-together"]The link is here.[/url]

The alternate solution (Author: eBusiness):

[CODE]
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;
}
}
}
}
}
[/CODE] Edited by tom_mai78101
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0