# Search Results

• ### 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)

• ### GUI device for throwing a ball

##### - by Fredrik Johansson
The hero has a ball, which shall be thrown with accuracy in a court on iPhone/iPad. The player is seen from above, in a 2D view. In game play, the player reach is between 1/15 and 1/6 of the height of the iPhone screen. The player will run, and try to outmaneuver his opponent, and then throw the ball at a specific location, which is guarded by the opponent (which is also shown on the screen). The player is controlled by a joystick, and that works ok, but how shall I control the stick? Maybe someone can propose a third control method? I've tried the following two approaches: Joystick: Hero has a reach of 1 meter, and this reach is marked with a semi-opaque circle around the player. The ball can be moved by a joystick. When the joystick is moved south, the ball is moved south within the reach circle. There is a direct coupling with the joystick and the position of the ball. I.e. when the joystick is moved max south, the ball is max south within the player reach. At each touch update the speed is calculated, and the Box2d ball position and ball speed are updated. NB, the ball will never be moved outside the reach as long as the player push the joystick. The ball is thrown by swiping the joystick to make the ball move, and then releasing the joystick. At release, the ball will get a smoothed speed of the joystick. Joystick Problem: The throwing accuracy gets bad, because the joystick can not be that big, and a small movement results in quite a large movement of the ball. If the user does not release before the end of the joystick maximum end point, the ball will stop, and when the user releases the joystick the speed of the ball will be zero. Bad... Touch pad A force is applied to the ball by a sweep on a touchpad. The ball is released when the sweep is ended, or when the ball is moved outside the player reach. As there is no one to one mapping between the swipe and the ball position, the precision can be improved. A large swipe can result in a small ball movement. Touch Pad Problem A touchpad is less intuitive. Users do not seem to know what to do with the touch pad. Some tap the touchpad, and then the ball just falls to the ground. As there is no one-to-one mapping, the ball can be moved outside the reach, and then it will just fall to the ground. It's a bit hard to control the ball, especially if the player also moves.

• ### 2D Ball Collisions with Corners

##### - by Aaron
I'm trying to write a 2D simulation of a ball that bounces off of fixed vertical and horizontal walls. Simulating collisions with the faces of the walls was pretty simple--just negate the X-velocity for a vertical wall or the Y-velocity for a horizontal wall. The problem is that the ball can also collide with the corners of the walls, where a horizontal wall meets with a vertical wall. I have already figured out how to detect when a collision with a corner is occurring. My question is how the ball should react to this collision--that is, how its X and Y velocities will change as a result. Here's a list of what I already know or know how to find: *The X and Y coordinates of the ball's center during the frame when a collision is detected *The X and Y components of the ball's velocity *The X and Y coordinates of the corner *The angle between the ball's center and the corner *The angle in which the ball is traveling just before the collision *The amount that the ball is overlapping the corner when the collision is detected I'm guessing that it's best to pretend that the corner is an infinitely small circle, so I can treat a collision between the ball and that circle as if the ball were colliding with a wall that runs tangent to the circles at the point of collision. It seems to me that all I need to do is rotate the coordinate system to line up with this imaginary wall, reverse the X component of the ball's velocity under this system, and rotate the coordinates back to the original system. The problem is that I have no idea how to program this. By the way, this is an ideal simulation. I'm not taking anything like friction or the ball's rotation into account. I'm using Objective-C, but I'd really just like a general algorithm or some advice. Many thanks if anyone can help!

• ### 1136: Incorrect number of arguments. Expected 0.? AS3 Flash Cs4

##### - by charmaine
Basically i am working through a book called..Foundation Actionscript 3.0 Animation, making things move. i am now on Chapter 9 - collision detection. On two lines of my code i get the 1135 error, letting me know that i have an incorrect number of arguments. Can anybody help me out on why this may be? package { import flash.display.Sprite; import flash.events.Event; public class Bubbles extends Sprite { private var balls:Array; private var numBalls:Number = 10; private var centerBall:Ball; private var bounce:Number = -1; private var spring:Number = 0.2; public function Bubbles() { init(); } private function init():void { balls = new Array(); centerBall = new Ball(100, 0xcccccc); addChild(centerBall); centerBall.x = stage.stageWidth / 2; centerBall.y = stage.stageHeight / 2; for(var i:uint = 0; i < numBalls; i++) { var ball:Ball = new Ball(Math.random() * 40 + 5, Math.random() * 0xffffff); ball.x = Math.random() * stage.stageWidth; ball.y = Math.random() * stage.stageHeight; ball.vx = Math.random() * 6 - 3; ball.vy = Math.random() * 6 - 3; addChild(ball); balls.push(ball); } addEventListener(Event.ENTER_FRAME, onEnterFrame); } private function onEnterFrame(event:Event):void { for(var i:uint = 0; i < numBalls; i++) { var ball:Ball = balls[i]; move(ball); var dx:Number = ball.x - centerBall.x; var dy:Number = ball.y - centerBall.y; var dist:Number = Math.sqrt(dx * dx + dy * dy); var minDist:Number = ball.radius + centerBall.radius; if(dist < minDist) { var angle:Number = Math.atan2(dy, dx); var tx:Number = centerBall.x + Math.cos(angle) * minDist; var ty:Number = centerBall.y + Math.sin(angle) * minDist; ball.vx += (tx - ball.x) * spring; ball.vy += (ty - ball.y) * spring; } } } ***private function move(ball:Ball):void*** { ball.x += ball.vx; ball.y += ball.vy; if(ball.x + ball.radius > stage.stageWidth) { ball.x = stage.stageWidth - ball.radius; ball.vx *= bounce; } else if(ball.x - ball.radius < 0) { ball.x = ball.radius; ball.vx *= bounce; } ***if(ball.y + ball.radius > stage.stageHeight)*** { ball.y = stage.stageHeight - ball.radius; ball.vy *= bounce; } else if(ball.y - ball.radius < 0) { ball.y = ball.radius; ball.vy *= bounce; } } } } The bold parts are the lines im having trouble with! please help..thanks in advance!!

• ### Are there any ball tracking algorithms/patterns around in game programming

##### - by user214626
Hello, I am a newbie to game programming,I would need the suggestions and help of the wonderful people around here. I have set of players, and a ball, the players can kick the ball around the ground (not yet a football game, neither a foosball game too ).Are there any algorithms/ patterns for addressing the problems with tracking the ball and taking decisions, Is that too much to ask.What I was looking at is something like a collision detection algorithm for the common problem of 2 objects interacting with one another.

• ### XNA C# Rectangle Intersect Ball on a Square

##### - by user2436057
I made a Game like Peggle Deluxe using C# and XNA for lerning. I have 2 rectangles a ball and a square field. The ball gets shoot out with a cannon and if the Ball hits the Square the Square disapears and the Ball flys away.But the Ball doesent spring of realistically, it sometimes flys away in a different direction or gets stuck on the edge. Thads my Code at the moment: public void Update(Ball b, Deadline dl) { ArrayList listToDelete = new ArrayList(); foreach (Field aField in allFields) { if (aField.square.Intersects(b.ballhere)) { listToDelete.Add(aField); Punkte = Punkte + 100; float distanceX = Math.Abs(b.ballhere.X - aField.square.X); float distanceY = Math.Abs(b.ballhere.Y - aField.square.Y); if (distanceX < distanceY) { b.myMovement.X = -b.myMovement.X; } else { b.myMovement.Y = -b.myMovement.Y; } } } It changes the X or Y axis depending on how the ball hits the Square but not everytimes. What could cause the problem? Thanks for your answer. Greetings from Switzerland.

• ### Detecting collision between ball (circle) and brick(rectangle)?

##### - by James Harrison
Ok so this is for a small uni project. My lecturer provided me with a framework for a simple brickbreaker game. I am currently trying to overcome to problem of detecting a collision between the two game objects. One object is always the ball and the other objects can either be the bricks or the bat. public Collision hitBy( GameObject obj ) { //obj is the bat or the bricks //the current object is the ball // if ball hits top of object if(topX + width >= obj.topX && topX <= obj.topX + obj.width && topY + height >= obj.topY - 2 && topY + height <= obj.topY){ return Collision.HITY; } //if ball hits left hand side else if(topY + height >= obj.topY && topY <= obj.topY + obj.height && topX + width >= obj.topX -2 && topX + width <= obj.topX){ return Collision.HITX; } else return Collision.NO_HIT; } So far I have a method that is used to detect this collision. The the current obj is a ball and the obj passed into the method is the the bricks. At the moment I have only added statement to check for left and top collisions but do not want to continue as I have a few problems. The ball reacts perfectly if it hits the top of the bricks or bat but when it hits the ball often does not change directing. It seems that it is happening toward the top of the left hand edge but I cannot figure out why. I would like to know if there is another way of approaching this or if people know where I'm going wrong. Lastly the collision.HITX calls another method later on the changes the x direction likewise with y.

• ### Java Spotlight Episode 99: Daniel Blaukopf on JavaFX for Embedded Systems

##### - by Roger Brinkley
Interview with  Daniel Blaukopf on JavaFX for Embedded Systems Right-click or Control-click to download this MP3 file. You can also subscribe to the Java Spotlight Podcast Feed to get the latest podcast automatically. If you use iTunes you can open iTunes and subscribe with this link:  Java Spotlight Podcast in iTunes. Show Notes News Top 5 Reasons to go to JavaOne 5. Chance to see the future of Java Technical Keynotes and sessions The pavillion The new [email protected] conference 4. The meetings outside the scope of the conference Top 10 Reasons to Attend the Oracle Appreciation Event GlassFish Community Event at JavaOne 2012 Sundays User Group Forum 3. It’s like drinking from firehose Less keynotes more sessions - 20% more 60% of the talks are external to HOLs Tutorials OracleJava University classes on Sunday - Top Five Reasons You Should Attend Java University at JavaOne 2. Students are free 1. It’s not what you see it’s who you will meet Events Sep 10-15, IMTS 2012 Conference,  Chicago Sep 12,  The Coming M2M Revolution: Critical Issues for End-to-End Software and Systems Development,  Webinar Sep 30-Oct 4, JavaONE, San Francisco Oct 3-4, Java Embedded @ JavaONE, San Francisco Oct 15-17, JAX London Oct 30-Nov 1, Arm TechCon, Santa Clara Oct 22-23, Freescale Technology Forum - Japan, Tokyo Oct 31, JFall, Netherlands Nov 2-3, JMagreb, Morocco Nov 13-17, Devoxx, Belgium Feature InterviewDaniel Blaukopf is the Embedded Java Client Architect at Oracle, working on JavaFX. Daniel's focus in his 14 years in the Java organization has been mobile and embedded devices, including working with device manufacturers to port and tune all levels of the Java stack to their hardware and software environments. Daniel's particular interests are: graphics, performance optimization and functional programming.

• ### How display path ball will bounce?

##### - by boolean
I'm trying to figure out a way to show the path a ball will travel, so that the player can line up a shot before they fire the ball. I can't think of a way to calculate this path in advance and show it to the player, especially if it involves collision detection. At first I thought I would run the game at a super high speed for one update, plot the path with some dotted lines where the ball bounced, and then in the next frame hide the 'tracer' ball. This seems to have two issues - Calculating collision detection without actually updating the frames and collision detection getting less reliable at high speeds. If they were straight lines I think I could figure this out in a while loop, but trying to take into account the speed of the ball, the curve of the path, the reflecting from other objects..it all seems a bit much. I'm not looking for any code and this isn't a platform specific question, more just help trying to figure out conceptually how this would work. Can this be done? Are there techniques to achieve this?

• ### Collisions between moving ball and polygons

##### - by miguelSantirso
I know this is a very typical problem and that there area a lot of similar questions, but I have been looking for a while and I have not found anything that fits what I want. I am developing a 2D game in which I need to perform collisions between a ball and simple polygons. The polygons are defined as an array of vertices. I have implemented the collisions with the bounding boxes of the polygons (that was easy) and I need to refine that collision in the cases where the ball collides with the bounding box. The ball can move quite fast and the polygons are not too big so I need to perform continuous collisions. I am looking for a method that allows me to detect if the ball collides with a polygon and, at the same time, calculate the new direction for the ball after bouncing in the polygon. (I am using XNA, in case that helps)

• ### Bouncing ball slowing down over time

##### - by user46610
I use the unreal engine 4 to bounce a ball off of walls in a 2D space, but over time the ball gets slower and slower. Movement happens in the tick function of the ball FVector location = GetActorLocation(); location.X += this->Velocity.X * DeltaSeconds; location.Y += this->Velocity.Y * DeltaSeconds; SetActorLocation(location, true); When a wall gets hit I get a Hit Event with the normal of the collision. This is how I calculate the new velocity of the ball: FVector2D V = this->Velocity; FVector2D N = FVector2D(HitNormal.X, HitNormal.Y); FVector2D newVelocity = -2 * (V.X * N.X + V.Y * N.Y) * N + V; this->Velocity = newVelocity; Over time, the more the ball bounced around, the velocity gets smaller and smaller. How do I prevent speed loss when bouncing off walls like that? It's supposed to be a perfect bounce without friction or anything.

• ### accessing object variables in javascript

##### - by user1452370
So, I just started javascript and everything was working fine till i came to objects. This peace of code is supposed to create a bouncing ball in a html canvas with javascript but it doesn't work. var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); //clear function clear() { ctx.clearRect(0, 0, canvas.width, canvas.height); } here is my ball object //ball var ball = { x: canvas.width / 2, getX: function() { return x; }, setX: function(a) { x = a; }, y: canvas.height / 2, getY: function() { return y; }, setY: function(a) { y = a; }, mx: 2, getMx: function() { return mx; }, my: 4, getMy: function() { return my; }, r: 10, getR: function() { return r; } }; code to draw my ball function drawBall() { ctx.beginPath(); ctx.arc(ball.getX, ball.getY, ball.getR, 0, Math.PI * 2, true); ctx.fillStyle = "#83F52C"; ctx.fill(); } function circle(x, y, r) { ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2, true); ctx.fillStyle = "#83F52C"; ctx.fill(); } //draws ball and updates x,y cords function draw() { clear(); drawBall(); if (ball.getX() + ball.getMx() >= canvas.width || ball.getX()+ ball.getMx() <= 0) { ball.setMx(-ball.getMx()); } if (ball.getY() + ball.getMy() >= canvas.height|| ball.getY()+ ball.getMy() <= 0) { ball.setMy(-ball.getMy()); } ball.setX(ball.getX() + ball.getMx()); ball.setY(ball.getY() + ball.getMy()); } set interval function init() { return setInterval(draw, 10); } init();

• ### 2D Gaming - How to reflect a ball off the bat?

##### - by sid
Hi there I am pretty new to XNA & game dev and am stuck at ball reflection. My ball is reflecting once it hits the bat, but only in one angle, no matter which angle the bat is at. Here's the code: if (BallRect.Intersects(BatRect)) { Vector2 NormBallVelocity = Ball.velocity; NormBallVelocity.Normalize(); NormBallVelocity = Vector2.Reflect(Ball.velocity, NormBallVelocity); Ball.velocity = NormBallVelocity; } The ball is retracting its way back. How do I make it look like the ball is reflecting off the bat? I have seen other posts but they are on 3D front I am too new to translate it to 2D terms... Thanks Sid

• ### Keep Your Eye on the Ball

##### - by [email protected]
With the FIFA World Cup 2010 in South Africa almost a week underway, the soccer fans all around the World are talking about at least 2 things. That typical vuvuzela sound and the new Jabulani ball, saying it moves unpredictably, is difficult to handle and somehow the altitude of the World Cup stadiums also seem to be a contributing factor.(Picture taken from http://www.flickr.com/photos/warrenski/4143923059/ under a Creative Commons license)Although the FIFA states that it hasn't received any official complaints, the end users don't seem to be very happy with this new ball. This brings me to a comparison with IT management and testing. When you're in a situation where you're introducing a new product, in IT terms, introducing a new application, you would like to test all possible scenarios that your end users could be using and experiencing. However, that's a very time and resource intensive process to do for every application change or update.  It's like getting ready for the big game but you have no game plan.That's why a new approach has been developed. One that's based on the 80/20 rule. Testing 80% of the application will cost about 20% of the efforts. The remaining 20% of your application will not be tested before deployment, but monitored with a real user monitoring solution immediately after deployment. These tools track all user experiences, including error messages and the performance and availability metrics from an end user perspective. Should any anomaly occur, you would be able to repair it quickly so you and your end users can get back into the game.These real user sessions can be easily converted into testing scripts, so the 80% of the application testing can be complimented with the remaining 20%.Oracle Enterprise Manager 11g group of products offers both the real user monitoring solution with Oracle Real User Experience Insight, as well as the required testing solution with Oracle Application Testing Suite. Visit our Oracle Enterprise Manager 11g resource center and find out how it's Business-Driven IT Management approach will help you keep your eye on your business ball.Happy World Cup.

• ### Le C en 20 heures d'Eric Berthomier et Daniel Schang

Nous avons le plaisir de vous présenter le livre "Le C en 20 heures" d'Eric Berthomier et Daniel Schang à consulter ou à télécharger gratuitement. Citation: L'ouvrage que vous tenez dans les mains ou que vous consultez sur votre écran a pour objectif de vous faire découvrir, par la pratique, la programmation en langage C. Il a été testé par de nombreux étudiants qui n'avaient aucune connaissance préalable de ce langage. En 20 à 30 heures de ...

• ### Bouncing ball isssue

##### - by user
I am currently working on the 2D Bouncing ball physics that bounces the ball up and down. The physics behaviour works fine but at the end the velocity keep +3 then 0 non-stop even the ball has stopped bouncing. How should I modify the code to fix this issue? ballPos = D3DXVECTOR2( 50, 100 ); velocity = 0; accelaration = 3.0f; isBallUp = false; void GameClass::Update() { velocity += accelaration; ballPos.y += velocity; if ( ballPos.y >= 590 ) isBallUp = true; else isBallUp = false; if ( isBallUp ) { ballPos.y = 590; velocity *= -1; } // Graphics Rendering m_Graphics.BeginFrame(); ComposeFrame(); m_Graphics.EndFrame(); }

• ### How to give a ball a following texture trailing effect

##### - by Evan Kohilas
How do I draw copies of the leading texture so that there is a line of the leading ball following behind it? (that don't collide) So far I have tried to create the effect by placing another graphic 2 pixels off the graphic, but I don't see the second ball being drawn. spriteBatch.Draw(ballTexture, ballPos, null, Color.White, 0.0f, new Vector2(Ballpos.X +2, ballPos.Y +2), ballSize, SpriteEffects.None, 0); Thanks.

• ### Critical Patch Update For Oracle Fusion Middleware – CPU October 2012 by Daniel Mortimer

##### - by JuergenKress
The latest Critical Patch Update (CPU) has been released for Oracle products. Start your reading here. Patch Set Update and Critical Patch Update October 2012 Availability Document [ID 1477727.1] Oracle Fusion Middleware 11g Release 2 11.1.2.0 Oracle Fusion Middleware 11g Release 1 11.1.1.4 (Portal,Forms,Reports and Discoverer) 11.1.1.5 11.1.1.6 Oracle Application Server 10g Release 3 10.1.3.5 Read the full article here. WebLogic Partner Community For regular information become a member in the WebLogic Partner Community please visit: http://www.oracle.com/partners/goto/wls-emea ( OPN account required). If you need support with your account please contact the Oracle Partner Business Center. BlogTwitterLinkedInMixForumWiki Technorati Tags: patch ofm,critical patch,WebLogic Community,Oracle,OPN,Jürgen Kress

• ### 2D Platformer Collision Handling

##### - by defender-zone
Hello, everyone! I am trying to create a 2D platformer (Mario-type) game and I am some having some issues with handling collisions properly. I am writing this game in C++, using SDL for input, image loading, font loading, etcetera. I am also using OpenGL via the FreeGLUT library in conjunction with SDL to display graphics. My method of collision detection is AABB (Axis-Aligned Bounding Box), which is really all I need to start with. What I need is an easy way to both detect which side the collision occurred on and handle the collisions properly. So, basically, if the player collides with the top of the platform, reposition him to the top; if there is a collision to the sides, reposition the player back to the side of the object; if there is a collision to the bottom, reposition the player under the platform. I have tried many different ways of doing this, such as trying to find the penetration depth and repositioning the player backwards by the penetration depth. Sadly, nothing I've tried seems to work correctly. Player movement ends up being very glitchy and repositions the player when I don't want it to. Part of the reason is probably because I feel like this is something so simple but I'm over-thinking it. If anyone thinks they can help, please take a look at the code below and help me try to improve on this if you can. I would like to refrain from using a library to handle this (as I want to learn on my own) or the something like the SAT (Separating Axis Theorem) if at all possible. Thank you in advance for your help! void world1Level1CollisionDetection() { for(int i; i < blocks; i++) { if (de2dCheckCollision(ball,block[i],0.0f,0.0f)==true) { int up = 0; int left = 0; int right = 0; int down = 0; if(ball.coords[0] < block[i].coords[0] && block[i].coords[0] < ball.coords[2] && ball.coords[2] < block[i].coords[2]) { left = 1; } if(block[i].coords[0] < ball.coords[0] && ball.coords[0] < block[i].coords[2] && block[i].coords[2] < ball.coords[2]) { right = 1; } if(ball.coords[1] < block[i].coords[1] && block[i].coords[1] < ball.coords[3] && ball.coords[3] < block[i].coords[3]) { up = 1; } if(block[i].coords[1] < ball.coords[1] && ball.coords[1] < block[i].coords[3] && block[i].coords[3] < ball.coords[3]) { down = 1; } cout << left << ", " << right << ", " << up << ", " << down << ", " << endl; if (left == 1) { ball.coords[0] = block[i].coords[0] - 16.0f; ball.coords[2] = block[i].coords[0] - 0.0f; } if (right == 1) { ball.coords[0] = block[i].coords[2] + 0.0f; ball.coords[2] = block[i].coords[2] + 16.0f; } if (down == 1) { ball.coords[1] = block[i].coords[3] + 0.0f; ball.coords[3] = block[i].coords[3] + 16.0f; } if (up == 1) { ball.yspeed = 0.0f; ball.gravity = 0.0f; ball.coords[1] = block[i].coords[1] - 16.0f; ball.coords[3] = block[i].coords[1] - 0.0f; } } if (de2dCheckCollision(ball,block[i],0.0f,0.0f)==false) { ball.gravity = -0.5f; } } } To explain what some of this code means: The blocks variable is basically an integer that is storing the amount of blocks, or platforms. I am checking all of the blocks using a for loop, and the number that the loop is currently on is represented by integer i. The coordinate system might seem a little weird, so that's worth explaining. coords[0] represents the x position (left) of the object (where it starts on the x axis). coords[1] represents the y position (top) of the object (where it starts on the y axis). coords[2] represents the width of the object plus coords[0] (right). coords[3] represents the height of the object plus coords[1] (bottom). de2dCheckCollision performs an AABB collision detection. Up is negative y and down is positive y, as it is in most games. Hopefully I have provided enough information for someone to help me successfully. If there is something I left out that might be crucial, let me know and I'll provide the necessary information. Finally, for anyone who can help, providing code would be very helpful and much appreciated. Thank you again for your help!

• ### 3D Ball Physics Theory: collision response on ground and against walls?

##### - by David
I'm really struggling to get a strong grasp on how I should be handling collision response in a game engine I'm building around a 3D ball physics concept. Think Monkey Ball as an example of the type of gameplay. I am currently using sphere-to-sphere broad phase, then AABB to OBB testing (the final test I am using right now is one that checks if one of the 8 OBB points crosses the planes of the object it is testing against). This seems to work pretty well, and I am getting back: Plane that object is colliding against (with a point on the plane, the plane's normal, and the exact point of intersection. I've tried what feels like dozens of different high-level strategies for handling these collisions, without any real success. I think my biggest problem is understanding how to handle collisions against walls in the x-y axes (left/right, front/back), which I want to have elasticity, and the ground (z-axis) where I want an elastic reaction if the ball drops down, but then for it to eventually normalize and be kept "on the ground" (not go into the ground, but also not continue bouncing). Without kluging something together, I'm positive there is a good way to handle this, my theories just aren't getting me all the way there. For physics modeling and movement, I am trying to use a Euler based setup with each object maintaining a position (and destination position prior to collision detection), a velocity (which is added onto the position to determine the destination position), and an acceleration (which I use to store any player input being put on the ball, as well as gravity in the z coord). Starting from when I detect a collision, what is a good way to approach the response to get the expected behavior in all cases? Thanks in advance to anyone taking the time to assist... I am grateful for any pointers, and happy to post any additional info or code if it is useful. UPDATE Based on Steve H's and eBusiness' responses below, I have adapted my collision response to what makes a lot more sense now. It was close to right before, but I didn't have all the right pieces together at the right time! I have one problem left to solve, and that is what is causing the floor collision to hit every frame. Here's the collision response code I have now for the ball, then I'll describe the last bit I'm still struggling to understand. // if we are moving in the direction of the plane (against the normal)... if (m_velocity.dot(intersection.plane.normal) <= 0.0f) { float dampeningForce = 1.8f; // eventually create this value based on mass and acceleration // Calculate the projection velocity PVRTVec3 actingVelocity = m_velocity.project(intersection.plane.normal); m_velocity -= actingVelocity * dampeningForce; } // Clamp z-velocity to zero if we are within a certain threshold // -- NOTE: this was an experimental idea I had to solve the "jitter" bug I'll describe below float diff = 0.2f - abs(m_velocity.z); if (diff > 0.0f && diff <= 0.2f) { m_velocity.z = 0.0f; } // Take this object to its new destination position based on... // -- our pre-collision position + vector to the collision point + our new velocity after collision * time // -- remaining after the collision to finish the movement m_destPosition = m_position + intersection.diff + (m_velocity * intersection.tRemaining * GAMESTATE->dt); The above snippet is run after a collision is detected on the ball (collider) with a collidee (floor in this case). With a dampening force of 1.8f, the ball's reflected "upward" velocity will eventually be overcome by gravity, so the ball will essentially be stuck on the floor. THIS is the problem I have now... the collision code is running every frame (since the ball's z-velocity is constantly pushing it a collision with the floor below it). The ball is not technically stuck, I can move it around still, but the movement is really goofy because the velocity and position keep getting affected adversely by the above snippet. I was experimenting with an idea to clamp the z-velocity to zero if it was "close to zero", but this didn't do what I think... probably because the very next frame the ball gets a new gravity acceleration applied to its velocity regardless (which I think is good, right?). Collisions with walls are as they used to be and work very well. It's just this last bit of "stickiness" to deal with. The camera is constantly jittering up and down by extremely small fractions too when the ball is "at rest". I'll keep playing with it... I like puzzles like this, especially when I think I'm close. Any final ideas on what I could be doing wrong here? UPDATE 2 Good news - I discovered I should be subtracting the intersection.diff from the m_position (position prior to collision). The intersection.diff is my calculation of the difference in the vector of position to destPosition from the intersection point to the position. In this case, adding it was causing my ball to always go "up" just a little bit, causing the jitter. By subtracting it, and moving that clamper for the velocity.z when close to zero to being above the dot product (and changing the test from <= 0 to < 0), I now have the following: // Clamp z-velocity to zero if we are within a certain threshold float diff = 0.2f - abs(m_velocity.z); if (diff > 0.0f && diff <= 0.2f) { m_velocity.z = 0.0f; } // if we are moving in the direction of the plane (against the normal)... float dotprod = m_velocity.dot(intersection.plane.normal); if (dotprod < 0.0f) { float dampeningForce = 1.8f; // eventually create this value based on mass and acceleration? // Calculate the projection velocity PVRTVec3 actingVelocity = m_velocity.project(intersection.plane.normal); m_velocity -= actingVelocity * dampeningForce; } // Take this object to its new destination position based on... // -- our pre-collision position + vector to the collision point + our new velocity after collision * time // -- remaining after the collision to finish the movement m_destPosition = m_position - intersection.diff + (m_velocity * intersection.tRemaining * GAMESTATE->dt); UpdateWorldMatrix(m_destWorldMatrix, m_destOBB, m_destPosition, false); This is MUCH better. No jitter, and the ball now "rests" at the floor, while still bouncing off the floor and walls. The ONLY thing left is that the ball is now virtually "stuck". He can move but at a much slower rate, likely because the else of my dot product test is only letting the ball move at a rate multiplied against the tRemaining... I think this is a better solution than I had previously, but still somehow not the right idea. BTW, I'm trying to journal my progress through this problem for anyone else with a similar situation - hopefully it will serve as some help, as many similar posts have for me over the years.