Search Results

Search found 12216 results on 489 pages for 'game physics'.

Page 9/489 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Game network physics collision

    - by Jonas Byström
    How to simulating two client-controlled vehicles colliding (sensibly) in a typical client/server setup for a network game? I did read this eminent blog post on how to do distributed network physics in general (without traditional client prediction), but this question is specifically on how to handle collisions of owned objects. Example Say client A is 20 ms ahead of server, client B 300 ms ahead of server (counting both latency and maximum jitter). This means that when the two vehicles collide, both clients will see the other as 320 ms behind - in the opposite direction of the velocity of the other vehicle. Head-to-head on a Swedish highway means a difference of 16 meters/17.5 yards! What not to try It is virtually impossible to extrapolate the positions, since I also have very complex vehicles with joints and bodies all over, which in turn have linear and angular positions, velocities and accelerations, not to mention states from user input.

    Read the article

  • HTML5 or Javascript game engine to develop a browser game

    - by Jack Duluoz
    I would like to start developing a MMO browser game, like Travian or Ogame, probably involving also a bit of more sophisticated graphical features such as players interacting in real time with a 2d map or something like that. My main doubt is what kind of development tools I should use: I've a good experience with PHP and MySQL for the server side and Javascript (and jQuery) regarding the client side. Coding everything from scratch would be of course really painful so I was wondering if I should use a javascript game engine or not. Are there (possibly free) game engine you would recommend? Are they good enough to develop a big game? Also, I saw a lot of HTML5 games popping up lately but I'm now sure if using HTML5 is a good idea or not. Would you recommend it? What are the pro and cons about using HTML5? If you'd recommend it, do you have any good links regarding game development with HTML5? (PS: I know that HTML5 and a Javascript engine are not mutually exclusive, I just didn't know how to formulate a proper title since English is not my main language. So, please, answer addressing HTML5 and a game engine pro and cons separately)

    Read the article

  • iPhone shooter game bullet physics!

    - by user298261
    Hello, Making a new shooter game here in the vein of "Galaga" (my fav shooter game growing up). Here's the code I have for bullet physics: -(IBAction)shootBullet:(id)sender{ imgBullet.hidden = NO; timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(fireBullet) userInfo:Nil repeats:YES]; } -(void)fireBullet{ imgBullet.center = CGPointMake(imgBullet.center.x + bulletVelocity.x , imgBullet.center.y + bulletVelocity.y); if(imgBullet.center.y <= 0){ imgBullet.hidden = YES; imgBullet.center = self.view.center; [timer invalidate]; } } Anyway, the obvious issue is that once the bullet leaves the screen, its center is being reset, so I'm reusing the same bullet for each press of the "fire" button. Ideally, I would like the user to be able to spam the "fire" button without causing the program to crash. How would I tinker this existing code so that a bullet object would spawn on the button press each time, and then despawn after it exits the screen, or collides with an enemy? Thank you for any assistance you can offer!

    Read the article

  • Bending of track in a racing game

    - by caius
    I am trying to create a small racing game in which the track would be modeled using a BSpline curve for the path's center line and directional vectors to define the 'bending' of the track at each point. My problem is that I don't know how to calculate the correct bending / slope of the curve, in such a way that it would be optimal or at least visually nice for a car to 'bend in the corner'. My idea was to use the direction of the 2nd derivatives of the curve, however while this approach looks fine for most of the track, there are points in which the 2nd derivative makes sharp 'twists' / very quick 180 degree flips. I also read about 'knots' of bsplines, but I don't know if such 'twist' in 2nd derivatives is a knot or knots are something else. Can you tell me that using a BSpline: 1. How could I calculate a visually nice bending of a track for a racing game? 2. Is it possible to do this by using some simple calculations of centripertal force / gravity? 3. Is it possible to do this by using 1st, 2nd and 3rd derivatives of the BSpline curve? I am not looking for the 'physically correct' bending angle for the track, I would just like to create something which is visually pleasing in a simple game. I am using a framework which has a built-in class for BSpline, including support for 1st, 2nd and 3rd derivatives of the curve.

    Read the article

  • simple collision detection with box2dweb

    - by skywalker
    im beginner in box2dweb that version of box2d for javascript i wrote simple gravity system and i want to detect the collision between the box and the ground , when the falling box hit the ground execute simple function like function sucs(){alert("the box on the floor !")}; this is my code var CANVAS_WIDTH = 1024, CANVAS_HEIGHT = 700, SCALE = 30; var b2Vec2 = Box2D.Common.Math.b2Vec2 , b2BodyDef = Box2D.Dynamics.b2BodyDef , b2Body = Box2D.Dynamics.b2Body , b2FixtureDef = Box2D.Dynamics.b2FixtureDef , b2Fixture = Box2D.Dynamics.b2Fixture , b2World = Box2D.Dynamics.b2World , b2MassData = Box2D.Collision.Shapes.b2MassData , b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape , b2CircleShape = Box2D.Collision.Shapes.b2CircleShape , b2DebugDraw = Box2D.Dynamics.b2DebugDraw; var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); var world = new b2World(new b2Vec2(0, 8), true); var fixDef = new b2FixtureDef(); var bodyDef = new b2BodyDef(); fixDef.density = 1.0; fixDef.friction = 0.5; bodyDef.type = b2Body.b2_staticBody; fixDef.shape = new b2PolygonShape; fixDef.shape.SetAsBox(20, 2); bodyDef.position.Set(10, 400 / 30 + 1.8); world.CreateBody(bodyDef).CreateFixture(fixDef); fixDef.density = 1.0; fixDef.friction = 0.5; fixDef.restitution = 0.3; bodyDef.type = b2Body.b2_dynamicBody; bodyDef.position.Set(50 / SCALE, 0 / SCALE); //bodyDef.linearVelocity.Set((Math.random() * 12) + 2, (Math.random() * 12) + 2); fixDef.shape = new b2PolygonShape(); fixDef.shape.SetAsBox(25 / SCALE, 25 / SCALE); world.CreateBody(bodyDef).CreateFixture(fixDef); var debugDraw = new b2DebugDraw(); debugDraw.SetSprite(document.getElementById("canvas").getContext("2d")); debugDraw.SetDrawScale(30.0); debugDraw.SetFillAlpha(0.5); debugDraw.SetLineThickness(1.0); debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit); world.SetDebugDraw(debugDraw); var image = new Image(); image.src = "image.png"; window.setInterval(gameLoop, 1000 / 60); function gameLoop() { world.Step(1 / 60, 8, 3); world.ClearForces(); context.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); b = world.GetBodyList() var pos = b.GetPosition(); context.save(); context.translate(pos.x * SCALE, pos.y * SCALE); context.rotate(b.GetAngle()); context.drawImage(image, -25, -25); context.restore(); b = b.GetNext(); pos = b.GetPosition(); context.save(); context.translate(pos.x * SCALE, pos.y * SCALE); //b.GetAngle()++; context.rotate(b.GetAngle()); context.drawImage(image, -25, -25); context.restore(); world.DrawDebugData(); };

    Read the article

  • How to apply numerical integration on a graph layout

    - by Cumatru
    I've done some basic 1 D integration, but i can't wrap my head around things and apply it to my graph layout. So, consider the picture below: if i drag the red node to the right, i'm forcing his position to my mouse position the other nodes will "follow" him, but how ? For Verlet, to compute the newPosition, i need the acceleration for every node and the currentPosition. That is what i don't understand. How to i compute the acceleration and the currentPosition ? The currentPosition will be the position of the RedNode ? If yes, doesn't that means that they will all overlap ? http://i.stack.imgur.com/NCKmO.jpg

    Read the article

  • Android in-game pause screen

    - by Max
    Right now Im calling a new activity with an xml-view when I pause my game, but Since I do this I need to use context in my real-time code, and this is causing a memory leak. Is there any preffered way to pause the game? By pause I mean if game is over, if I die, or if I press pause-button. Would a custom dialog work just aswell? this would mean I wont have to leave my main-activity while im in-game.

    Read the article

  • Axis-Aligned Bounding Boxes vs Bounding Ellipse

    - by Griffin
    Why is it that most, if not all collision detection algorithms today require each body to have an AABB for the use in the broad phase only? It seems to me like simply placing a circle at the body's centroid, and extending the radius to where the circle encompasses the entire body would be optimal. This would not need to be updated after the body rotates and broad overlap-calculation would be faster to. Correct? Bonus: Would a bounding ellipse be practical for broad phase calculations also, since it would better represent long, skinny shapes? Or would it require extensive calculations, defeating the purpose of broad-phase?

    Read the article

  • Game timings and formats

    - by topright
    There are more or less standardized TV-show/movie formats and recommended timings: 1. By the early 1960s, television companies commonly presented half-hour long "comedy" series, or one hour long "dramas." Half-hour series were mostly restricted to situation comedy or family comedy, and were usually aired with either a live or artificial laugh track. One hour dramas included genre series such as police and detective series, westerns, science fiction, and, later, serialized prime time soap operas. Programs today still overwhelmingly conform to these half-hour and one hour guidelines. Source 2. In the United States, most medical dramas are one hour long. Source 3. Traditionally serials were broadcast as fifteen minute installments each weekday in daytime slots. In 1956 As the World Turns debuted as the first half-hour soap opera. All soap operas broadcast half-hour episodes by the end of the 1960s. With increased popularity in the 1970s most soap operas expanded to an hour (Another World even expanded to ninety minutes for a short time). More than half of the serials had expanded to one hour episodes by 1980. As of 2010, six of the seven US serials air one hour episodes each weekday. Source Interesting. Are there any standards of timing in game development? Well, 5-20 minutes casual games, of course. There is even a "5-minutes-game" site. And 1-hour-gamer site. Are there 1-week, 1-year, 1-eternity game formats? Chess and Go - deep games that you can study all your life; but they are played in hour or several days (pro games). Addictive long-term online role-playing games (without win-condition) are played in monthes and, possibly, years. Replayability is an important factor to consider. It's good when game design document contains a line: "A game is designed for solving in X hours". How can it be measured before there is any prototype or demo? When you know your game format, you know your audience (and vice versa). It is practical question. Are there psychological researches about dynamic of gaming interest and involvement? And is there a correlation between game format and game genre?

    Read the article

  • Collision filtering techniques

    - by Griffin
    I was wondering what efficient techniques are out there for mapping collision filtering between various bodies, sub-bodies, and so forth. I'm familiar with the simple idea of having different layers of 2D bodies, but this is not sufficient for more complex mapping: (Think of having sub-bodies of a body, such as limbs, collide with each other by placing them on the same layer, and then wanting to only have the legs collide with the ground while the arms would not) This can be solved with a multidimensional layer setup, but I would probably end up just creating more and more layers to the point where the simplicity and efficiency of layer filtering would be gone. Are there any more complex ways to solve even more complex situations than this?

    Read the article

  • In-Game Encyclopedias

    - by SHiNKiROU
    There are some games where there is an in-game encyclopedia where you can know many things about characters and settings of the game. For example, the Codex in Mass Effect. I want to know if it is exclusive to Bioware, and get inspired about other encyclopedia systems. What are some other examples of in-game encyclopedias? How effective is it? I also want some examples where the in-game encyclopedia is not effective at all or an ignored feature

    Read the article

  • Implementing a wheeled character controller

    - by Lazlo
    I'm trying to implement Boxycraft's character controller in XNA (with Farseer), as Bryan Dysmas did (minus the jumping part, yet). My current implementation seems to sometimes glitch in between two parallel planes, and fails to climb 45 degree slopes. (YouTube videos in links, plane glitch is subtle). How can I fix it? From the textual description, I seem to be doing it right. Here is my implementation (it seems like a huge wall of text, but it's easy to read. I wish I could simplify and isolate the problem more, but I can't): public Body TorsoBody { get; private set; } public PolygonShape TorsoShape { get; private set; } public Body LegsBody { get; private set; } public Shape LegsShape { get; private set; } public RevoluteJoint Hips { get; private set; } public FixedAngleJoint FixedAngleJoint { get; private set; } public AngleJoint AngleJoint { get; private set; } ... this.TorsoBody = BodyFactory.CreateRectangle(this.World, 1, 1.5f, 1); this.TorsoShape = new PolygonShape(1); this.TorsoShape.SetAsBox(0.5f, 0.75f); this.TorsoBody.CreateFixture(this.TorsoShape); this.TorsoBody.IsStatic = false; this.LegsBody = BodyFactory.CreateCircle(this.World, 0.5f, 1); this.LegsShape = new CircleShape(0.5f, 1); this.LegsBody.CreateFixture(this.LegsShape); this.LegsBody.Position -= 0.75f * Vector2.UnitY; this.LegsBody.IsStatic = false; this.Hips = JointFactory.CreateRevoluteJoint(this.TorsoBody, this.LegsBody, Vector2.Zero); this.Hips.MotorEnabled = true; this.AngleJoint = new AngleJoint(this.TorsoBody, this.LegsBody); this.FixedAngleJoint = new FixedAngleJoint(this.TorsoBody); this.Hips.MaxMotorTorque = float.PositiveInfinity; this.World.AddJoint(this.Hips); this.World.AddJoint(this.AngleJoint); this.World.AddJoint(this.FixedAngleJoint); ... public void Move(float m) // -1, 0, +1 { this.Hips.MotorSpeed = 0.5f * m; }

    Read the article

  • Rope Colliding with a Rectangle

    - by Colton
    I have my rope, and I have my rectangles. The rope is similar to the implementation found here: http://nehe.gamedev.net/tutorial/rope_physics/17006/ Now, I want to make the rope properly collide with the rectangle such that the rope will not pass through a rectangle, and wrap around the rectangle and all that good stuff. Currently, I have it set so no rope node can pass through a rect (successfully), however, this means a rope segment can still pass through a block. Ex: So the question is, what can I do to fix this? What I have tried: I create a rectangle between two nodes of a rope, calculate rotation between the nodes, and get myself a transformed rectangle. I can successfully detect a collision between rope segments and a (non-transformed) rectangle. Create a new node or pivot point around the corner of the block, and rearrange nodes to point to the corner node. Trouble is determining what corner the rope segment is passing through. And then the current rope setup goes wonky (based on verlet integration, so a sudden change in position causes the rope to wiggle like a seismograph during a magnitude 8 earth quake.) Among other issues that might be solvable, but its turning into a case by case thing, which doesn't seem right. I think the best answer here would just be a link to a tutorial (I simply can't find any, most lead to box2D or farseer, but I want to at least learn how it works before I hide behind an engine).

    Read the article

  • Continuous Collision Detection Techniques

    - by Griffin
    I know there are quite a few continuous collision detection algorithms out there , but I can't find a list or summary of different 2D techniques; only tutorials on specific algorithms. What techniques are out there for calculating when different 2D bodies will collide and what are the advantages / disadvantages of each? I say techniques and not algorithms because I have not yet decided on how I will store different polygons which might be concave or even have holes. I plan to make a decision on this based on what the algorithm requires (for instance if an algorithm breaks down a polygon into triangles or convex shapes I will simply store the polygon data in this form).

    Read the article

  • Smooth waypoint traversing

    - by TheBroodian
    There are a dozen ways I could word this question, but to keep my thoughts in line, I'm phrasing it in line with my problem at hand. So I'm creating a floating platform that I would like to be able to simply travel from one designated point to another, and then return back to the first, and just pass between the two in a straight line. However, just to make it a little more interesting, I want to add a few rules to the platform. I'm coding it to travel multiples of whole tile values of world data. So if the platform is not stationary, then it will travel at least one whole tile width or tile height. Within one tile length, I would like it to accelerate from a stop to a given max speed. Upon reaching one tile length's distance, I would like it to slow to a stop at given tile coordinate and then repeat the process in reverse. The first two parts aren't too difficult, essentially I'm having trouble with the third part. I would like the platform to stop exactly at a tile coordinate, but being as I'm working with acceleration, it would seem easy to simply begin applying acceleration in the opposite direction to a value storing the platform's current speed once it reaches one tile's length of distance (assuming that the tile is traveling more than one tile-length, but to keep things simple, let's just assume it is)- but then the question is what would the correct value be for acceleration to increment from to produce this effect? How would I find that value?

    Read the article

  • Determining relative velocities on impact?

    - by meds
    I'm trying to figure out a way to determine the relative velocity of a body colliding with another in a 2D environment. For example if one body is moving at (1,0) and another traveling behind it collides with it from behind at (2,0) the velocity of the impact relative to the first body was (1,0). I need a method which takes in two velocities, one velocity belonging to the body the velocity is being measured against, and the other for the impacting body and return the relative velocity.

    Read the article

  • JBox2D applyLinearImpulse doesn't work

    - by Romeo
    So i have this line of code: if(input.isKeyDown(Input.KEY_W)&&canJump()) { body.applyLinearImpulse(new Vec2(0, 30), cam.screenToWorld(body.getPosition())); System.out.println("I can jump!"); } My problem is that the console display I can jump! but the body doesn't do that. Can you explain to me if i do something wrong? Some more code. This function creates my 'hero' the one supposed to jump. private Body setDynamic(float width, float height, float x, float y) { PolygonShape shape = new PolygonShape(); shape.setAsBox(width/2, height/2); BodyDef bd = new BodyDef(); bd.allowSleep = true; bd.position = new Vec2(cam.screenToWorld(new Vec2(x + width / 2, y + height / 2))); bd.type = BodyType.DYNAMIC; bd.userData = new BodyInfo(width, height); Body body = world.createBody(bd); body.createFixture(shape, 10); return body; } And this is the main update loop: if(input.isKeyDown(Input.KEY_A)) { body.setLinearVelocity(new Vec2(-10*delta, body.getLinearVelocity().y)); } else if (input.isKeyDown(Input.KEY_D)) { body.setLinearVelocity(new Vec2(10*delta, body.getLinearVelocity().y)); } else { body.setLinearVelocity(new Vec2(0, body.getLinearVelocity().y)); } if(input.isKeyDown(Input.KEY_W)&&canJump()) { body.applyLinearImpulse(new Vec2(0, 30), body.getPosition()); System.out.println("I can jump!"); } world.step(delta * 0.001f, 10, 5); }

    Read the article

  • Find angle for projectile to meet target in parabolic arc

    - by TheBroodian
    I'm making a thing that launches projectiles in 2D. Its projectiles are fired with a set initial velocity, and are only affected by gravity. Assuming that its target is within range, and that there aren't any obstacles, how would my thing find the appropriate angle at which to launch its projectile (in radians)? The equation for this is found here: Wikipedia: Angle Required to Hit Coordinate Sadly, I'm not a physicist (a.k.a. can't read smart people math) and am having a hard time reading its breakdown. If not only for the sake of anybody else that might read this other than myself, would anybody be kind enough to break the equation down into baby words please?

    Read the article

  • Reflection velocity

    - by MindSeeker
    I'm trying to get a moving circular object to bounce (elastically) off of an immovable circular object. Am I doing this right? (The results look right, but I hate to trust that alone, and I can't find a tutorial that tackles this problem and includes the nitty gritty math/code to verify what I'm doing). If it is right, is there a better/faster/more elegant way to do this? Note that the object (this) is the moving circle, and the EntPointer object is the immovable circle. //take vector separating the two centers <x, y>, and then get unit vector of the result: MathVector2d unitnormal = MathVector2d(this -> Retxpos() - EntPointer -> Retxpos(), this -> Retypos() - EntPointer -> Retypos()).UnitVector(); //take tangent <-y, x> of the unitnormal: MathVector2d unittangent = MathVector2d(-unitnormal.ycomp, unitnormal.xcomp); MathVector2d V1 = MathVector2d(this -> Retxvel(), this -> Retyvel()); //Calculate the normal and tangent vector lengths of the velocity: (the normal changes, the tangent stays the same) double LengthNormal = DotProduct(unitnormal, V1); double LengthTangent = DotProduct(unittangent, V1); MathVector2d VelVecNewNormal = unitnormal.ScalarMultiplication(-LengthNormal); //the negative of what it was before MathVector2d VelVecNewTangent = unittangent.ScalarMultiplication(LengthTangent); //this stays the same MathVector2d NewVel = VectorAddition(VelVecNewNormal, VelVecNewTangent); //combine them xvel = NewVel.xcomp; //and then apply them yvel = NewVel.ycomp; Note also that this question is just about velocity, the position code is handled elsewhere (in other words, assume that this code is implemented at the exact moment that the circles begin to overlap). Thanks in advance for your help and time!

    Read the article

  • How do I calculate the motion of 2 massive bodies in space?

    - by 1224
    I'm writing code simulating the 2-dimensional motion of two massive bodies with gravitational fields. The bodies' masses are known and I have a gravitational force equation. I know from that force I can get a differential equation for coordinates. I know that I once I solve this equation I will get the coordinates. I will need to make up some initial position and some initial velocity. I'd like to end up with a numeric solver for the ordinal differential equation for coordinates to get the formulas that I can write in code. Could someone break down how from laws and initial conditions we get to the formulas that calculate x and y at time t?

    Read the article

  • Box2d contant speed before and after collision

    - by bobenko
    I want to make my body fly at constant speed, how to make it fly at constant speed before and after collision? I set restitution of my body to 1.0 but after some direct and powerful collisions my objects begins to slow, I want it to fly same speed as before. I heard this can be done by setting liner damping of the object, I think it can prevent only from fast flying objects not slow. Thanks in advance.

    Read the article

  • Simple Physics Simulation in java not working.

    - by Static Void Main
    Dear experts, I wanted to implement ball physics and as i m newbie, i adapt the code in tutorial http://adam21.web.officelive.com/Documents/JavaPhysicsTutorial.pdf . i try to follow that as i much as i can, but i m not able to apply all physical phenomenon in code, can somebody please tell me, where i m mistaken or i m still doing some silly programming mistake. The balls are moving when i m not calling bounce method and i m unable to avail the bounce method and ball are moving towards left side instead of falling/ending on floor**, Can some body recommend me some better way or similar easy compact way to accomplish this task of applying physics on two ball or more balls with interactivity. here is code ; import java.awt.*; public class AdobeBall { protected int radius = 20; protected Color color; // ... Constants final static int DIAMETER = 40; // ... Instance variables private int m_x; // x and y coordinates upper left private int m_y; private double dx = 3.0; // delta x and y private double dy = 6.0; private double m_velocityX; // Pixels to move each time move() is called. private double m_velocityY; private int m_rightBound; // Maximum permissible x, y values. private int m_bottomBound; public AdobeBall(int x, int y, double velocityX, double velocityY, Color color1) { super(); m_x = x; m_y = y; m_velocityX = velocityX; m_velocityY = velocityY; color = color1; } public double getSpeed() { return Math.sqrt((m_x + m_velocityX - m_x) * (m_x + m_velocityX - m_x) + (m_y + m_velocityY - m_y) * (m_y + m_velocityY - m_y)); } public void setSpeed(double speed) { double currentSpeed = Math.sqrt(dx * dx + dy * dy); dx = dx * speed / currentSpeed; dy = dy * speed / currentSpeed; } public void setDirection(double direction) { m_velocityX = (int) (Math.cos(direction) * getSpeed()); m_velocityY = (int) (Math.sin(direction) * getSpeed()); } public double getDirection() { double h = ((m_x + dx - m_x) * (m_x + dx - m_x)) + ((m_y + dy - m_y) * (m_y + dy - m_y)); double a = (m_x + dx - m_x) / h; return a; } // ======================================================== setBounds public void setBounds(int width, int height) { m_rightBound = width - DIAMETER; m_bottomBound = height - DIAMETER; } // ============================================================== move public void move() { double gravAmount = 0.02; double gravDir = 90; // The direction for the gravity to be in. // ... Move the ball at the give velocity. m_x += m_velocityX; m_y += m_velocityY; // ... Bounce the ball off the walls if necessary. if (m_x < 0) { // If at or beyond left side m_x = 0; // Place against edge and m_velocityX = -m_velocityX; } else if (m_x > m_rightBound) { // If at or beyond right side m_x = m_rightBound; // Place against right edge. m_velocityX = -m_velocityX; } if (m_y < 0) { // if we're at top m_y = 0; m_velocityY = -m_velocityY; } else if (m_y > m_bottomBound) { // if we're at bottom m_y = m_bottomBound; m_velocityY = -m_velocityY; } // double speed = Math.sqrt((m_velocityX * m_velocityX) // + (m_velocityY * m_velocityY)); // ...Friction stuff double fricMax = 0.02; // You can use any number, preferably less than 1 double friction = getSpeed(); if (friction > fricMax) friction = fricMax; if (m_velocityX >= 0) { m_velocityX -= friction; } if (m_velocityX <= 0) { m_velocityX += friction; } if (m_velocityY >= 0) { m_velocityY -= friction; } if (m_velocityY <= 0) { m_velocityY += friction; } // ...Gravity stuff m_velocityX += Math.cos(gravDir) * gravAmount; m_velocityY += Math.sin(gravDir) * gravAmount; } public Color getColor() { return color; } public void setColor(Color newColor) { color = newColor; } // ============================================= getDiameter, getX, getY public int getDiameter() { return DIAMETER; } public double getRadius() { return radius; // radius should be a local variable in Ball. } public int getX() { return m_x; } public int getY() { return m_y; } } using adobeBall: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AdobeBallImplementation implements Runnable { private static final long serialVersionUID = 1L; private volatile boolean Play; private long mFrameDelay; private JFrame frame; private MyKeyListener pit; /** true means mouse was pressed in ball and still in panel. */ private boolean _canDrag = false; private static final int MAX_BALLS = 50; // max number allowed private int currentNumBalls = 2; // number currently active private AdobeBall[] ball = new AdobeBall[MAX_BALLS]; public AdobeBallImplementation(Color ballColor) { frame = new JFrame("simple gaming loop in java"); frame.setSize(400, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pit = new MyKeyListener(); pit.setPreferredSize(new Dimension(400, 400)); frame.setContentPane(pit); ball[0] = new AdobeBall(34, 150, 7, 2, Color.YELLOW); ball[1] = new AdobeBall(50, 50, 5, 3, Color.BLUE); frame.pack(); frame.setVisible(true); frame.setBackground(Color.white); start(); frame.addMouseListener(pit); frame.addMouseMotionListener(pit); } public void start() { Play = true; Thread t = new Thread(this); t.start(); } public void stop() { Play = false; } public void run() { while (Play == true) { // bounce(ball[0],ball[1]); runball(); pit.repaint(); try { Thread.sleep(mFrameDelay); } catch (InterruptedException ie) { stop(); } } } public void drawworld(Graphics g) { for (int i = 0; i < currentNumBalls; i++) { g.setColor(ball[i].getColor()); g.fillOval(ball[i].getX(), ball[i].getY(), 40, 40); } } public double pointDistance (double x1, double y1, double x2, double y2) { return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); } public void runball() { while (Play == true) { try { for (int i = 0; i < currentNumBalls; i++) { for (int j = 0; j < currentNumBalls; j++) { if (pointDistance(ball[i].getX(), ball[i].getY(), ball[j].getX(), ball[j].getY()) < ball[i] .getRadius() + ball[j].getRadius() + 2) { // bounce(ball[i],ball[j]); ball[i].setBounds(pit.getWidth(), pit.getHeight()); ball[i].move(); pit.repaint(); } } } try { Thread.sleep(50); } catch (Exception e) { System.exit(0); } } catch (Exception e) { e.printStackTrace(); } } } public static double pointDirection(int x1, int y1, int x2, int y2) { double H = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); // The // hypotenuse double x = x2 - x1; // The opposite double y = y2 - y1; // The adjacent double angle = Math.acos(x / H); angle = angle * 57.2960285258; if (y < 0) { angle = 360 - angle; } return angle; } public static void bounce(AdobeBall b1, AdobeBall b2) { if (b2.getSpeed() == 0 && b1.getSpeed() == 0) { // Both balls are stopped. b1.setDirection(pointDirection(b1.getX(), b1.getY(), b2.getX(), b2 .getY())); b2.setDirection(pointDirection(b2.getX(), b2.getY(), b1.getX(), b1 .getY())); b1.setSpeed(1); b2.setSpeed(1); } else if (b2.getSpeed() == 0 && b1.getSpeed() != 0) { // B1 is moving. B2 is stationary. double angle = pointDirection(b1.getX(), b1.getY(), b2.getX(), b2 .getY()); b2.setSpeed(b1.getSpeed()); b2.setDirection(angle); b1.setDirection(angle - 90); } else if (b1.getSpeed() == 0 && b2.getSpeed() != 0) { // B1 is moving. B2 is stationary. double angle = pointDirection(b2.getX(), b2.getY(), b1.getX(), b1 .getY()); b1.setSpeed(b2.getSpeed()); b1.setDirection(angle); b2.setDirection(angle - 90); } else { // Both balls are moving. AdobeBall tmp = b1; double angle = pointDirection(b2.getX(), b2.getY(), b1.getX(), b1 .getY()); double origangle = b1.getDirection(); b1.setDirection(angle + origangle); angle = pointDirection(tmp.getX(), tmp.getY(), b2.getX(), b2.getY()); origangle = b2.getDirection(); b2.setDirection(angle + origangle); } } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { new AdobeBallImplementation(Color.red); } }); } } *EDIT:*ok splitting the code using new approach for gravity from this forum: this code also not working the ball is not coming on floor: public void mymove() { m_x += m_velocityX; m_y += m_velocityY; if (m_y + m_bottomBound > 400) { m_velocityY *= -0.981; // setY(400 - m_bottomBound); m_y = 400 - m_bottomBound; } // ... Bounce the ball off the walls if necessary. if (m_x < 0) { // If at or beyond left side m_x = 0; // Place against edge and m_velocityX = -m_velocityX; } else if (m_x > m_rightBound) { // If at or beyond right side m_x = m_rightBound - 20; // Place against right edge. m_velocityX = -m_velocityX; } if (m_y < 0) { // if we're at top m_y = 1; m_velocityY = -m_velocityY; } else if (m_y > m_bottomBound) { // if we're at bottom m_y = m_bottomBound - 20; m_velocityY = -m_velocityY; } } thanks a lot for any correction and help. jibby

    Read the article

  • Runge-Kutta (RK4) integration for game physics

    - by Kai
    Gaffer on Games has a great article about using RK4 integration for better game physics. The implementation is straightforward but the math behind it confuses me. I understand derivatives and integrals on a conceptual level but I haven't manipulated equations in a long time. Here's the brunt of Gaffer's implementation: void integrate(State &state, float t, float dt) { Derivative a = evaluate(state, t, 0.0f, Derivative()); Derivative b = evaluate(state, t+dt*0.5f, dt*0.5f, a); Derivative c = evaluate(state, t+dt*0.5f, dt*0.5f, b); Derivative d = evaluate(state, t+dt, dt, c); const float dxdt = 1.0f/6.0f * (a.dx + 2.0f*(b.dx + c.dx) + d.dx); const float dvdt = 1.0f/6.0f * (a.dv + 2.0f*(b.dv + c.dv) + d.dv) state.x = state.x + dxdt * dt; state.v = state.v + dvdt * dt; } Can anybody explain in simple terms how RK4 works? Specifically, why are we averaging the derivatives at 0.0f, 0.5f, 0.5f, and 1.0f? How is averaging derivatives up to the 4th order different from doing a simple euler integration with a smaller timestep? After reading the accepted answer below, and several other articles, I have a grasp on how RK4 works. To answer my own questions: Can anybody explain in simple terms how RK4 works? RK4 takes advantage of the fact that we can get a much better approximation of a function if we use its higher-order derivatives rather than just the first or second derivative. That's why the Taylor series converges much faster than Euler approximations. (take a look at the animation on the right side of that page) Specifically, why are we averaging the derivatives at 0.0f, 0.5f, 0.5f, and 1.0f? The Runge-Kutta method is an approximation of a function that samples derivatives of several points within a timestep, unlike the Taylor series which only samples derivatives of a single point. After sampling these derivatives we need to know how to weigh each sample to get the closest approximation possible. An easy way to do this is to pick constants that coincide with the Taylor series, which is how the constants of a Runge-Kutta equation are determined. This article made it clearer for me: http://web.mit.edu/10.001/Web/Course%5FNotes/Differential%5FEquations%5FNotes/node5.html. Notice how (15) is the Taylor series expansion while (17) is the Runge-Kutta derivation. How is averaging derivatives up to the 4th order different from doing a simple euler integration with a smaller timestep? Mathematically it converges much faster than doing many Euler approximations. Of course, with enough Euler approximations we can gain equal accuracy to RK4, but the computational power needed doesn't justify using Euler.

    Read the article

  • Game Center alternatives for non-iOS development

    - by Eat at Joes
    I have completed a game for iOS which integrates GameKit. I am happy with Game Center however my game also has an HTML5 web version and will soo have an Android version. My question is what alternatives do I have for non-iOS platforms but primarily for Android and to a lesser extent a Javascript/Web SDK. I looked at Openfeint a year ago and it seemed to be a good solution back then but am not sure if this is still the case? Note, I have no plans to replace what I already have in my iOS game and I understand the leader boards, users, and achievements won't be shared out of Game Center.

    Read the article

  • What can make a peaceful game successful?

    - by Miro
    Today, the most successful games are action games like FPS, RPG, MMORPG... I'd like to make peaceful game, but I don't know how to attract people. I can make good graphics, but that's not the main thing that makes people like game more that couple of minutes. The content is important. In game styles mentioned in beginning are main content fight, kill others, make from yourself predator/the most powerful creature/player in the game. But what content can attract people in peaceful game?

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >