Search Results

Search found 130 results on 6 pages for 'balls'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • 2D Collision in Canvas - Balls Overlapping When Velocity is High

    - by kushsolitary
    I am doing a simple experiment in canvas using Javascript in which some balls will be thrown on the screen with some initial velocity and then they will bounce on colliding with each other or with the walls. I managed to do the collision with walls perfectly but now the problem is with the collision with other balls. I am using the following code for it: //Check collision between two bodies function collides(b1, b2) { //Find the distance between their mid-points var dx = b1.x - b2.x, dy = b1.y - b2.y, dist = Math.round(Math.sqrt(dx*dx + dy*dy)); //Check if it is a collision if(dist <= (b1.r + b2.r)) { //Calculate the angles var angle = Math.atan2(dy, dx), sin = Math.sin(angle), cos = Math.cos(angle); //Calculate the old velocity components var v1x = b1.vx * cos, v2x = b2.vx * cos, v1y = b1.vy * sin, v2y = b2.vy * sin; //Calculate the new velocity components var vel1x = ((b1.m - b2.m) / (b1.m + b2.m)) * v1x + (2 * b2.m / (b1.m + b2.m)) * v2x, vel2x = (2 * b1.m / (b1.m + b2.m)) * v1x + ((b2.m - b1.m) / (b2.m + b1.m)) * v2x, vel1y = v1y, vel2y = v2y; //Set the new velocities b1.vx = vel1x; b2.vx = vel2x; b1.vy = vel1y; b2.vy = vel2y; } } You can see the experiment here. The problem is, some balls overlap each other and stick together while some of them rebound perfectly. I don't know what is causing this issue. Here's my balls object if that matters: function Ball() { //Random Positions this.x = 50 + Math.random() * W; this.y = 50 + Math.random() * H; //Random radii this.r = 15 + Math.random() * 30; this.m = this.r; //Random velocity components this.vx = 1 + Math.random() * 4; this.vy = 1 + Math.random() * 4; //Random shade of grey color this.c = Math.round(Math.random() * 200); this.draw = function() { ctx.beginPath(); ctx.fillStyle = "rgb(" + this.c + ", " + this.c + ", " + this.c + ")"; ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false); ctx.fill(); ctx.closePath(); } }

    Read the article

  • Friday Fun: Factory Balls – Christmas Edition

    - by Asian Angel
    Your weekend is almost here, but until the work day is over we have another fun holiday game for you. This week your job is to correctly decorate/paint the ornaments that go on the Christmas tree. Simple you say? Maybe, but maybe not! Factory Balls – Christmas Edition The object of the game is to correctly decorate/paint each Christmas ornament exactly as shown in the “sample image” provided for each level. What starts off as simple will quickly have you working to figure out the correct combination or sequence to complete each ornament. Are you ready? The first level serves as a tutorial to help you become comfortable with how to decorate/paint the ornaments. To move an ornament to a paint bucket or cover part of it with one of the helper items simply drag the ornament towards that area. The ornament will automatically move back to its’ starting position when the action is complete. First, a nice coat of red paint followed by covering the middle area with a horizontal belt. Once the belt is on move the ornament to the bucket of yellow paint. Next, you will need to remove the belt, so move the ornament back to the belt’s original position. One ornament finished! As soon as you complete decorating/painting an ornament, you move on to the next level and will be shown the next “sample Image” in the upper right corner. Starting with a coat of orange paint sounds good… Pop the little serrated edge cap on top… Add some blue paint… Almost have it… Place the large serrated edge cap on top… Another dip in the orange paint… And the second ornament is finished. Level three looks a little bit tougher…just work out your pattern of helper items & colors and you will definitely get it! Have fun decorating/painting those ornaments! Note: Starting with level four you will need to start using a combination of two helper items combined at times to properly complete the ornaments. Play Factory Balls – Christmas Edition Latest Features How-To Geek ETC The Complete List of iPad Tips, Tricks, and Tutorials The 50 Best Registry Hacks that Make Windows Better The How-To Geek Holiday Gift Guide (Geeky Stuff We Like) LCD? LED? Plasma? The How-To Geek Guide to HDTV Technology The How-To Geek Guide to Learning Photoshop, Part 8: Filters Improve Digital Photography by Calibrating Your Monitor Exploring the Jungle Ruins Wallpaper Protect Your Privacy When Browsing with Chrome and Iron Browser Free Shipping Day is Friday, December 17, 2010 – National Free Shipping Day Find an Applicable Quote for Any Programming Situation Winter Theme for Windows 7 from Microsoft Score Free In-Flight Wi-Fi Courtesy of Google Chrome

    Read the article

  • Changing balls direction in Pong

    - by hustlerinc
    I'm making a Pong game to get started with game-developement but I've run into a problem that i can't figure out. When trying to change the balls direction it doesn't change. This is the relevant code: function moveBall(){ this.speed = 2.5; this.direction = 2; if(this.direction == 1){ ball.X +=this.speed; } else if(this.direction == 2){ ball.X -=this.speed; } } function collision(){ if(ball.X == 500){ moveBall.direction = 2; } if(ball.X == 300){ moveBall.direction = 1; } } Why doesn't it work? I've tried many different ways, and none of them seem to work. The moveBall.direction changes though, since it alerts the new direction once it reaches the defined ball.X position. If someone could help me I would deeply appreciate it. I've included a JSFiddle link. http://jsfiddle.net/hustlerinc/y4wp3/

    Read the article

  • Do you use Styrofoam balls to model your systems?

    - by Nick D
    [Objective-C] Do you still use Styrofoam balls to model your systems, where each ball represents a class? Tom Love: We do, actually. We've also done a 3D animation version of it, which we found to be nowhere near as useful as the Styrofoam balls. There's something about a physical, conspicuous structure hanging from the ceiling right in the middle of a development project that's regularly updated to provide not only the structure of the system that you're building, but also the current status of each one of the classes. We've done it on 19 projects the last time I've counted. One of them was 1,856 classes, which is big - actually, probably bigger than it should be. It was a big commercial project, so it needed to be somewhat big. Masterminds of Programming It is the first time I've read or heard about using styrofoam balls to model classes. Is that a commonly used technique? And, how does that sort of modeling help us to design better the system? If you have any photos to share which can show us how the classes are represented it'd be great!

    Read the article

  • Bouncing off a circular Boundary with multiple balls?

    - by Anarkie
    I am making a game like this : Yellow Smiley has to escape from red smileys, when yellow smiley hits the boundary game is over, when red smileys hit the boundary they should bounce back with the same angle they came, like shown below: Every 10 seconds a new red smiley comes in the big circle, when red smiley hits yellow, game is over, speed and starting angle of red smileys should be random. I control the yellow smiley with arrow keys. The biggest problem I have reflecting the red smileys from the boundary with the angle they came. I don't know how I can give a starting angle to a red smiley and bouncing it with the angle it came. I would be glad for any tips! My js source code : var canvas = document.getElementById("mycanvas"); var ctx = canvas.getContext("2d"); // Object containing some global Smiley properties. var SmileyApp = { radius: 15, xspeed: 0, yspeed: 0, xpos:200, // x-position of smiley ypos: 200 // y-position of smiley }; var SmileyRed = { radius: 15, xspeed: 0, yspeed: 0, xpos:350, // x-position of smiley ypos: 65 // y-position of smiley }; var SmileyReds = new Array(); for (var i=0; i<5; i++){ SmileyReds[i] = { radius: 15, xspeed: 0, yspeed: 0, xpos:350, // x-position of smiley ypos: 67 // y-position of smiley }; SmileyReds[i].xspeed = Math.floor((Math.random()*50)+1); SmileyReds[i].yspeed = Math.floor((Math.random()*50)+1); } function drawBigCircle() { var centerX = canvas.width / 2; var centerY = canvas.height / 2; var radiusBig = 300; ctx.beginPath(); ctx.arc(centerX, centerY, radiusBig, 0, 2 * Math.PI, false); // context.fillStyle = 'green'; // context.fill(); ctx.lineWidth = 5; // context.strokeStyle = '#003300'; // green ctx.stroke(); } function lineDistance( positionx, positiony ) { var xs = 0; var ys = 0; xs = positionx - 350; xs = xs * xs; ys = positiony - 350; ys = ys * ys; return Math.sqrt( xs + ys ); } function drawSmiley(x,y,r) { // outer border ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(x,y,r, 0, 2*Math.PI); //red ctx.fillStyle="rgba(255,0,0, 0.5)"; ctx.fillStyle="rgba(255,255,0, 0.5)"; ctx.fill(); ctx.stroke(); // mouth ctx.beginPath(); ctx.moveTo(x+0.7*r, y); ctx.arc(x,y,0.7*r, 0, Math.PI, false); // eyes var reye = r/10; var f = 0.4; ctx.moveTo(x+f*r, y-f*r); ctx.arc(x+f*r-reye, y-f*r, reye, 0, 2*Math.PI); ctx.moveTo(x-f*r, y-f*r); ctx.arc(x-f*r+reye, y-f*r, reye, -Math.PI, Math.PI); // nose ctx.moveTo(x,y); ctx.lineTo(x, y-r/2); ctx.lineWidth = 1; ctx.stroke(); } function drawSmileyRed(x,y,r) { // outer border ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(x,y,r, 0, 2*Math.PI); //red ctx.fillStyle="rgba(255,0,0, 0.5)"; //yellow ctx.fillStyle="rgba(255,255,0, 0.5)"; ctx.fill(); ctx.stroke(); // mouth ctx.beginPath(); ctx.moveTo(x+0.4*r, y+10); ctx.arc(x,y+10,0.4*r, 0, Math.PI, true); // eyes var reye = r/10; var f = 0.4; ctx.moveTo(x+f*r, y-f*r); ctx.arc(x+f*r-reye, y-f*r, reye, 0, 2*Math.PI); ctx.moveTo(x-f*r, y-f*r); ctx.arc(x-f*r+reye, y-f*r, reye, -Math.PI, Math.PI); // nose ctx.moveTo(x,y); ctx.lineTo(x, y-r/2); ctx.lineWidth = 1; ctx.stroke(); } // --- Animation of smiley moving with constant speed and bounce back at edges of canvas --- var tprev = 0; // this is used to calculate the time step between two successive calls of run function run(t) { requestAnimationFrame(run); if (t === undefined) { t=0; } var h = t - tprev; // time step tprev = t; SmileyApp.xpos += SmileyApp.xspeed * h/1000; // update position according to constant speed SmileyApp.ypos += SmileyApp.yspeed * h/1000; // update position according to constant speed for (var i=0; i<SmileyReds.length; i++){ SmileyReds[i].xpos += SmileyReds[i].xspeed * h/1000; // update position according to constant speed SmileyReds[i].ypos += SmileyReds[i].yspeed * h/1000; // update position according to constant speed } // change speed direction if smiley hits canvas edges if (lineDistance(SmileyApp.xpos, SmileyApp.ypos) + SmileyApp.radius > 300) { alert("Game Over"); } // redraw smiley at new position ctx.clearRect(0,0,canvas.height, canvas.width); drawBigCircle(); drawSmiley(SmileyApp.xpos, SmileyApp.ypos, SmileyApp.radius); for (var i=0; i<SmileyReds.length; i++){ drawSmileyRed(SmileyReds[i].xpos, SmileyReds[i].ypos, SmileyReds[i].radius); } } // uncomment these two lines to get every going // SmileyApp.speed = 100; run(); // --- Control smiley motion with left/right arrow keys function arrowkeyCB(event) { event.preventDefault(); if (event.keyCode === 37) { // left arrow SmileyApp.xspeed = -100; SmileyApp.yspeed = 0; } else if (event.keyCode === 39) { // right arrow SmileyApp.xspeed = 100; SmileyApp.yspeed = 0; } else if (event.keyCode === 38) { // up arrow SmileyApp.yspeed = -100; SmileyApp.xspeed = 0; } else if (event.keyCode === 40) { // right arrow SmileyApp.yspeed = 100; SmileyApp.xspeed = 0; } } document.addEventListener('keydown', arrowkeyCB, true); JSFiddle : http://jsfiddle.net/gj4Q7/

    Read the article

  • Mass Ball-to-Ball Collision Handling (as in, lots of balls)

    - by BlueThen
    Update: Found out that I was using the radius as the diameter, which was why the mtd was overcompensating. Hi, StackOverflow. I've written a Processing program awhile back simulating ball physics. Basically, I have a large number of balls (1000), with gravity turned on. Detection works great, but my issue is that they start acting weird when they're bouncing against other balls in all directions. I'm pretty confident this involves the handling. For the most part, I'm using Jay Conrod's code. One part that's different is if (distance > 1.0) return; which I've changed to if (distance < 1.0) return; because the collision wasn't even being performed with the first bit of code, I'm guessing that's a typo. The balls overlap when I use his code, which isn't what I was looking for. My attempt to fix it was to move the balls to the edge of each other: float angle = atan2(y - collider.y, x - collider.x); float distance = dist(x,y, balls[ID2].x,balls[ID2].y); x = collider.x + radius * cos(angle); y = collider.y + radius * sin(angle); This isn't correct, I'm pretty sure of that. I tried the correction algorithm in the previous ball-to-ball topic: // get the mtd Vector2d delta = (position.subtract(ball.position)); float d = delta.getLength(); // minimum translation distance to push balls apart after intersecting Vector2d mtd = delta.multiply(((getRadius() + ball.getRadius())-d)/d); // resolve intersection -- // inverse mass quantities float im1 = 1 / getMass(); float im2 = 1 / ball.getMass(); // push-pull them apart based off their mass position = position.add(mtd.multiply(im1 / (im1 + im2))); ball.position = ball.position.subtract(mtd.multiply(im2 / (im1 + im2))); except my version doesn't use vectors, and every ball's weight is 1. The resulting code I get is this: PVector delta = new PVector(collider.x - x, collider.y - y); float d = delta.mag(); PVector mtd = new PVector(delta.x * ((radius + collider.radius - d) / d), delta.y * ((radius + collider.radius - d) / d)); // push-pull apart based on mass x -= mtd.x * 0.5; y -= mtd.y * 0.5; collider.x += mtd.x * 0.5; collider.y += mtd.y * 0.5; This code seems to over-correct collisions. Which doesn't make sense to me because in no other way do I modify the x and y values of each ball, other than this. Some other part of my code could be wrong, but I don't know. Here's the snippet of the entire ball-to-ball collision handling I'm using: if (alreadyCollided.contains(new Integer(ID2))) // if the ball has already collided with this, then we don't need to reperform the collision algorithm return; Ball collider = (Ball) objects.get(ID2); PVector collision = new PVector(x - collider.x, y - collider.y); float distance = collision.mag(); if (distance == 0) { collision = new PVector(1,0); distance = 1; } if (distance < 1) return; PVector velocity = new PVector(vx,vy); PVector velocity2 = new PVector(collider.vx, collider.vy); collision.div(distance); // normalize the distance float aci = velocity.dot(collision); float bci = velocity2.dot(collision); float acf = bci; float bcf = aci; vx += (acf - aci) * collision.x; vy += (acf - aci) * collision.y; collider.vx += (bcf - bci) * collision.x; collider.vy += (bcf - bci) * collision.y; alreadyCollided.add(new Integer(ID2)); collider.alreadyCollided.add(new Integer(ID)); PVector delta = new PVector(collider.x - x, collider.y - y); float d = delta.mag(); PVector mtd = new PVector(delta.x * ((radius + collider.radius - d) / d), delta.y * ((radius + collider.radius - d) / d)); // push-pull apart based on mass x -= mtd.x * 0.2; y -= mtd.y * 0.2; collider.x += mtd.x * 0.2; collider.y += mtd.y * 0.2; Thanks. (Apologies for lack of sources, stackoverflow thinks I'm a spammer)

    Read the article

  • 2D colliding n-body simulation (fast Collision Detection for large number of balls)

    - by osgx
    Hello I want to write a program for simulating a motion of high number (N = 1000 - 10^5 and more) of bodies (circles) on 2D plane. All bodies have equal size and the only force between them is elastic collision. I want to get something like but in larger scale, with more balls and more dense filling of the plane (not a gas model as here, but smth like boiling water model). So I want a fast method of detection that ball number i does have any other ball on its path within 2*radius+V*delta_t distance. I don't want to do a full search of collision with N balls for each of i ball. (This search will be N^2.) PS Sorry for loop-animated GIF. Just press Esc to stop it. (Will not work in Chrome).

    Read the article

  • how to avoid clutch billiard balls?

    - by Nait87
    I'm working on the simple behaviour of billiard balls in a collision with each other. All works normal, but there was a problem when facing a few easy balls is the effect of coupling balls and they're cool with each other. Tell me how to prevent this. bool MGBilliard::CollisingBall(CCPoint curr_point, CCPoint next_point) { float dx = next_point.x - (curr_point.x + dvdt.x); float dy = next_point.y - (curr_point.y - dvdt.y); float d = dx*dx+dy*dy; return d <= BALL_RADIUS * BALL_RADIUS; } double MGBilliard::angleCollisionBalls(Ball* current, Ball* next) { double na; double dx = fabs(next->location.x - current->location.x); double dy = fabs(next->location.y - current->location.y); na = atan(fabs(dy/dx)); if(atan(fabs(current->location.y/current->location.x)) < atan(fabs(next->location.y/next->location.x))) na = current->angle - na; else if(atan(fabs(current->location.y/current->location.x)) > atan(fabs(next->location.y/next->location.x))) na = current->angle + na; return na; } for(unsigned int i = 0;i<BALL_COUNT;++i) { if(vBalls[i]->speed > 0){ vBalls[i]->speed += vBalls[i]->acceleration; float dsdt = vBalls[i]->speed*dt; dvdt.x = dsdt*cos(vBalls[i]->angle); dvdt.y = dsdt*sin(vBalls[i]->angle); vBalls[i]->location.x += dvdt.x; vBalls[i]->location.y += dvdt.y; for(unsigned int j = 1; j < BALL_COUNT; ++j) { if(i == j) continue; if(CollisingBall(vBalls[i]->spriteBall->getPosition(),vBalls[j]->spriteBall->getPosition())) { vBalls[j]->speed = 600; double angle; angle = angleCollisionBalls(vBalls[i],vBalls[j]); vBalls[i]->angle = (float)-angle; vBalls[j]->angle = (float)angle; } } } }

    Read the article

  • 2d ball collision code problem XNA, over accelerated balls and stick together sometimes. help please? [closed]

    - by Sivan
    public static void Collision(Ball ball1, Ball ball2) { Vector3 x = new Vector3((ball1.BallPosition.X - ball2.BallPosition.X), (ball1.BallPosition.Y - ball2.BallPosition.Y), 0); x.Normalize(); Vector3 v1 = new Vector3(ball1.Speed, 0); float x1 = Vector3.Dot(x, v1); Vector3 v1x = x * x1; Vector3 v1y = v1 - v1x; x = -x; Vector3 v2 = new Vector3(ball2.Speed, 0); float x2 = Vector3.Dot(x, v2); Vector3 v2x = x * x2; Vector3 v2y = v2 - v2x; float m1 = 12, m2 = 4; float combinedMass = m1 + m2; Vector3 newVelA = (v1x * ((m1 - m2) / combinedMass)) + (v2x * ((2f * m2) / combinedMass)) + v1y; Vector3 newVelB = (v1x * ((2f * m1) / combinedMass)) + (v2x * ((m2 - m1) / combinedMass)) + v2y; ball1.Speed = new Vector2(newVelA.X, newVelA.Y); ball2.Speed = new Vector2(newVelB.X,newVelB.Y ); }

    Read the article

  • Beginner question: ArrayList can't seem to get it right! Pls help

    - by elementz
    I have been staring at this code all day now, but just can't get it right. ATM I am just pushing codeblocks around without being able to concentrate anymore, with the due time being within almost an hour... So you guys are my last resort here. I am supposed to create a few random balls on a canvas, those balls being stored within an ArrayList (I hope an ArrayList is suitable here: the alternative options to choose from were HashSet and HashMap). Now, whatever I do, I get the differently colored balls at the top of my canvas, but they just get stuck there and refuse to move at all. Apart from that I now get a ConcurrentModificationException, when running the code: java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372) at java.util.AbstractList$Itr.next(AbstractList.java:343) at BallDemo.bounce(BallDemo.java:109) Reading up on that exception, I found out that one can make sure ArrayList is accessed in a threadsafe manner by somehow synchronizing access. But since I have remember fellow students doing without synchronizing, my guess is, that it would actually be the wrong path to go. Maybe you guys could help me get this to work, I at least need those stupid balls to move ;-) /** * Simulate random bouncing balls */ public void bounce(int count) { int ground = 400; // position of the ground line System.out.println(count); myCanvas.setVisible(true); // draw the ground myCanvas.drawLine(50, ground, 550, ground); // Create an ArrayList of type BouncingBalls ArrayList<BouncingBall>balls = new ArrayList<BouncingBall>(); for (int i = 0; i < count; i++){ Random numGen = new Random(); // Creating a random color. Color col = new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256)); // creating a random x-coordinate for the balls int ballXpos = numGen.nextInt(550); BouncingBall bBall = new BouncingBall(ballXpos, 80, 20, col, ground, myCanvas); // adding balls to the ArrayList balls.add(bBall); bBall.draw(); boolean finished = false; } for (BouncingBall bBall : balls){ bBall.move(); } } This would be the original unmodified method we got from our teacher, which only creates two balls: /** * Simulate two bouncing balls */ public void bounce() { int ground = 400; // position of the ground line myCanvas.setVisible(true); myCanvas.drawLine(50, ground, 550, ground); // draw the ground // crate and show the balls BouncingBall ball = new BouncingBall(50, 50, 16, Color.blue, ground, myCanvas); ball.draw(); BouncingBall ball2 = new BouncingBall(70, 80, 20, Color.red, ground, myCanvas); ball2.draw(); // make them bounce boolean finished = false; while(!finished) { myCanvas.wait(50); // small delay ball.move(); ball2.move(); // stop once ball has travelled a certain distance on x axis if(ball.getXPosition() >= 550 && ball2.getXPosition() >= 550) { finished = true; } } ball.erase(); ball2.erase(); } }

    Read the article

  • What is the best testing pattern for checking that parameters are being used properly?

    - by Joseph
    I'm using Rhino Mocks to try to verify that when I call a certain method, that the method in turn will properly group items and then call another method. Something like this: //Arrange var bucketsOfFun = new BucketGame(); var balls = new List<IBall> { new Ball { Color = Color.Red }, new Ball { Color = Color.Blue }, new Ball { Color = Color.Yellow }, new Ball { Color = Color.Orange }, new Ball { Color = Color.Orange } }; //Act bucketsOfFun.HaveFunWithBucketsAndBalls(balls); //Assert ??? Here is where the trouble begins for me. My method is doing something like this: public void HaveFunWithBucketsAndBalls(IList<IBall> balls) { //group all the balls together according to color var blueBalls = GetBlueBalls(balls); var redBalls = GetRedBalls(balls); // you get the idea HaveFunWithABucketOfBalls(blueBalls); HaveFunWithABucketOfBalls(redBalls); // etc etc with all the different colors } public void HaveFunWithABucketOfBalls(IList<IBall> colorSpecificBalls) { //doing some stuff here that i don't care about //for the test i'm writing right now } What I want to assert is that each time I call HaveFunWithABucketOfBalls that I'm calling it with a group of 1 red ball, then 1 blue ball, then 1 yellow ball, then 2 orange balls. If I can assert that behavior then I can verify that the method is doing what I want it to do, which is grouping the balls properly. Any ideas of what the best testing pattern for this would be?

    Read the article

  • Ball to Ball Collision - Detection and Handling

    - by Simucal
    With the help of the Stack Overflow community I've written a pretty basic-but fun physics simulator. You click and drag the mouse to launch a ball. It will bounce around and eventually stop on the "floor". My next big feature I want to add in is ball to ball collision. The ball's movement is broken up into a x and y speed vector. I have gravity (small reduction of the y vector each step), I have friction (small reduction of both vectors each collision with a wall). The balls honestly move around in a surprisingly realistic way. I guess my question has two parts: What is the best method to detect ball to ball collision? Do I just have an O(n^2) loop that iterates over each ball and checks every other ball to see if it's radius overlaps? What equations do I use to handle the ball to ball collisions? Physics 101 How does it effect the two balls speed x/y vectors? What is the resulting direction the two balls head off in? How do I apply this to each ball? Handling the collision detection of the "walls" and the resulting vector changes were easy but I see more complications with ball-ball collisions. With walls I simply had to take the negative of the appropriate x or y vector and off it would go in the correct direction. With balls I don't think it is that way. Some quick clarifications: for simplicity I'm ok with a perfectly elastic collision for now, also all my balls have the same mass right now, but I might change that in the future. In case anyone is interested in playing with the simulator I have made so far, I've uploaded the source here (EDIT: Check the updated source below). Edit: Resources I have found useful 2d Ball physics with vectors: 2-Dimensional Collisions Without Trigonometry.pdf 2d Ball collision detection example: Adding Collision Detection Success! I have the ball collision detection and response working great! Relevant code: Collision Detection: for (int i = 0; i < ballCount; i++) { for (int j = i + 1; j < ballCount; j++) { if (balls[i].colliding(balls[j])) { balls[i].resolveCollision(balls[j]); } } } This will check for collisions between every ball but skip redundant checks (if you have to check if ball 1 collides with ball 2 then you don't need to check if ball 2 collides with ball 1. Also, it skips checking for collisions with itself). Then, in my ball class I have my colliding() and resolveCollision() methods: public boolean colliding(Ball ball) { float xd = position.getX() - ball.position.getX(); float yd = position.getY() - ball.position.getY(); float sumRadius = getRadius() + ball.getRadius(); float sqrRadius = sumRadius * sumRadius; float distSqr = (xd * xd) + (yd * yd); if (distSqr <= sqrRadius) { return true; } return false; } public void resolveCollision(Ball ball) { // get the mtd Vector2d delta = (position.subtract(ball.position)); float d = delta.getLength(); // minimum translation distance to push balls apart after intersecting Vector2d mtd = delta.multiply(((getRadius() + ball.getRadius())-d)/d); // resolve intersection -- // inverse mass quantities float im1 = 1 / getMass(); float im2 = 1 / ball.getMass(); // push-pull them apart based off their mass position = position.add(mtd.multiply(im1 / (im1 + im2))); ball.position = ball.position.subtract(mtd.multiply(im2 / (im1 + im2))); // impact speed Vector2d v = (this.velocity.subtract(ball.velocity)); float vn = v.dot(mtd.normalize()); // sphere intersecting but moving away from each other already if (vn > 0.0f) return; // collision impulse float i = (-(1.0f + Constants.restitution) * vn) / (im1 + im2); Vector2d impulse = mtd.multiply(i); // change in momentum this.velocity = this.velocity.add(impulse.multiply(im1)); ball.velocity = ball.velocity.subtract(impulse.multiply(im2)); } Source Code: Complete source for ball to ball collider. Binary: Compiled binary in case you just want to try bouncing some balls around. If anyone has some suggestions for how to improve this basic physics simulator let me know! One thing I have yet to add is angular momentum so the balls will roll more realistically. Any other suggestions? Leave a comment!

    Read the article

  • Do 3d assets cost a lot more than 2d?

    - by Balls
    I'm planning to create a game on my own and will most likely hire an artist in the future. I just want to know if making a game in 2d will a lot cheaper than making it on 3d? Here's my plan: If it will be a 2d game.. I'll probably make a platform game. More like a Braid level of graphics. If it will be a 3d game.. Closest of graphics I'll ask for will be far cry 1 or if possible oblivion. So any thoughts? I'm funding all of it on my own. It will be my first game but will use maybe an engine around if it will be a 3d game. If 2d, I have my own engine lying around here. Thank you, Balls

    Read the article

  • Given a string of red and blue balls, find min number of swaps to club the colors together

    - by efficiencyIsBliss
    We are given a string of the form: RBBR, where R - red and B - blue. We need to find the minimum number of swaps required in order to club the colors together. In the above case that answer would be 1 to get RRBB or BBRR. I feel like an algorithm to sort a partially sorted array would be useful here since a simple sort would give us the number of swaps, but we want the minimum number of swaps. Any ideas? This is allegedly a Microsoft interview question according to this.

    Read the article

  • Building View Matrix in Direct3D11

    - by Balls
    Am I doing it right? I converted this. m_ViewMatrix = XMMatrixLookAtLH(XMLoadFloat3(&m_Position), lookAtVector, upVector); to this one. XMVECTOR vz = XMVector3Normalize( lookAtVector - XMLoadFloat3(&m_Position) ); XMVECTOR vx = XMVector3Normalize( XMVector3Cross( upVector, vz ) ); XMVECTOR vy = XMVector3Cross( vz, vx ); m_ViewMatrix.r[0] = vx; m_ViewMatrix.r[1] = vy; m_ViewMatrix.r[2] = vz; m_ViewMatrix.r[3] = XMLoadFloat3(&m_Position); m_ViewMatrix.r[0].m128_f32[3] = 0.0f; m_ViewMatrix.r[1].m128_f32[3] = 0.0f; m_ViewMatrix.r[2].m128_f32[3] = 0.0f; m_ViewMatrix.r[3].m128_f32[3] = 1.0f; m_ViewMatrix = XMMatrixInverse( &XMMatrixDeterminant(m_ViewMatrix), m_ViewMatrix ); Everything looks fine when I run it. Another question is, I saw on this site(http://webglfactory.blogspot.com/2011/06/how-to-create-view-matrix.html) that he subtracted lookat from position in his vector vz. I tried it but gave me wrong view matrix. Can anyone check my code. I'm studying linear algebra right now. Sucks my course doesn't have one. Thank you, Balls

    Read the article

  • Box 2D Collision Question

    - by Farooq Arshed
    I am very new to Box 2D Physics world. I wanted to know how to collide 2 bodies when one is Dynamic and other is Kinematic. The whole Scenario is explained below: I have 3 balls in total. I want to balls to remain in their places and the third ball to be able to move. When the third ball hits the other two balls then they should move according to the speed and direction from which they were hit. My gravity of the world is 0 because I only want z-axis gravity. I would also like some one to point me towards some good tutorials regarding Box 2D basics which is language independent. I hope I have explained my scenario well. Thanks for the help in advance.

    Read the article

  • Deleting a game object causing an access violation

    - by Balls
    I tried doing this but it cause an access violation. void GameObjectFactory::Update() { for( std::list<GameObject*>::iterator it=gameObjectList.begin() ..... (*it)->Update(); } void Bomb::Update() { if( time == 2.0f ) { gameObjectFactory->Remove( this ); } } void GameObjectFactory::Remove( ... ) { gameObjectList.remove( ... ); } My thoughts would be to mark the object to be dead then let the factory handle it the on next frame for deletion. Is it the best and fastest way? What do you think?

    Read the article

  • Deleting a game object

    - by Balls
    I tried doing this but it cause an access violation. void GameObjectFactory::Update() { for( std::list<GameObject*>::iterator it=gameObjectList.begin() ..... (*it)->Update(); } void Bomb::Update() { if( time == 2.0f ) { gameObjectFactory->Remove( this ); } } void GameObjectFactory::Remove( ... ) { gameObjectList.remove( ... ); } My thoughts would be to mark the object to be dead then let the factory handle it the on next frame for deletion. Is it the best and fastest way? What do you think?

    Read the article

  • How to handle JSON response using SBJSON iPhone?

    - by Jay Mehta
    I am receiving the below response from my web service? Can any one has idea how to handle it using SBJSON? { "match_details" : { "score" : 86-1 "over" : 1.1 "runrate" : 73.71 "team_name" : England "short_name" : ENG "extra_run" : 50 } "players" : { "key_0" : { "is_out" : 2 "runs" : 4 "balls" : 2 "four" : 1 "six" : 0 "batsman_name" : Ajmal Shahzad * "wicket_info" : not out } "key_1" : { "is_out" : 1 "runs" : 12 "balls" : 6 "four" : 2 "six" : 0 "batsman_name" : Andrew Strauss "wicket_info" : c. Kevin b.Kevin } "key_2" : { "is_out" : 2 "runs" : 20 "balls" : 7 "four" : 4 "six" : 0 "batsman_name" : Chris Tremlett * "wicket_info" : not out } } "fow" : { "0" : 40-1 } } I have done something like this:

    Read the article

  • algorithim for simple colision detection in Java

    - by Bob Twinkles
    I'm not very experienced with Java, just started a couple weeks ago, but I have a simple applet that has two user controlled balls, drawn through java.awt and I need a way to detect a collision with between them. I have an algorithm for detecting collision with the walls: while (true){ if (xPositon > (300 - radius)){ xSpeed = -xSpeed; } else if (xPositon < radius){ xSpeed = -xSpeed; } else if (yPositon > (300 - radius)) { ySpeed = -ySpeed; } else if (yPositon < radius){ ySpeed = -ySpeed; } xPositon += xSpeed; yPositon += ySpeed; and for the second ball if (xPositon2 > (300 - radius)){ xSpeed2 = -xSpeed2; } else if (xPositon2 < radius){ xSpeed2 = -xSpeed2; } else if (yPositon2 > (300 - radius)) { ySpeed2 = -ySpeed2; } else if (yPositon2 < radius){ ySpeed2 = -ySpeed2; } xPositon2 += xSpeed2; yPositon2 += ySpeed2; the applet is 300 pixels by 300 pixels radius stores the radius of the circles xPositon and xPositon2 store the x cordanents for the two balls yPositon and yPositon store the y cordanents for the two balls xSpeed and xSpeed2 store the x velocities for the two balls ySpeed and ySpeed2 store the y velocities for the two balls I've only taken algebra 1 so please no advanced math or physics.

    Read the article

  • error of integer overflow

    - by user308565
    This the part of my OpenGL code, I am getting an error for : struct Ball { float x; float y; float rot; float dir; bool rmv; Ball* next; }; Ball* curBall; void addBall() { if (balls==NULL) { balls=new Ball; balls->next=NULL; curBall=balls; } else { curBall->next=new Ball; curBall=curBall->next; curBall->next=NULL; } curBall->x=((float)rand()/(float)(RAND_MAX+1))*(ww-1) +1; curBall->y=((float)rand()/(float)(RAND_MAX+1))*(wh-1) +1; curBall->dir=((float)rand()/(float)(RAND_MAX+1))*(2*PI-1) +1; curBall->rot=((float)rand()/(float)(RAND_MAX+1))*(359) +1; curBall->rmv=false; } error : In function ‘void addBall()’: file.cpp:120: warning: integer overflow in expression file.cpp:121: warning: integer overflow in expression file.cpp:122: warning: integer overflow in expression file.cpp:123: warning: integer overflow in expression

    Read the article

  • How would I make a mouse controlled physics object in Box2D / AS3?

    - by Marty Wallace
    I recently created this tennis game using my own basic physics: http://martywallace.com/sandbox/tennis/ Basically a tennis racquet sticks to your mouse and you can hit the tennis balls upward. The physics aren't that great, and I want to make a more interesting version of this game with milestones and levels in Flash. I am planning to use Box2D because I have moderate experience with it. I'm not sure how to go about creating the racquet - as far as I understand Box2D, the racquet needs a velocity to influence the velocities of the balls when you hit them (so that you can hit them harder or softer upward to keep them up). With that said, I'm assuming I can't just have a kinematic body that will have its position set to the mouse, because it won't affect the velocities of the balls as expected. I've also thought about setting the velocity to the difference between the racquet position and the mouse each frame, but I am concerned that won't provide accurate positioning and am also thinking that the velocity could end up really large if you move the mouse quickly. What is the correct way to have a physics object locked to the mouse but also to have its displacement in the last frame (from where it was to the mouse) affect the balls?

    Read the article

  • frequency of objects in an array using Ruby

    - by eastafri
    If i had a list of balls each of which has a color property. how can i cleanly get the list of balls with the most frequent color. [m1,m2,m3,m4] say, m1.color = blue m2.color = blue m3.color = red m4.color = blue [m1,m2,m4] is the list of balls with the most frequent color My Approach is to do: [m1,m2,m3,m4].group_by{|ball| ball.color}.each do |samecolor| my_items = samecolor.count end where count is defined as class Array def count k =Hash.new(0) self.each{|x|k[x]+=1} k end end my_items will be a hash of frequencies foreach same color group. My implementation could be buggy and i feel there must be a better and more smarter way. any ideas please?

    Read the article

  • Watching the oil slick

    - by fatherjack
    Having dominated the news for the last month or more BP's problems with one of their oil exploration endeavours is a problem that will affect the whole planet. Now I dont know the whole story, either how it all happened or what is being done to restore some sort of control (I have heard about shredded tyres and golf balls being pumped into the hole but am not sure if that was a satirical program mocking the situation or an actual event . golf balls . seriously!? ). I started wondering what the...(read more)

    Read the article

1 2 3 4 5 6  | Next Page >