Search Results

Search found 1429 results on 58 pages for 'simon elliston ball'.

Page 1/58 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • 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

  • Ball bouncing at a certain angle and efficiency computations

    - by X Y
    I would like to make a pong game with a small twist (for now). Every time the ball bounces off one of the paddles i want it to be under a certain angle (between a min and a max). I simply can't wrap my head around how to actually do it (i have some thoughts and such but i simply cannot implement them properly - i feel i'm overcomplicating things). Here's an image with a small explanation . One other problem would be that the conditions for bouncing have to be different for every edge. For example, in the picture, on the two small horizontal edges i do not want a perfectly vertical bounce when in the middle of the edge but rather a constant angle (pi/4 maybe) in either direction depending on the collision point (before the middle of the edge, or after). All of my collisions are done with the Separating Axes Theorem (and seem to work fine). I'm looking for something efficient because i want to add a lot of things later on (maybe polygons with many edges and such). So i need to keep to a minimum the amount of checking done every frame. The collision algorithm begins testing whenever the bounding boxes of the paddle and the ball intersect. Is there something better to test for possible collisions every frame? (more efficient in the long run,with many more objects etc, not necessarily easy to code). I'm going to post the code for my game: Paddle Class public class Paddle : Microsoft.Xna.Framework.DrawableGameComponent { #region Private Members private SpriteBatch spriteBatch; private ContentManager contentManager; private bool keybEnabled; private bool isLeftPaddle; private Texture2D paddleSprite; private Vector2 paddlePosition; private float paddleSpeedY; private Vector2 paddleScale = new Vector2(1f, 1f); private const float DEFAULT_Y_SPEED = 150; private Vector2[] Normals2Edges; private Vector2[] Vertices = new Vector2[4]; private List<Vector2> lst = new List<Vector2>(); private Vector2 Edge; #endregion #region Properties public float Speed { get {return paddleSpeedY; } set { paddleSpeedY = value; } } public Vector2[] Normal2EdgesVector { get { NormalsToEdges(this.isLeftPaddle); return Normals2Edges; } } public Vector2[] VertexVector { get { return Vertices; } } public Vector2 Scale { get { return paddleScale; } set { paddleScale = value; NormalsToEdges(this.isLeftPaddle); } } public float X { get { return paddlePosition.X; } set { paddlePosition.X = value; } } public float Y { get { return paddlePosition.Y; } set { paddlePosition.Y = value; } } public float Width { get { return (Scale.X == 1f ? (float)paddleSprite.Width : paddleSprite.Width * Scale.X); } } public float Height { get { return ( Scale.Y==1f ? (float)paddleSprite.Height : paddleSprite.Height*Scale.Y ); } } public Texture2D GetSprite { get { return paddleSprite; } } public Rectangle Boundary { get { return new Rectangle((int)paddlePosition.X, (int)paddlePosition.Y, (int)this.Width, (int)this.Height); } } public bool KeyboardEnabled { get { return keybEnabled; } } #endregion private void NormalsToEdges(bool isLeftPaddle) { Normals2Edges = null; Edge = Vector2.Zero; lst.Clear(); for (int i = 0; i < Vertices.Length; i++) { Edge = Vertices[i + 1 == Vertices.Length ? 0 : i + 1] - Vertices[i]; if (Edge != Vector2.Zero) { Edge.Normalize(); //outer normal to edge !! (origin in top-left) lst.Add(new Vector2(Edge.Y, -Edge.X)); } } Normals2Edges = lst.ToArray(); } public float[] ProjectPaddle(Vector2 axis) { if (Vertices.Length == 0 || axis == Vector2.Zero) return (new float[2] { 0, 0 }); float min, max; min = Vector2.Dot(axis, Vertices[0]); max = min; for (int i = 1; i < Vertices.Length; i++) { float p = Vector2.Dot(axis, Vertices[i]); if (p < min) min = p; else if (p > max) max = p; } return (new float[2] { min, max }); } public Paddle(Game game, bool isLeftPaddle, bool enableKeyboard = true) : base(game) { contentManager = new ContentManager(game.Services); keybEnabled = enableKeyboard; this.isLeftPaddle = isLeftPaddle; } public void setPosition(Vector2 newPos) { X = newPos.X; Y = newPos.Y; } public override void Initialize() { base.Initialize(); this.Speed = DEFAULT_Y_SPEED; X = 0; Y = 0; NormalsToEdges(this.isLeftPaddle); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); paddleSprite = contentManager.Load<Texture2D>(@"Content\pongBar"); } public override void Update(GameTime gameTime) { //vertices array Vertices[0] = this.paddlePosition; Vertices[1] = this.paddlePosition + new Vector2(this.Width, 0); Vertices[2] = this.paddlePosition + new Vector2(this.Width, this.Height); Vertices[3] = this.paddlePosition + new Vector2(0, this.Height); // Move paddle, but don't allow movement off the screen if (KeyboardEnabled) { float moveDistance = Speed * (float)gameTime.ElapsedGameTime.TotalSeconds; KeyboardState newKeyState = Keyboard.GetState(); if (newKeyState.IsKeyDown(Keys.Down) && Y + paddleSprite.Height + moveDistance <= Game.GraphicsDevice.Viewport.Height) { Y += moveDistance; } else if (newKeyState.IsKeyDown(Keys.Up) && Y - moveDistance >= 0) { Y -= moveDistance; } } else { if (this.Y + this.Height > this.GraphicsDevice.Viewport.Height) { this.Y = this.Game.GraphicsDevice.Viewport.Height - this.Height - 1; } } base.Update(gameTime); } public override void Draw(GameTime gameTime) { spriteBatch.Begin(SpriteSortMode.Texture,null); spriteBatch.Draw(paddleSprite, paddlePosition, null, Color.White, 0f, Vector2.Zero, Scale, SpriteEffects.None, 0); spriteBatch.End(); base.Draw(gameTime); } } Ball Class public class Ball : Microsoft.Xna.Framework.DrawableGameComponent { #region Private Members private SpriteBatch spriteBatch; private ContentManager contentManager; private const float DEFAULT_SPEED = 50; private float speedIncrement = 0; private Vector2 ballScale = new Vector2(1f, 1f); private const float INCREASE_SPEED = 50; private Texture2D ballSprite; //initial texture private Vector2 ballPosition; //position private Vector2 centerOfBall; //center coords private Vector2 ballSpeed = new Vector2(DEFAULT_SPEED, DEFAULT_SPEED); //speed #endregion #region Properties public float DEFAULTSPEED { get { return DEFAULT_SPEED; } } public Vector2 ballCenter { get { return centerOfBall; } } public Vector2 Scale { get { return ballScale; } set { ballScale = value; } } public float SpeedX { get { return ballSpeed.X; } set { ballSpeed.X = value; } } public float SpeedY { get { return ballSpeed.Y; } set { ballSpeed.Y = value; } } public float X { get { return ballPosition.X; } set { ballPosition.X = value; } } public float Y { get { return ballPosition.Y; } set { ballPosition.Y = value; } } public Texture2D GetSprite { get { return ballSprite; } } public float Width { get { return (Scale.X == 1f ? (float)ballSprite.Width : ballSprite.Width * Scale.X); } } public float Height { get { return (Scale.Y == 1f ? (float)ballSprite.Height : ballSprite.Height * Scale.Y); } } public float SpeedIncreaseIncrement { get { return speedIncrement; } set { speedIncrement = value; } } public Rectangle Boundary { get { return new Rectangle((int)ballPosition.X, (int)ballPosition.Y, (int)this.Width, (int)this.Height); } } #endregion public Ball(Game game) : base(game) { contentManager = new ContentManager(game.Services); } public void Reset() { ballSpeed.X = DEFAULT_SPEED; ballSpeed.Y = DEFAULT_SPEED; ballPosition.X = Game.GraphicsDevice.Viewport.Width / 2 - ballSprite.Width / 2; ballPosition.Y = Game.GraphicsDevice.Viewport.Height / 2 - ballSprite.Height / 2; } public void SpeedUp() { if (ballSpeed.Y < 0) ballSpeed.Y -= (INCREASE_SPEED + speedIncrement); else ballSpeed.Y += (INCREASE_SPEED + speedIncrement); if (ballSpeed.X < 0) ballSpeed.X -= (INCREASE_SPEED + speedIncrement); else ballSpeed.X += (INCREASE_SPEED + speedIncrement); } public float[] ProjectBall(Vector2 axis) { if (axis == Vector2.Zero) return (new float[2] { 0, 0 }); float min, max; min = Vector2.Dot(axis, this.ballCenter) - this.Width/2; //center - radius max = min + this.Width; //center + radius return (new float[2] { min, max }); } public void ChangeHorzDirection() { ballSpeed.X *= -1; } public void ChangeVertDirection() { ballSpeed.Y *= -1; } public override void Initialize() { base.Initialize(); ballPosition.X = Game.GraphicsDevice.Viewport.Width / 2 - ballSprite.Width / 2; ballPosition.Y = Game.GraphicsDevice.Viewport.Height / 2 - ballSprite.Height / 2; } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); ballSprite = contentManager.Load<Texture2D>(@"Content\ball"); } public override void Update(GameTime gameTime) { if (this.Y < 1 || this.Y > GraphicsDevice.Viewport.Height - this.Height - 1) this.ChangeVertDirection(); centerOfBall = new Vector2(ballPosition.X + this.Width / 2, ballPosition.Y + this.Height / 2); base.Update(gameTime); } public override void Draw(GameTime gameTime) { spriteBatch.Begin(); spriteBatch.Draw(ballSprite, ballPosition, null, Color.White, 0f, Vector2.Zero, Scale, SpriteEffects.None, 0); spriteBatch.End(); base.Draw(gameTime); } } Main game class public class gameStart : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; public gameStart() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; this.Window.Title = "Pong game"; } protected override void Initialize() { ball = new Ball(this); paddleLeft = new Paddle(this,true,false); paddleRight = new Paddle(this,false,true); Components.Add(ball); Components.Add(paddleLeft); Components.Add(paddleRight); this.Window.AllowUserResizing = false; this.IsMouseVisible = true; this.IsFixedTimeStep = false; this.isColliding = false; base.Initialize(); } #region MyPrivateStuff private Ball ball; private Paddle paddleLeft, paddleRight; private int[] bit = { -1, 1 }; private Random rnd = new Random(); private int updates = 0; enum nrPaddle { None, Left, Right }; private nrPaddle PongBar = nrPaddle.None; private ArrayList Axes = new ArrayList(); private Vector2 MTV; //minimum translation vector private bool isColliding; private float overlap; //smallest distance after projections private Vector2 overlapAxis; //axis of overlap #endregion protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); paddleLeft.setPosition(new Vector2(0, this.GraphicsDevice.Viewport.Height / 2 - paddleLeft.Height / 2)); paddleRight.setPosition(new Vector2(this.GraphicsDevice.Viewport.Width - paddleRight.Width, this.GraphicsDevice.Viewport.Height / 2 - paddleRight.Height / 2)); paddleLeft.Scale = new Vector2(1f, 2f); //scale left paddle } private bool ShapesIntersect(Paddle paddle, Ball ball) { overlap = 1000000f; //large value overlapAxis = Vector2.Zero; MTV = Vector2.Zero; foreach (Vector2 ax in Axes) { float[] pad = paddle.ProjectPaddle(ax); //pad0 = min, pad1 = max float[] circle = ball.ProjectBall(ax); //circle0 = min, circle1 = max if (pad[1] <= circle[0] || circle[1] <= pad[0]) { return false; } if (pad[1] - circle[0] < circle[1] - pad[0]) { if (Math.Abs(overlap) > Math.Abs(-pad[1] + circle[0])) { overlap = -pad[1] + circle[0]; overlapAxis = ax; } } else { if (Math.Abs(overlap) > Math.Abs(circle[1] - pad[0])) { overlap = circle[1] - pad[0]; overlapAxis = ax; } } } if (overlapAxis != Vector2.Zero) { MTV = overlapAxis * overlap; } return true; } protected override void Update(GameTime gameTime) { updates += 1; float ftime = 5 * (float)gameTime.ElapsedGameTime.TotalSeconds; if (updates == 1) { isColliding = false; int Xrnd = bit[Convert.ToInt32(rnd.Next(0, 2))]; int Yrnd = bit[Convert.ToInt32(rnd.Next(0, 2))]; ball.SpeedX = Xrnd * ball.SpeedX; ball.SpeedY = Yrnd * ball.SpeedY; ball.X += ftime * ball.SpeedX; ball.Y += ftime * ball.SpeedY; } else { updates = 100; ball.X += ftime * ball.SpeedX; ball.Y += ftime * ball.SpeedY; } //autorun :) paddleLeft.Y = ball.Y; //collision detection PongBar = nrPaddle.None; if (ball.Boundary.Intersects(paddleLeft.Boundary)) { PongBar = nrPaddle.Left; if (!isColliding) { Axes.Clear(); Axes.AddRange(paddleLeft.Normal2EdgesVector); //axis from nearest vertex to ball's center Axes.Add(FORMULAS.NormAxisFromCircle2ClosestVertex(paddleLeft.VertexVector, ball.ballCenter)); } } else if (ball.Boundary.Intersects(paddleRight.Boundary)) { PongBar = nrPaddle.Right; if (!isColliding) { Axes.Clear(); Axes.AddRange(paddleRight.Normal2EdgesVector); //axis from nearest vertex to ball's center Axes.Add(FORMULAS.NormAxisFromCircle2ClosestVertex(paddleRight.VertexVector, ball.ballCenter)); } } if (PongBar != nrPaddle.None && !isColliding) switch (PongBar) { case nrPaddle.Left: if (ShapesIntersect(paddleLeft, ball)) { isColliding = true; if (MTV != Vector2.Zero) ball.X += MTV.X; ball.Y += MTV.Y; ball.ChangeHorzDirection(); } break; case nrPaddle.Right: if (ShapesIntersect(paddleRight, ball)) { isColliding = true; if (MTV != Vector2.Zero) ball.X += MTV.X; ball.Y += MTV.Y; ball.ChangeHorzDirection(); } break; default: break; } if (!ShapesIntersect(paddleRight, ball) && !ShapesIntersect(paddleLeft, ball)) isColliding = false; ball.X += ftime * ball.SpeedX; ball.Y += ftime * ball.SpeedY; //check ball movement if (ball.X > paddleRight.X + paddleRight.Width + 2) { //IncreaseScore(Left); ball.Reset(); updates = 0; return; } else if (ball.X < paddleLeft.X - 2) { //IncreaseScore(Right); ball.Reset(); updates = 0; return; } base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Aquamarine); spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); spriteBatch.End(); base.Draw(gameTime); } } And one method i've used: public static Vector2 NormAxisFromCircle2ClosestVertex(Vector2[] vertices, Vector2 circle) { Vector2 temp = Vector2.Zero; if (vertices.Length > 0) { float dist = (circle.X - vertices[0].X) * (circle.X - vertices[0].X) + (circle.Y - vertices[0].Y) * (circle.Y - vertices[0].Y); for (int i = 1; i < vertices.Length;i++) { if (dist > (circle.X - vertices[i].X) * (circle.X - vertices[i].X) + (circle.Y - vertices[i].Y) * (circle.Y - vertices[i].Y)) { temp = vertices[i]; //memorize the closest vertex dist = (circle.X - vertices[i].X) * (circle.X - vertices[i].X) + (circle.Y - vertices[i].Y) * (circle.Y - vertices[i].Y); } } temp = circle - temp; temp.Normalize(); } return temp; } Thanks in advance for any tips on the 4 issues. EDIT1: Something isn't working properly. The collision axis doesn't come out right and the interpolation also seems to have no effect. I've changed the code a bit: private bool ShapesIntersect(Paddle paddle, Ball ball) { overlap = 1000000f; //large value overlapAxis = Vector2.Zero; MTV = Vector2.Zero; foreach (Vector2 ax in Axes) { float[] pad = paddle.ProjectPaddle(ax); //pad0 = min, pad1 = max float[] circle = ball.ProjectBall(ax); //circle0 = min, circle1 = max if (pad[1] < circle[0] || circle[1] < pad[0]) { return false; } if (Math.Abs(pad[1] - circle[0]) < Math.Abs(circle[1] - pad[0])) { if (Math.Abs(overlap) > Math.Abs(-pad[1] + circle[0])) { overlap = -pad[1] + circle[0]; overlapAxis = ax * (-1); } //to get the proper axis } else { if (Math.Abs(overlap) > Math.Abs(circle[1] - pad[0])) { overlap = circle[1] - pad[0]; overlapAxis = ax; } } } if (overlapAxis != Vector2.Zero) { MTV = overlapAxis * Math.Abs(overlap); } return true; } And part of the Update method: if (ShapesIntersect(paddleRight, ball)) { isColliding = true; if (MTV != Vector2.Zero) { ball.X += MTV.X; ball.Y += MTV.Y; } //test if (overlapAxis.X == 0) //collision with horizontal edge { } else if (overlapAxis.Y == 0) //collision with vertical edge { float factor = Math.Abs(ball.ballCenter.Y - paddleRight.Y) / paddleRight.Height; if (factor > 1) factor = 1f; if (overlapAxis.X < 0) //left edge? ball.Speed = ball.DEFAULTSPEED * Vector2.Normalize(Vector2.Reflect(ball.Speed, (Vector2.Lerp(new Vector2(-1, -3), new Vector2(-1, 3), factor)))); else //right edge? ball.Speed = ball.DEFAULTSPEED * Vector2.Normalize(Vector2.Reflect(ball.Speed, (Vector2.Lerp(new Vector2(1, -3), new Vector2(1, 3), factor)))); } else //vertex collision??? { ball.Speed = -ball.Speed; } } What seems to happen is that "overlapAxis" doesn't always return the right one. So instead of (-1,0) i get the (1,0) (this happened even before i multiplied with -1 there). Sometimes there isn't even a collision registered even though the ball passes through the paddle... The interpolation also seems to have no effect as the angles barely change (or the overlapAxis is almost never (-1,0) or (1,0) but something like (0.9783473, 0.02743843)... ). What am i missing here? :(

    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

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

    Read the article

  • 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!

    Read the article

  • Intel Dual Band Wireless-AC 7260 keeps dropping wifi

    - by Rick T
    My wifi Intel Dual Band Wireless-AC 7260 keeps dropping wificonnection drops and the network to which I was connected disappears from the list of available networks in network manager. The only way to fix it is to disable wifi and re-enable it How can I fix this. I'm using ubuntu 14.04 64bit. It mostly drops connections on the 5ghz network. My other devices don't drop connections over wifi. see logs and versions rt@simon:~$ uname -a Linux simon 3.13.0-34-generic #60-Ubuntu SMP Wed Aug 13 15:45:27 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux rt@simon:~$ rt@simon:~$ dmesg | grep iwl [ 3.370777] iwlwifi 0000:03:00.0: irq 46 for MSI/MSI-X [ 3.381089] iwlwifi 0000:03:00.0: loaded firmware version 22.24.8.0 op_mode iwlmvm [ 3.414637] iwlwifi 0000:03:00.0: Detected Intel(R) Dual Band Wireless AC 7260, REV=0x144 [ 3.414695] iwlwifi 0000:03:00.0: L1 Disabled; Enabling L0S [ 3.414913] iwlwifi 0000:03:00.0: L1 Disabled; Enabling L0S [ 3.630208] ieee80211 phy0: Selected rate control algorithm 'iwl-mvm-rs' [ 9.304838] iwlwifi 0000:03:00.0: L1 Disabled; Enabling L0S [ 9.305068] iwlwifi 0000:03:00.0: L1 Disabled; Enabling L0S [ 605.483174] iwlwifi 0000:03:00.0: L1 Disabled; Enabling L0S [ 605.483396] iwlwifi 0000:03:00.0: L1 Disabled; Enabling L0S rt@simon:~$ cat /var/log/syslog | grep -e iwl -e 80211 | tail -n25 Aug 14 08:13:02 simon kernel: [ 3.452780] cfg80211: (5735000 KHz - 5835000 KHz @ 40000 KHz), (300 mBi, 2000 mBm) Aug 14 08:13:02 simon kernel: [ 3.630208] ieee80211 phy0: Selected rate control algorithm 'iwl-mvm-rs' Aug 14 08:13:06 simon NetworkManager[1125]: <info> rfkill1: found WiFi radio killswitch (at /sys/devices/pci0000:00/0000:00:1c.2/0000:03:00.0/ieee80211/phy0/rfkill1) (driver iwlwifi) Aug 14 08:13:06 simon NetworkManager[1125]: <info> (wlan0): using nl80211 for WiFi device control Aug 14 08:13:06 simon NetworkManager[1125]: <info> (wlan0): new 802.11 WiFi device (driver: 'iwlwifi' ifindex: 3) Aug 14 08:13:06 simon kernel: [ 9.304838] iwlwifi 0000:03:00.0: L1 Disabled; Enabling L0S Aug 14 08:13:06 simon kernel: [ 9.305068] iwlwifi 0000:03:00.0: L1 Disabled; Enabling L0S Aug 14 08:14:18 simon kernel: [ 81.230162] cfg80211: Calling CRDA to update world regulatory domain Aug 14 08:14:18 simon kernel: [ 81.232330] cfg80211: World regulatory domain updated: Aug 14 08:14:18 simon kernel: [ 81.232332] cfg80211: (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp) Aug 14 08:14:18 simon kernel: [ 81.232333] cfg80211: (2402000 KHz - 2472000 KHz @ 40000 KHz), (300 mBi, 2000 mBm) Aug 14 08:14:18 simon kernel: [ 81.232334] cfg80211: (2457000 KHz - 2482000 KHz @ 40000 KHz), (300 mBi, 2000 mBm) Aug 14 08:14:18 simon kernel: [ 81.232335] cfg80211: (2474000 KHz - 2494000 KHz @ 20000 KHz), (300 mBi, 2000 mBm) Aug 14 08:14:18 simon kernel: [ 81.232336] cfg80211: (5170000 KHz - 5250000 KHz @ 40000 KHz), (300 mBi, 2000 mBm) Aug 14 08:14:18 simon kernel: [ 81.232337] cfg80211: (5735000 KHz - 5835000 KHz @ 40000 KHz), (300 mBi, 2000 mBm) Aug 14 08:23:02 simon kernel: [ 605.483174] iwlwifi 0000:03:00.0: L1 Disabled; Enabling L0S Aug 14 08:23:02 simon kernel: [ 605.483396] iwlwifi 0000:03:00.0: L1 Disabled; Enabling L0S Aug 14 08:23:18 simon kernel: [ 621.223905] cfg80211: Calling CRDA to update world regulatory domain Aug 14 08:23:18 simon kernel: [ 621.228945] cfg80211: World regulatory domain updated: Aug 14 08:23:18 simon kernel: [ 621.228950] cfg80211: (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp) Aug 14 08:23:18 simon kernel: [ 621.228954] cfg80211: (2402000 KHz - 2472000 KHz @ 40000 KHz), (300 mBi, 2000 mBm) Aug 14 08:23:18 simon kernel: [ 621.228956] cfg80211: (2457000 KHz - 2482000 KHz @ 40000 KHz), (300 mBi, 2000 mBm) Aug 14 08:23:18 simon kernel: [ 621.228959] cfg80211: (2474000 KHz - 2494000 KHz @ 20000 KHz), (300 mBi, 2000 mBm) Aug 14 08:23:18 simon kernel: [ 621.228961] cfg80211: (5170000 KHz - 5250000 KHz @ 40000 KHz), (300 mBi, 2000 mBm) Aug 14 08:23:18 simon kernel: [ 621.228963] cfg80211: (5735000 KHz - 5835000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)

    Read the article

  • 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!!

    Read the article

  • 1136: Incorrect number of arguments. Expected 0.? AS3 Flash Cs4 (Round 2)

    - by charmaine
    (I have asked this before but I dont think I was direct enough with my question and therefore it did not get resolved so here goes again!) 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. I have highlighted the two areas in which this occurs with asterisks: 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; } } } } I think this is due to the non-existance of a Ball.as, when reading the tutorial I assumed it meant that I had to create a movie clip of a ball on stage and then export it for actionscript with the class name being Ball, however when flicking back through the book I saw that a Ball.as already existed, stating that I may need to use this again later on in the book, this read: package { import flash.display.Sprite; public class Ball extends Sprite { private var radius:Number; private var color:uint; public var vx:Number=0; public var vy:Number=0; public function Ball(radius:Number=40, color:uint=0xff0000) { this.radius=radius; this.color=color; init(); } public function init():void { graphics.beginFill(color); graphics.drawCircle(0, 0, radius); graphics.endFill(); } } } This managed to stop all the errors appearing however, it did not transmit any of the effects from Bubbles.as it just braught a Red Ball on the center of the stage. How would I alter this code in order to work in favour of Bubbles.as? Please Help! Thanks!

    Read the article

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

    Read the article

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

    Read the article

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

    Read the article

  • Multiple setInterval in a HTML5 Canvas game

    - by kushsolitary
    I'm trying to achieve multiple animations in a game that I am creating using Canvas (it is a simple ping-pong game). This is my first game and I am new to canvas but have created a few experiments before so I have a good knowledge about how canvas work. First, take a look at the game here. The problem is, when the ball hits the paddle, I want a burst of n particles at the point of contact but that doesn't came right. Even if I set the particles number to 1, they just keep coming from the point of contact and then hides automatically after some time. Also, I want to have the burst on every collision but it occurs on first collision only. I am pasting the code here: //Initialize canvas var canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d"), W = window.innerWidth, H = window.innerHeight, particles = [], ball = {}, paddles = [2], mouse = {}, points = 0, fps = 60, particlesCount = 50, flag = 0, particlePos = {}; canvas.addEventListener("mousemove", trackPosition, true); //Set it's height and width to full screen canvas.width = W; canvas.height = H; //Function to paint canvas function paintCanvas() { ctx.globalCompositeOperation = "source-over"; ctx.fillStyle = "black"; ctx.fillRect(0, 0, W, H); } //Create two paddles function createPaddle(pos) { //Height and width this.h = 10; this.w = 100; this.x = W/2 - this.w/2; this.y = (pos == "top") ? 0 : H - this.h; } //Push two paddles into the paddles array paddles.push(new createPaddle("bottom")); paddles.push(new createPaddle("top")); //Setting up the parameters of ball ball = { x: 2, y: 2, r: 5, c: "white", vx: 4, vy: 8, draw: function() { ctx.beginPath(); ctx.fillStyle = this.c; ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false); ctx.fill(); } }; //Function for creating particles function createParticles(x, y) { this.x = x || 0; this.y = y || 0; this.radius = 0.8; this.vx = -1.5 + Math.random()*3; this.vy = -1.5 + Math.random()*3; } //Draw everything on canvas function draw() { paintCanvas(); for(var i = 0; i < paddles.length; i++) { p = paddles[i]; ctx.fillStyle = "white"; ctx.fillRect(p.x, p.y, p.w, p.h); } ball.draw(); update(); } //Mouse Position track function trackPosition(e) { mouse.x = e.pageX; mouse.y = e.pageY; } //function to increase speed after every 5 points function increaseSpd() { if(points % 4 == 0) { ball.vx += (ball.vx < 0) ? -1 : 1; ball.vy += (ball.vy < 0) ? -2 : 2; } } //function to update positions function update() { //Move the paddles on mouse move if(mouse.x && mouse.y) { for(var i = 1; i < paddles.length; i++) { p = paddles[i]; p.x = mouse.x - p.w/2; } } //Move the ball ball.x += ball.vx; ball.y += ball.vy; //Collision with paddles p1 = paddles[1]; p2 = paddles[2]; if(ball.y >= p1.y - p1.h) { if(ball.x >= p1.x && ball.x <= (p1.x - 2) + (p1.w + 2)){ ball.vy = -ball.vy; points++; increaseSpd(); particlePos.x = ball.x, particlePos.y = ball.y; flag = 1; } } else if(ball.y <= p2.y + 2*p2.h) { if(ball.x >= p2.x && ball.x <= (p2.x - 2) + (p2.w + 2)){ ball.vy = -ball.vy; points++; increaseSpd(); particlePos.x = ball.x, particlePos.y = ball.y; flag = 1; } } //Collide with walls if(ball.x >= W || ball.x <= 0) ball.vx = -ball.vx; if(ball.y > H || ball.y < 0) { clearInterval(int); } if(flag == 1) { setInterval(emitParticles(particlePos.x, particlePos.y), 1000/fps); } } function emitParticles(x, y) { for(var k = 0; k < particlesCount; k++) { particles.push(new createParticles(x, y)); } counter = particles.length; for(var j = 0; j < particles.length; j++) { par = particles[j]; ctx.beginPath(); ctx.fillStyle = "white"; ctx.arc(par.x, par.y, par.radius, 0, Math.PI*2, false); ctx.fill(); par.x += par.vx; par.y += par.vy; par.radius -= 0.02; if(par.radius < 0) { counter--; if(counter < 0) particles = []; } } } var int = setInterval(draw, 1000/fps); Now, my function for emitting particles is on line 156, and I have called this function on line 151. The problem here can be because of I am not resetting the flag variable but I tried doing that and got more weird results. You can check that out here. By resetting the flag variable, the problem of infinite particles gets resolved but now they only animate and appear when the ball collides with the paddles. So, I am now out of any solution.

    Read the article

  • 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?

    Read the article

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

    Read the article

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

    Read the article

  • 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();

    Read the article

  • 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

    Read the article

  • OOW 2013 Summary for Fusion Middleware Architects & Administrators by Simon Haslam

    - by JuergenKress
    OOW 2013 Summary for Fusion Middleware Architects & Administrators by Simon Haslam This September during Oracle OpenWorld 2013 the weather in San Francisco, as you see can from the photo, was exceptionally sunny. The dramatic final few days of the Americas Cup sailing competition, being held every day in the bay, coincided with the conference and meant that there was almost a holiday feel to the whole event. Here's my annual round-up of what I think was most interesting at OpenWorld 2013 for Fusion Middleware architects and administrators; I hope you find it useful and if you think I've missed something please add a comment! WebLogic and Cloud Application Foundation (CAF) The big WebLogic release of the year has already happened a few months ago with 12.1.2 so I won't duplicate that here. Will Lyons discussed the WebLogic and Coherence roadmap which essentially is that 12.1.3 will probably be released to coincide with SOA 12c next year and that 12.1.4, the next feature-rich WebLogic release, is more likely to be in 2015. This latter release will probably include full Java EE 7 support, have enhancements for multi-tenancy and further auto-scaling features to support increased density (i.e. more WebLogic usage for the same amount of hardware). There's a new Oracle Virtual Assembly Builder (OVAB) out already and an Oracle Traffic Director (OTD) 12c release round the corner too. Also of relevance to administrators is that Oracle has increased the support lifetime for Fusion Middleware 11g (e.g. WebLogic 10.3.6) so that Premier Support will now run to the end of 2018 and Extended Support until 2021 - this should remove any Oracle-driven pressure to upgrade at least. Java Mission Control Java Mission Control (JMC) is the HotSpot Java 7 version of JRockit 6 Mission Control, a very nice performance monitoring tool from Oracle's BEA acquisition. Flight Recorder is a feature built into the JVM which records diagnostic events into, typically, a circular buffer which can then be used for historical analysis, particularly in the case of a JVM crash or hang. It's been available separately for WebLogic only for perhaps a year now but, more significantly, it now includes JVM events and was bundled in with JDK7 Update 40 a few weeks ago. I attended a couple of interesting Java One sessions on JMC/Flight Recorder and have to say it's looking really good - it has all the previous JRMC features except for memory leak detector, plus some enhancements around operative sets and ECID filtering I think. Marcus also showed how you could add your own events into flight recorder by building your own event class - they are then available for graphing alongside all the other events in JMC. This uses a currently an unsupported/undocumented API, but it's also the same one that WebLogic uses for WLDF events so I imagine it is stable. I'm not sure quite whether this would be useful to custom applications, as opposed to infrastructure services or ISV packaged applications, but it was a very nice demonstration. I've been testing JMC / FR enabling on several environments recently and my confidence is growing - it feels robust and I think could very soon be part of my standard builds. 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. Blog Twitter LinkedIn Mix Forum Wiki Technorati Tags: OOW,Simon Haslam,Oracle OpenWorld,WebLogic,WebLogic Community,Oracle,OPN,Jürgen Kress

    Read the article

  • Talking JavaOne with Rock Star Simon Ritter

    - by Janice J. Heiss
    Oracle’s Java Technology Evangelist Simon Ritter is well known at JavaOne for his quirky and fun-loving sessions, which, this year include: CON4644 -- “JavaFX Extreme GUI Makeover” (with Angela Caicedo on how to improve UIs in JavaFX) CON5352 -- “Building JavaFX Interfaces for the Real World” (Kinect gesture tracking and mind reading) CON5348 -- “Do You Like Coffee with Your Dessert?” (Some cool demos of Java of the Raspberry Pi) CON6375 -- “Custom JavaFX Charts: (How to extend JavaFX Chart controls with some interesting things) I recently asked Ritter about the significance of the Raspberry Pi, the topic of one of his sessions that consists of a credit card-sized single-board computer developed in the UK with the intention of stimulating the teaching of basic computer science in schools. “I don't think there's one definitive thing that makes the RP significant,” observed Ritter, “but a combination of things that really makes it stand out. First, it's the cost: $35 for what is effectively a completely usable computer. OK, so you have to add a power supply, SD card for storage and maybe a screen, keyboard and mouse, but this is still way cheaper than a typical PC. The choice of an ARM processor is also significant, as it avoids problems like cooling (no heat sink or fan) and can use a USB power brick.  Combine these two things with the immense groundswell of community support and it provides a fantastic platform for teaching young and old alike about computing, which is the real goal of the project.”He informed me that he’ll be at the Raspberry Pi meetup on Saturday (not part of JavaOne). Check out the details here.JavaFX InterfacesWhen I asked about how JavaFX can interface with the real world, he said that there are many ways. “JavaFX provides you with a simple set of programming interfaces that can create complex, cool and compelling user interfaces,” explained Ritter. “Because it's just Java code you can combine JavaFX with any other Java library to provide data to display and control the interface. What I've done for my session is look at some of the possible ways of doing this using some of the amazing hardware that's available today at very low cost. The Kinect sensor has added a new dimension to gaming in terms of interaction; there's a Java API to access this so you can easily collect skeleton tracking data from it. Some clever people have also written libraries that can track gestures like swipes, circles, pushes, and so on. We use these to control parts of the UI. I've also experimented with a Neurosky EEG sensor that can in some ways ‘read your mind’ (well, at least measure some of the brain functions like attention and meditation).  I've written a Java library for this that I include as a way of controlling the UI. We're not quite at the stage of just thinking a command though!” Here Comes Java EmbeddedAnd what, from Ritter’s perspective, is the most exciting thing happening in the world of Java today? “I think it's seeing just how Java continues to become more and more pervasive,” he said. “One of the areas that is growing rapidly is embedded systems.  We've talked about the ‘Internet of things’ for many years; now it's finally becoming a reality. With the ability of more and more devices to include processing, storage and networking we need an easy way to write code for them that's reliable, has high performance, and is secure. Java fits all these requirements. With Java Embedded being a conference within a conference, I'm very excited about the possibilities of Java in this space.”Check out Ritter’s sessions or say hi if you run into him. Originally published on blogs.oracle.com/javaone.

    Read the article

  • Talking JavaOne with Rock Star Simon Ritter

    - by Janice J. Heiss
    Oracle’s Java Technology Evangelist Simon Ritter is well known at JavaOne for his quirky and fun-loving sessions, which, this year include: CON4644 -- “JavaFX Extreme GUI Makeover” (with Angela Caicedo on how to improve UIs in JavaFX) CON5352 -- “Building JavaFX Interfaces for the Real World” (Kinect gesture tracking and mind reading) CON5348 -- “Do You Like Coffee with Your Dessert?” (Some cool demos of Java of the Raspberry Pi) CON6375 -- “Custom JavaFX Charts: (How to extend JavaFX Chart controls with some interesting things) I recently asked Ritter about the significance of the Raspberry Pi, the topic of one of his sessions that consists of a credit card-sized single-board computer developed in the UK with the intention of stimulating the teaching of basic computer science in schools. “I don't think there's one definitive thing that makes the RP significant,” observed Ritter, “but a combination of things that really makes it stand out. First, it's the cost: $35 for what is effectively a completely usable computer. OK, so you have to add a power supply, SD card for storage and maybe a screen, keyboard and mouse, but this is still way cheaper than a typical PC. The choice of an ARM processor is also significant, as it avoids problems like cooling (no heat sink or fan) and can use a USB power brick.  Combine these two things with the immense groundswell of community support and it provides a fantastic platform for teaching young and old alike about computing, which is the real goal of the project.”He informed me that he’ll be at the Raspberry Pi meetup on Saturday (not part of JavaOne). Check out the details here.JavaFX InterfacesWhen I asked about how JavaFX can interface with the real world, he said that there are many ways. “JavaFX provides you with a simple set of programming interfaces that can create complex, cool and compelling user interfaces,” explained Ritter. “Because it's just Java code you can combine JavaFX with any other Java library to provide data to display and control the interface. What I've done for my session is look at some of the possible ways of doing this using some of the amazing hardware that's available today at very low cost. The Kinect sensor has added a new dimension to gaming in terms of interaction; there's a Java API to access this so you can easily collect skeleton tracking data from it. Some clever people have also written libraries that can track gestures like swipes, circles, pushes, and so on. We use these to control parts of the UI. I've also experimented with a Neurosky EEG sensor that can in some ways ‘read your mind’ (well, at least measure some of the brain functions like attention and meditation).  I've written a Java library for this that I include as a way of controlling the UI. We're not quite at the stage of just thinking a command though!” Here Comes Java EmbeddedAnd what, from Ritter’s perspective, is the most exciting thing happening in the world of Java today? “I think it's seeing just how Java continues to become more and more pervasive,” he said. “One of the areas that is growing rapidly is embedded systems.  We've talked about the ‘Internet of things’ for many years; now it's finally becoming a reality. With the ability of more and more devices to include processing, storage and networking we need an easy way to write code for them that's reliable, has high performance, and is secure. Java fits all these requirements. With Java Embedded being a conference within a conference, I'm very excited about the possibilities of Java in this space.”Check out Ritter’s sessions or say hi if you run into him.

    Read the article

  • 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(); }

    Read the article

  • JavaOne Afterglow by Simon Ritter

    - by JuergenKress
    Last week was the eighteenth JavaOne conference and I thought it would be a good idea to write up my thoughts about how things went. Firstly thanks to Yoshio Terada for the photos, I didn't bother bringing a camera with me so it's good to have some pictures to add to the words. Things kicked off full-throttle on Sunday.  We had the Java Champions and JUG leaders breakfast, which was a great way to meet up with a lot of familiar faces and start talking all things Java.  At midday the show really started with the Strategy and Technical Keynotes.  This was always going to be tougher job than some years because there was no big shiny ball to reveal to the audience.  With the Java EE 7 spec being finalised a few months ago and Java SE 8, Java ME 8 and JDK8 not due until the start of next year there was not going to be any big announcement.  I thought both keynotes worked really well each focusing on the things most important to Java developers: Strategy One of the things that is becoming more and more prominent in many companies marketing is the Internet of Things (IoT).  We've moved from the conventional desktop/laptop environment to much more mobile connected computing with smart phones and tablets.  The next wave of the internet is not just billions of people connected, but 10s or 100s of billions of devices connected to the network, all generating data and providing much more precise control of almost any process you can imagine.  This ties into the ideas of Big Data and Cloud Computing, but implementation is certainly not without its challenges.  As Peter Utzschneider explained it's about three Vs: Volume, Velocity and Value.  All these devices will create huge volumes of data at very high speed; to avoid being overloaded these devices will need some sort of processing capabilities that can filter the useful data from the redundant.  The raw data then needs to be turned into useful information that has value.  To make this happen will require applications on devices, at gateways and on the back-end servers, all very tightly integrated.  This is where Java plays a pivotal role, write once, run everywhere becomes essential, having nine million developers fluent in the language makes it the defacto lingua franca of IoT.  There will be lots more information on how this will become a reality, so watch this space. Technical How do we make the IoT a reality, technically?  Using the game of chess Mark Reinhold, with the help of people like John Ceccarelli, Jasper Potts and Richard Bair, showed what you could do.  Using Java EE on the back end, Java SE and JavaFX on the desktop and Java ME Embedded and JavaFX on devices they showed a complete end-to-end demo. This was really impressive, using 3D features from JavaFX 8 (that's included with JDK8) to make a 3D animated Duke chess board.  Jasper also unveiled the "DukePad" a home made tablet using a Raspberry Pi, touch screen and accelerometer. Although the Raspberry Pi doesn't have earth shattering CPU performance (about the same level as a mid 1990s Pentium), it does have really quite good GPU performance so the GUI works really well.  The plans are all open sourced and available here.  One small, but very significant announcement was that Java SE will now be included with the NOOB and Raspbian Linux distros provided by the Raspberry Pi foundation (these can be found here).  No more hassle having to download and install the JDK after you've flashed your SD card OS image.  The finale was the Raspberry Pi powered chess playing robot.  Really very, very cool.  I talked to Jasper about this and he told me each of the chess pieces had been 3D printed and then he had to use acetone to give them a glossy finish (not sure what his wife thought of him spending hours in the kitchen in a gas mask!)  The way the robot arm worked was very impressive as it did not have any positioning data (like a potentiometer connected to each motor), but relied purely on carefully calibrated timings to get the arm to the right place.  Having done things like this myself in the past I know how easy it is to find a small error gets magnified into very big mistakes. Here's some pictures from the keynote: The "Dukepad" architecture Nice clear perspex case so you can see the innards. The very nice 3D chess set.  Maya's obviously a great tool. 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. Blog Twitter LinkedIn Mix Forum Wiki Technorati Tags: Simon Ritter,Java One,OOW,Oracle OpenWorld,WebLogic,WebLogic Community,Oracle,OPN,Jürgen Kress

    Read the article

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

    Read the article

  • Simon Sabin has a great discount for the SQL Server Masterclass

    - by Testas
    Check out Simons blog post to get a discount of £100 for this event http://sqlblogcasts.com/blogs/simons/archive/2010/05/14/paul-and-kimberly-are-coming-the-uk.aspx   Remember as well  Pencil the 17th June in your diary, send an email [email protected] with the title of Masterclass in the subject line. On Friday 25th May we will draw out a name and the winner will have free entrance to a must see seminar on SQL Server from two of the industry’s leading experts. Thanks Chris

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >