_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
6 | Choosing the correct normal for a collision I have taken the task of building a basic impulse physics engine. Circle vs Circle collision resolution has been done and I moved onto Line vs Circle. I can detect a collision and know that the normal should be perpendicular to the line which can be calculated easily (2d physics engine). However it's the direction of the normal that I cannot work out. From the image you can see there are 2 possible normals, one upwards (the correct one) and one downwards. How do I choose the correct normal? |
6 | Applying Angular Acceleration in a Basic Physics Model I'm attempting to use a basic physics system to create an arcade flight model. So far I have managed to get the aircraft moving forward, apply gravity, etc. However, after trying to implement torque I noticed some interesting behaviour in the flight model. When turning after a while the controls appear to reverse, sometimes, the controls for the different movements (pitch, roll, yaw) also seem to change. I was hoping that someone may be able to advise me as to what I should check next. I have included my source code in case anyone spots any glaring mistakes! I have listed some of the variables below to show their data types Quaternion rotation Quaternion.Identity Quaternion newRotation Quaternion.Identity Vector3 rotationChange Vector3.Zero Vector3 rotVec Vector3.Zero Below is the update logic for the rotational forces dt (float)gameTime.ElapsedGameTime.TotalSeconds if (dt gt 1.0f 60.0f) dt 1.0f 60.0f Vector3 newRotationChange rotationChange dt angularAcceleration Vector3 newRotVec rotVec dt newRotationChange rotationChange newRotationChange rotVec newRotVec Vector3 rotAxis rotVec rotAxis.Normalize() if (rotVec.Length() lt 0.001f) rotVec Vector3.Zero newRotation Quaternion.CreateFromAxisAngle(forwardVector, 0.0f) else float angle rotVec.Length() newRotation Quaternion.CreateFromAxisAngle(rotAxis, angle) if (rotationChange.Length() lt 0.001f) rotationChange Vector3.Zero rotation newRotation angularAcceleration Vector3.Zero My method for creating the torque lt summary gt Creates a rotational force for an object lt summary gt lt param name "pointOfAction" gt Point the force is being applied on the object lt param gt lt param name "forceAmount" gt Magnitude of the force being applied lt param gt lt param name "forceDir" gt Direction of the force being applied lt param gt public void CreateTorque(Vector3 pointOfAction, float forceAmount, Vector3 forceDir) Vector from position to pointOfAction Vector3 r pointOfAction position Create the force Vector3 force forceDir forceAmount Create the torque force torque Vector3.Cross(r, force) angularAcceleration torque Sorry for the massive code block and thanks in advance for any help you can give. |
6 | How can velocity be normalized after a collision if a projectile needs to maintain its height? I want a thrown disc to travel along the same height, even after collisions. The problem is, there's an edge case that I'm not sure how to deal with. The lowest tech solution would probably be to quickly interpolate the rotation of the disc so that it's flat, and also interpolate its height so that it never collides with another object in a way that would impact its height, but that might be a bit heavy handed. I worry that it would look really bad if you're holding the disc at an angle when releasing it for a throw, and it just suddenly "swooshes" flat mid flight. Would that seem janky? If I don't do that, and I simply retain the disc's rotation as it flies along its path, then it might collide with an object's edge in a way where the correct bounce angle would send it upwards or downwards, which I don't want. But if I simply hard code the y velocity to 0, then in those instances, the lateral velocity becomes very low. Should I just check for a "minimum" speed, and increase it to that if it falls below that? Because the issue is that in the case where it bounces upward, there's a good chance that the correct bounce angle, if the y velocity is ignored, results in the disc continuing in the same direction rather than bouncing. So I'm honestly leaning towards extending the collision boxes for these objects really far above and below where the disc could possibly be thrown, that way regardless of its orientation, it would always be the side of a cylinder colliding either with the side of a box or one of its vertical edges, and the velocity change should thus (hopefully) always look like it makes sense. |
6 | Relative Position Rotation calculation I have 2 objects each with a 3x3 Matrix (Orientation) and a Vector3 (Translation). Both are relative to world coordinates. How do I calculate the position and orientation of object B in relation to object A? I'm using the JVector, JMatrix that are a part of the Jitter3D physics library. (http code.google.com p jitterphysics ) Any help would be greatly appreciated! |
6 | how to move object in a circle around point? There are two controllable objects orbiting around a centre block. Unfortunately, I don't really know how to stick them so they can only move around the block (left a sends them clockwise, right a sends them anti clockwise) and can only get them to move like normal sprites not on a set path. I haven't got any code to show yet, but I could really appreciate either some advice, or preferably some examples. |
6 | RK4, Derivatives, Understanding Game Physics Gafferon Games has a great article on RK4 Integration for building physics simulations which can be found here Integration Basics Personally my mathematics and physics knowledge could use improvement. I feel comfortable within the realm of vector mathematics, trig, some stats (I've had to use linear line regression formulas for software, etc. ), and basically most things high school level to first year college. Now to the question, I've read this article, downloaded the associated source and debugged line by line to try and get an understanding of what is happening and still feel like I'm clearly not getting what I'm looking at. I've searched the internet trying to find the "For Dummies" versions, frankly I learn a little differently and staring at formulas all day with the emphasis on memorization isn't going to cut it as I need to understand what is happening so I can be flexible applying it. So here's what I think I understand so far, but I am hoping someone else can clarify or completely correct me. The RK4 uses a Euler step, then bases that to move forward in time to calculate several more essentially Euler steps(?) and determines using a weighted sum what the best position and velocity is for the next frame? Furthermore that acceleration method (converted into AS3) private function acceleration(state State, time Number) Number const k int 10 const b int 1 return k state.x b state.v takes a constant mass(10) and force(1)? and returns some weird calculation I have no idea why... mass position force velocity? what? Then for my last bit of confusion, in the evaluate methods which look like (AS3) private function evaluateD(initial State, time Number, dtime Number, d Derivative) Derivative var state State new State() state.x initial.x d.dx dtime state.v initial.v d.dv dtime var output Derivative new Derivative() output.dx state.v output.dv acceleration(state, time dtime) return output We store a new state with the time step, then set a derivative to return...I sort of understand this as it's used in the approximation process, but what is this! output.dx state.v output.dv acceleration(state, time dtime) ok I get we are getting the new velocity since v a t, obviously I don't what acceleration() is returning though. We set the derivative output change in position to the states new velocity? Huh? Lastly this test simulation runs doing this var state State new State() state.x 100 state.v 0 t 0 dt 0.1 while (Math.abs(state.x) gt 0.001 Math.abs(state.v) gt 0.001) trace(state.x, state.v) integrate(state, t, dt) t dt So we are setting a new state with a positional value of 100, and a velocity of 0? What is the point of this simulation if we have no velocity... Anyway, needless to say I'm pretty confused and have drifted off planet Earth. Hoping someone out there can clarify this for me. |
6 | When should I use a fixed or variable time step? Should a game loop be based on fixed or variable time steps? Is one always superior, or does the right choice vary by game? Variable time step Physics updates are passed a "time elapsed since last update" argument and are hence framerate dependent. This may mean doing calculations as position distancePerSecond timeElapsed. Pros smooth, easier to to code Cons non deterministic, unpredictable at very small or large steps deWiTTERS example while( game is running ) prev frame tick curr frame tick curr frame tick GetTickCount() update( curr frame tick prev frame tick ) render() Fixed time step Updates might not even accept a "time elapsed", as they assume each update is for a fixed time period. Calculations may be done as position distancePerUpdate. The example includes an interpolation during render. Pros predictable, deterministic (easier to network sync?), clearer calculation code Cons not synced to monitor v sync (causes jittery graphics unless you interpolate), limited max frame rate (unless you interpolate), hard to work within frameworks that assume variable time steps (like Pyglet or Flixel) deWiTTERS example while( game is running ) while( GetTickCount() gt next game tick ) update() next game tick SKIP TICKS interpolation float( GetTickCount() SKIP TICKS next game tick ) float( SKIP TICKS ) render( interpolation ) Some resources Gaffer on games Fix your timestep! deWitter's game loop article Quake 3's FPS affects jump physics allegedly a reason Doom 3 is frame locked to 60fps? Flixel requires a variable timestep (I think this is determined by Flash) whereas Flashpunk allows both types. Box2D's manual Simulating the World of Box2D suggests it uses constant time steps. |
6 | Who know how to implement the 2D bone animation showed in the game? I wonder how do they implement the bone animation in the flash game http www.foddy.net athletics.swf Do you know any study materials which I can start to learn 2D bone system from? I just implemented a avatar system by compose multiple bitmaps in each frame(similar with maple story), but some guys tell me that, a bone system can save more art resources, so I want to learn some thing about that. |
6 | What is the point of "delta" in this code? Does it reflect a standard thing in game dev? I know very little about game programming but would like to learn more. I am trying to understand the code for this game. I am trying to understand why the code is passing a "delta" to Shipcontrols.js, which changes the direction of the ship based on user input. Basically the game calculates "delta" every loop... Here is an abbreviated version of the stack that uses delta thru one loop... var delta now this.time this.time now this.current.render.call(this.current, delta, this.renderer) Steps into here... ctx.manager.add("game", scene, camera, function(delta, renderer) if(delta gt 25 amp amp this.objects.lowFPS lt 1000) this.objects.lowFPS var dt delta 16.6 this.objects.components.shipControls.update(dt) Steps into here... bkcore.hexgl.ShipControls.prototype.update function(dt) var pitchAng var yaw var roll if (undefined ! hand) Which does stuff like this... if(this.key.forward) this.speed this.thrust dt else and this... if(this.key.right) angularAmount this.angularSpeed dt What is the point of delta here? Is it just trying to introduce an element of randomness? The code for this game is very good. Why did this guy use delta? |
6 | Changing orientation by applying torques Suppose you've got an object floating freely in space. You have a vector you want this object to point towards, and a vector representing the direction it's currently facing. From these two, you can get the rotation (matrix, quaternion, whatever) that represents the change in orientation to bring the two vectors into alignment. If you only have the ability to apply torque (derivative of angular velocity) to your object, what's a good algorithm for applying torque over time that won't over undershoot the destination? (In this case, it's a space ship that wants to automatically orient itself in the direction of travel using thrusters. Roll is irrelevant.) |
6 | How to make a smooth projectile in roblox? I am trying to make a projectile (Energy ball) for my game. I am using body velocities, but the issue is is that it seems laggy. I shoot it then half a second through flight it seems to stop in mid air for a quarter of a second then continue. This only happens the first minute of playing. Here is my code local Motion Instance.new("BodyVelocity", Ball) Motion.Velocity ((MouseClickLocation Player.Character.HumanoidRootPart.Position).Unit 100) Why is the described behavior happening and how can I make it never happen? |
6 | How to make character gain acceleration? I want to create more realistic physics for my 2D games. Currently, the character and the other game objects in my games start moving instantly (achieve maximum speed instantly) and stop instantly (achieve 0 speed instantly). There is no transition between speed levels resting and moving, moving and resting. I heard about 'steering behaviors', but am pretty sure they're mostly for designing AI agents' movements. Should I learn steering behaviors to make more realistic character movements in general? (In the physics aspect). Is this the way to go? If the answer is 'yes', could you recommend a good source to learn them? |
6 | How do I convert matrices intended for OpenGL to be compatible for DirectX? I have finished working through the book "Game Physics Engine Development 2nd Ed" by Millington, and have got it working, but I want to adapt it to work with DirectX. I understand that D3D9 has the option to use either left handed, or right handed convention, but I am unsure about how to return my matrices to be usable by D3D. The source code gives returning OpenGL column major matrices (the transpose of the working transform matrix shown below), but DirectX is row major. For those unfamiliar for the organization of the matrices used in the book r11 r12 r13 t1 r21 r22 r23 t2 r31 r32 r33 t3 0 0 0 1 r meaning the value of that element in the rotation matrix, and t meaning the translation value. So the question in short is How do I convert the matrix above to be easily usable by D3D? All of the documentation that I have found simply states that D3D is row major, but not where to put what elements so that it is usable by D3D in terms of rotation, and translation elements. |
6 | Channelling an explosion along a narrow passage I am simulating explosions in a 2D maze game. If an explosion occurs in an open area, it covers a circular region (this is the easy bit.) However if an explosion occurs in a narrow passage (i.e narrower than the blast range) then it should be "compressed", so that it goes further and also it should go around corners. Ultimately, unless it is completely boxed in, then it should cover a constant number of pixels, spreading in whatever direction is necessary to reach this total area. I have tried using a shortest path algorithm to pick the nearest N pixels to the origin avoiding walls, but the effect is exaggerated the blast travels around corners too easily, making U turns even when there is a clear path in another direction. I don't know whether this is realistic or not but it is counter intuitive to players who assume that they can hide around a corner and the blast will take the path of least resistance in a different direction. Is there a well known (and fast) algorithm for this? |
6 | Twin stick controls for a cohesive group of agents I'm trying to implement a classic twin stick controller for a group of physics based game objects. Here are the rules I'm trying to follow Agents always stay close to each other within a certain threshold. Moving the left stick moves the entire group in that direction. Moving the group on a collider like a wall will "compress" the group like a ball. Releasing the left stick will make the group recover its "natural" shape. I tried a few things Classic steering with cohesion follow behaviors This kinda works, but when moving against a sharp corner, a part of the group will move on and separate from the others. Adjusting the steering weights in this scenario produces unnatural results, and the whole thing just feels too "floaty". Softbody simulation This works pretty well when moving on a corner, but you can really feel the springs between each agent. Again, it just feels wrong as a whole. Box2D joints between each agent Keeps all the agents tightly packed, but the group feels very rigid. The solution might be a combination of the previous points, but I'm pretty sure I'm over thinking this. |
6 | Altering Animation Playback Given Terrain Information Say my character has a jog animation. Assuming Y is vertical, his feet leave the ground at Y 0 and hit the ground again at Y 0. This works fine in a world like that of Minecraft, where every surface the player could traverse is flat. Now say the character is jogging through hilly terrain. Without any transformations, the animation would break through the ground at certain points. (As the character's foot is lifted and moved forwards, it would go straight through the hill.) How do I remove this artifact? Do I ask the artists to create separate animations depending on the grade of the terrain? Is there a standard system to resolve animation world collisions that I'm unfamiliar with? Or is there another more logical approach I haven't thought of yet? |
6 | Should a bowling game use a 2d or a 3d physics engine? I'm creating a bowling game in flash as3. I'm new to physics engines, so, to start I've begun to learn Box2D since I've heard it's one of the most popular physics game engines. Currently, I'm not sure if it's the best solution. I'm not sure even if I should use a 2D physics engine or if I should move to 3D physics engine. As you can see in the attached screenshot of my game, the ball should move on the lane until it hits the pins. The game has some amount of 3D behavior. Please advise. |
6 | Web workers for HTML5 game physics simulation? A bit related to this question. The idea is to guarantee the same physics behavior as much as possible. Would it be possible to run fixed time step physics on a web worker? The UI would update itself with different variable refresh rate. Has anyone tried such yet? |
6 | Increasing mass in ineleastic collision by orders of magnitude resultsin little change in velocity When increasing my rocketMass from 10 to 1000 or to a 1000 or bringing my shipMass down to 1, I notice very little increase in how far the ship's final inertia is. I'm expecting that increasing from 10 to 1000 will be visibly about 100 times faster.. but it's not. If I multiply the hypotenuse at the end, that does make the bouncing incredibly faster. Am I misunderstanding physics or is this a calculation error? handleCollision(r) var angle r.r Math.PI 180.0 var rr this.r Math.PI 180 var rocketVector 'x' r.power Math.cos(angle), 'y' r.power Math.sin(angle) var inertiaVector 'x' this.magnitude Math.cos(rr), 'y' this.magnitude Math.sin(rr) var rMass 100 var shipMass 1 var x (rMass rocketVector.x) (shipMass inertiaVector.x) var y (rMass rocketVector.y) (shipMass inertiaVector.y) var xDividedByMass x (rMass shipMass) var yDividedByMass y (rMass shipMass) var yRadians (yDividedByMass Math.PI 180) var xRadians (xDividedByMass Math.PI 180) var theta Math.atan( yRadians xRadians) theta theta 180 Math.PI console.log(theta) var hypotenuse Math.sqrt((xDividedByMass xDividedByMass) (yDividedByMass yDividedByMass)) if (x lt 0) theta 180 this.r theta if (this.r lt 0) this.r 360 else if (this.r gt 360) this.r 360 |
6 | LOVE Physics Joint Stretching After asking a similar question yesterday I've come across another problem with using joints in box2D LOVE and trying to create a weighted chain. Everything is set up as follows, I've tried to remove most of the fluff Each link is created as a body shape pair then joined together and added to a links table. for i 1, segments, 1 do link link.body love.physics.newBody(world, xpos, ypos, "dynamic") if (i segments) then link.shape love.physics.newCircleShape(endlink radius) Ending link else link.shape love.physics.newCircleShape(link radius) end link.fixture love.physics.newFixture(link.body, link.shape) Fix bodies to shapes table.insert(links,link) ypos ypos link distance end Links are joined together using rope joints to allow for some springy ness for i 2, links, 1 do x1,y1 links i 1 .body getPosition() x2,y2 links i .body getPosition() links i 1 .join love.physics.newRopeJoint(links i 1 .body, links i .body, x1, y1, x2, y2, link distance, true ) end The player controls the first element of the chain and holds the table of links, its created as follows local body love.physics.newBody(world, 300, 100, "kinematic") local shape love.physics.newCircleShape(3) local fixture love.physics.newFixture(body, shape) local chain chain.new(world) Joined to the chain x1,y1 body getPosition() x2,y2 links 1 .body getPosition() join love.physics.newRevoluteJoint(body, links 1 .body, x1, y1, x2, y2, true ) The player tracks the mouse cursor, determines a velocity and moves towards it by setting the linear velocity of the first chain element body setLinearVelocity(velocity.x, velocity.y) And this very nearly works, you can pull the chain around quite nicely using the mouse (directing the top pink element), however if you keep spinning the chain it begins to stretch and pull away from the first element Any ideas on how to solve this? I've tried using different joints and parameters, adding a reinforcing joint from the first link to the last, adjusting body weights and altering the update iterations but can't seem to find anything effective. Many thanks. |
6 | Car physics velocity and latheral force Im developing simple car racing game. To turn a car, I need to calculate slip angles for each tire and then use those angles to find lateral force (using Hans B. Pacejka magic formula). One thing I don't understand is relation between car s speed and lateral forces. Everywhere is written, that lateral force depends only on slip angle. But it means that lateral force will be the same for slow and very fast velocity. Is that true? How to use lateral forces to move a car? In my opinion lateral force should be small if velocity is small. |
6 | Unit conversion for physics I'm doing the physics for a 2D game which visuals are represented in openGl. Gravity is 9,8 m s 2, how do i convert that to my screen size? OpenGl sets width to 1 to 1, and does aspect ratio of the screens real width and height to get height's size(normaly from 3 to 3, due is a smartphone game). I know i have to convert meters to my screen size units, but what are those units and how do I convert meters to them? For example, lets say I want my screen to represent 20 meters, what are the maths? 9,8 m s 2 x screenUnits m y screenUnits s 2 Those screen units are pixels? It doesn't make much sense cos OpenGl scales from 1 to 1 independend of the amount of pixels represented by that size. I want this to work the same on various smartphones. Thanks in advance. |
6 | How can I manage the deceleration of units so that they arrive on target? When I first started trying to set up my air units' movement in my RTS game, I thought it was going to be easy with simple Euler method linear acceleration. This was far from the case as the ship would have to slow to a halt on exactly the target destination, as well as properly compensate after a sharp turn. How would I decelerate my unit exactly onto the target destination and properly compensate for changed destinations while still factoring in the current velocity in a 2D simulation (Positions and velocity stored in 2D vectors)? StarCraft 2 does this well, and I'd like to arrive at a similar effect. I want something like shown here. Acceleration can be seen at 0 20. Turning and maintaining momentum can be seen at 1 25. Deceleration can be seen at 1 55. (Find these times in recent comments of the video). Note I'm using a lockstep model and frame rate can be either 5 or 10 per second depending on players' computer abilities. |
6 | Bird flight simulation (physics) I tried to search something about bird like animal flight simulation but it looks like everything is spammed with flappy bird 2D questions. I want to have in my 3D game bird like animals with realistic flight, for example we have a scene where player attacked by predator birds and he must attack them with gun. When I say bird like, I mean that animal has wings. As I understand I need to apply force to bird object to compensate gravity force, but if I do this strictly, it looks very unnatural. So could someone provide good description or maybe links to good articles about such simulation for 3D game? |
6 | Should I used Box2D for a Flash platformer or use something for gaming like Fixel or Flashpunk? I'm trying to make a platformer with Flash AS3 and have been looking for something to help with some of the collision etc. I've look at a few engines and Box2D WCK seems the most sophisticated. Do I need that level of sophistication or should I just stick to something simple like Fixel or Flashpunk? OR should I just do everything myself? |
6 | How do I set the size of a single 'unit' in my game? I'm currently trying to remake port an old game created on Unreal Engine 2.5 to my own engine, and I have access to its physics data. It's using a scale of 80 units per meter, or 1 unit 1.25cm. The walk speed value for example is 5, and physics is simulated at 60 FPS, so the walking speed I need to implement would be 3.75 meters per second. But I don't exactly know what the size of a game engine's quot unit quot actually means. I of course want my own engine (I'm using C , OpenGL, and GLM) to use this same scale, but I'm not sure how to go about that. I'd assume this affects not only physics movement code, but the scale of models and maps I load in as well, so it's important to make sure it's the same as in the original game. How would I implement this? What parts of a game does the size of a 'unit' affect and how? Just the physics and movement calculations, or the graphics side as well (matrices, clipping space, FOV, etc.)? (I'm not sure if I'm overthinking things) |
6 | Fixed timestep game loop, why interpolation This is a very standard way of doing a fixed timestep game loop, where you just accumulate time from the previous frame and consume it in discrete steps with the physics engine while ( accumulator gt dt ) previousState currentState integrate( currentState, t, dt ) t dt accumulator dt A lot of articles suggest that with the residual lag we should do an interpolation between the previous update and the current one, BUT it does not make any sense to me! If you have residual lag it means that you still have some time to catch and you should EXTRAPOLATE the current state. Why would you ever do an interpolation with the previous state? |
6 | Rigidbodies gaining speed when they shouldn't I'm trying to get the effect of a constant magnetic field on a charged particle. A really important aspect of this is that the magnetic field doesn't do any work on the particle, which in this case means that it doesn't make it any faster or slower, just changes its direction. On paper, this works because the equation for magnetic force on a charged particle is q VxB, or the cross product of the velocity of the particle and the magnetic field times the charge of the particle, which makes the force always perpendicular to the velocity. The code I wrote for this is this forces charge Vector3.Cross(rb.velocity, cons.constantMagneticField) If the particle is the only thing that exists, and it has some initial velocity, and the magnetic field is perpendicular to that velocity, then the particle should ideally move in a circle of constant radius, because the magnetic force will always be perpendicular to the velocity. With what I have now, my particle moves in a tightish spiral, gaining speed way faster than I'd expect it to, and at a rate that scales with the particle's velocity. Is there a way to compensate for this? If not, is there a another way to get the behavior I want? |
6 | How to make a moving platform in Godot not be affected by collisions? I am trying to make a moving platform in Godot (for a 2D platform game, but I suspect the issue would be similar in 3D). Basically, both my player and my platform are KinematicBody2D, and they move via the move and slide() method. The documentation says You can use this to make moving or rotating platforms, or to make nodes push other nodes. This seems to fit my use case. However, when the player collides with the platform, the latter will be affected. For example, if the player stands on top of the platform, it will slowly start going down. I don't want that, I want the platform to move in a fixed fashion no matter what is throw at it (and if the player stands in the path of the platform for example, the player should be pushed). How can I solve this? I was thinking about using a StaticBody2D for the platform, but the documentation says A StaticBody2D is a body that is not intended to move. So I am not sure if this is the correct solution. It seems that the move and slide() method has some additional parameters, such as infinite inertia, but the documentation is not very clear to me as to what they do exactly. |
6 | Maximum range of projectile fired at given force and elevation I've gone over this again and again, and my result is obviously wrong when viewed in action. Here's the initial formula I converted (first one) http en.wikipedia.org wiki Range of a projectile and here's my C code float CalculateMaximumRange() float g Physics.gravity.y float y origin.position.y float v projectileSpeed float a 45 float vSin v Mathf.Sin(a) float vCos v Mathf.Cos(a) float sqrt Mathf.Sqrt(vSin vSin 2 g y) return Mathf.Abs((vCos g) (vSin sqrt)) Does anyone see what I did wrong? |
6 | how to calculate initial Y velocity required to reach target? I am trying to calculate the y velocity necessary for my player character to jump up and reach a y position within 1 second. Given that my game engine is at 60fps, I am doing velY (targetY playerY) 60 .. However, I need to account for gravity which is being applied to the character on every update, so I am doing velY ((targetY playerY) 60) (gravity 60) This results in the player character always jumping significantly higher than expect. UPDATE Attempting to try the Equations of Motion approach, I am setting a timestamp when the player character should begin moving to the target position... So then in my update loop, I am calling a function with currentTime timestamp. update function(paceFactor) paceFactor in this game engine is how many nominal 60FPS game ticks have elapsed. So if the game is running at 30FPS, then paceFactor will be 2.0, if it's 60FPS, then 1.0 will be passed in. this.timer paceFactor (1 60) if (this.setVelocityAt) this.setVelocityFor(this.timer this.setVelocityAt, this.targetPoint) this.position.x this.vel.x this.speed paceFactor this.position.y this.vel.y this.speed paceFactor this.position.y (gravity (paceFactor paceFactor) 0.5) this.vel.y gravity paceFactor , setVelocityFor function(time, target) if (time gt 1) time 1 this.setVelocityAt undefined this.character.vel.x (target.x this.character.position.x) time this.character.vel.y (target.y (0.5 GRAVITY time time) this.character.position.y) time , Then later the position and gravity is applied to the character as described in the previous update. However, the velocity being set is a huge number which is... wrong. |
6 | Help interpreting the physics of a rolling ball I'm using this article for reference. I understand handling the collision aspect, but I can't figure out how to calculate the new velocity once the ball collides with the ramp. Without it the ball just slides down the slope and stops at the bottom, with no horizontal velocity generated from the descent. The equation mentioned is tangentialVelocity velocity (velocity normal)normal Which I've tried as ball.velocityX magnitude ( magnitude normalX) normalX ball.velocityY magnitude ( magnitude normalY) normalY to no avail. Here is what I've done so far, which finds how far the ball is intersecting in the ramp and moves it outside. var distance int FP.distance(circleWorld.x, circleWorld.y, ball.x, ball.y) var penetration int distance ball.radius worldRadius if ( penetration gt 0) var componentX int circleWorld.x ball.x var componentY int circleWorld.y ball.y var normalX Number componentX distance var normalY Number componentY distance ball.x normalX penetration ball.y normalY penetration |
6 | How to control a spaceship near a planet in Unity3D? Right now I have spaceship orbiting a small planet. I'm trying to make an effective control system for that spaceship, but it always end up spinning out of control. After spinning the ship to change direction, the thrusters thrust the wrong way. Normal airplane controls don't work, since the ship is able to leave the atmosphere and go to other planets, in the journey going "upside down". Could someone please enlighten me on how to get thrusters to work the way they are supposed to? |
6 | Unity rigidbody exhibits a premature max speed In effort to build a racing simulator, I have been working on a working model for the pistons in the engine, and have come to a bit of a stand still. I have gone through extensive testing, through which we have "dumbed down" our prototype, in efforts to localise the actual problem. We have a wheel, represented by a basic cylinder. I have added a second cylinder as a sort of knob, which allows us to run the system, and easily visualise its spin, using the following line Throughout various tests, a common observation is that the wheel does not appear to spin correctly. Using a collision plane to derive rotations per minute, we have determined that at a certain "thrust", the wheel reaches its maximum speed. Past a value of approximately 'thrust 5,000', the wheel will not increase its speed. At present, this gives us a rotation of approximately 60 rotations per minute. Ideally, we want to be able to reach the breaking point of about 10,0000. rigidbody.AddTorque(transform.up Time.deltaTime rotatioonSpeed, ForceMode.Acceleration) What causes the rigidbody to 'cap' its force? Everything is at default, as per various tutorials we have explored As far as we have looked, various values might have an impact, but not to the point where speed hits a maximum on its own merit. Incase it matters, a some extra information about the system We are not yet using conventional Unity measurements. While to scale, the pistons are quite larger then normal, with the cylinder housing the piston holding a length of approximately 2 meters. Once "thrust" exceeds the maximum allowance to impact on speed, the value appears to weigh on breaking force, instead. Prior to reaching maximum speed, the user needs to "push" on the opposite direction, to reverse the rotation. It can take a second or two before the wheel slows down, and reverses its direction. The further past this maximum we go, the quicker the engine will immediately move in the reverse direction. There is nothing else imparted on our model for this behaviour to take place. We are literally dealing with a wheel with a joiner pin on the side. As stated, tutorials we have viewed tend to suggest that the values in the rigidbody should not effect the behaviour, this early. That said, here are our values Mass 1 Drag 0 Angular Drag 0.05 Use Gravity False Is Kinematic False Interpolate None Collision Detection Discrete Constraints FreezeRotationYZ My best attempts to find a similar problem online ironically reaches a bunch of articles on users attempting to enforce a maximum speed. For best results within scope, we would hope to be able to reach infinite speeds, and separately work out whether the speed of our wheel would cause a major fault, in turn limiting the speed it would potentially reach in practice. Personally, I suspect that the size of the object would make a difference, as unity perceives it. Another member on my team argues that because the rigidbody uses relative values, size should not make a difference. Unfortunately, this is as far as we can get in localising the problem. |
6 | How to implement accurate frame rate independent physics? So, I have been working on a project for a while now and recently stumbled across a problem The common approach to frame rate independent physics is to either use a fixed update interval (ie. Unity) or just multiply each physical change with delta. So it would look something like this update(int delta) ... positionX velocityX delta ... And when acceleration is added, the velocity change is treated similar update(int delta) ... velocityX accelerationX delta ... This works fine for most use cases. In fact so fine, that I haven't noticed anything was off for months. But there is a problem with this logic, namely that the position will be slightly off for entirely different frame rates. This problem is negligible when working with small frame rate changes, but is entirely noticeable once the delta time is changing by bigger amounts. Say, FPS rate from 30 to 600. Now, in a normal game the FPS are just locked and even if the positions are off for a few frames by like 5 it doesn't matter because one doesn't notice it. But I manually multiply the delta with a factor to accomplish a certain effect, and the error is somewhat noticeable and game breaking. A small example to clarify what I mean There is a game object with start position posX 0 and a x Velocity of 10 and an horizontal acceleration of 0.1. After two frames, for 50FPS this would lead to (with an average delta) velocityX acceleration delta posX velocityX delta velocityX 0.1 20 velocityX 12 posX 12 20 posX 240 next frame velocityX 0.1 20 velocityX 14 posX 14 20 posX 520 (240 280) After one frame with 25FPS, which equals the same time interval like two frames with 50FPS, this would get us velocityX 0.1 40 velocityX 14 posX 14 40 posX 560 So two situations with the same time interval elapsed we get different results (520 for 50FPS and 560 for 25FPS). Now, the problem obviously is that there is one extra frame (in this example, it could be any number of frames but the results still differ for the same interval) in which the acceleration is applied and therefore you get further with less FPS. Stabilizing the delta is not an option as I need different deltas for said effect, so I need to physics to be entirely independent there. Has anyone ever come across a similar situation and are there any solutions for it? |
6 | Ragdoll on alive creatures has somebody already implemented it? I find that a dead creature falling realistically is boring. I wonder, has any game implemented an animation system where the model moves depending of the muscle forces and the velocity of the limbs, but calculated ingame ? It is much faster to have determinate animation data which is loaded and is just read sequentially, but it looks much "static". Since I hear a lot about procedural generated data, one could generate a body with its own animation depending of the weight of the bones. I'm not talking about a real life robot simulation where the bone is standing, auto adjusting some angles to keep balance, but something more intermediate and more pre calculated. The forces vary slightly between steps (some random on a float so vary plus or minus 10 ), so the trajectory of the limbsvary between steps. It would require a lot of adjustement and preconfiguration, but it would look much less deterministic. |
6 | How can I add an impulse to specific rigid bodies at rest? Scenario Rocks falling down a rocky slope, with a flat surface at the bottom. When they land on the surface, the rocks move slightly before coming to a rest. GLESDebugDraw shows the bright orange outline turning to a slightly darker orange once a rock comes to a rest, until the rock is agitated by another falling rock. Question I would like to add an impulse to the rock once it reaches the rest state. How would I implement that? |
6 | Understanding Fixed time step From what I understand about time based Euler Integration is that you will set a number of pixels you want your object to move in the space of second and then the value will be regulated based on the frame rate of the machine your running the game on. What I'm having issue with is this You will set your acceleration acceleration 30 Then that acceleration will be added to the velocity and multiplied by the time which would be say 0.0166667 if the frame rate is 60fps which will cut down the velocity to the appropriate number for that frame which would be 0.50001 velocity acceleration dt but then when you add the velocity to the position it yet again multiplies the result by 0.0166667 which leaves you with 0.0833366667 position velocity dt What I'm trying to get is that instead of the 30 pixels per second I initially intended for the character to move I will need to put in an acceleration value of 1800. I was wondering why this is done instead of simply multiplying the acceleration by the dt and leaving it at that ? |
6 | Why is RK4 better than Euler integration? At the end of these great slides, the author compares all the different integrators presented. One way or another, they all fall short except for Improved Euler Integration and Runge Kutta 4 Integration, which both pass all tests. I suppose I should mention that I am working on a 2D game that isn't very physics intensive. I'm just curious as to where Improved Euler Integration would fall short and RK4 would have to be used instead. My game consists mostly of simple gravity (jumping and falling), movement along the X and Y axes, and bounding box collision. Is it worthwhile to implement RK4 or would Improved Euler be sufficient? I see many discussions where Euler Integration's users are chastised, but from what I can see, Improved Euler is quivalent in simple 2D matters. I imagine it'd also be faster. |
6 | Is it possible to have vehicles with physics like GTA in an MMO game? I haven't seen any MMO games with vehicles with realistic physics and that could achieve high speed, why? Is it because of network bandwidth limitations? Second Life has vehicles, but physics are poor and max speed is pathetic. |
6 | How can I adjust the speed my character jumps at? I've applied this method How to make a character jump?, like let wallForce 0 const targetVx gravity 4.0 const updatePos delta gt const dt delta 0.01 const oldY hero.y hero.vy wallForce dt hero.vy gravity dt hero.x hero.vx dt hero.y hero.vy dt updateCollisionsBetween(oldY, hero.y) hero.vx (targetVx hero.vx) dt wallForce 0 and on jump let doubleJump 0 const jump delta gt wallForce 0 hero.vy hero.jumpVy if (doubleJump 1) hero.vx 2 I want to speed up the jumps, that is I want the hero to jump and land faster. If I give a higher negative velocity on the jump (eg. hero.vy hero.jumpVy 2.0), then the hero jumps higher but its speed doesn't change. |
6 | Where should the collision response resolution code go? I've got a collision response resolution function that does the same for any pair of two entities. It's is in the World class right now. But right before that function is invoked, I have some entity specific logic A specific pair of entities should never have their collisions resolved (this is literally to keep the player from hitting itself with a carried object) When two specific entities collide, an event should be triggered Because of this, I'm starting to wonder if I should move the collision resolution function as a method into Entity, that'd allow me to use polymorphism. However, this sound very messy to me If both entities involved in a collision can resolve it, how can I figure out which one should do it? Is there another way to move these special cases out of World? |
6 | Ideas for 2D Water Simulation I am looking for any input on simulating water in 2D, against a rather large (call it) blocked not blocked array (viewed from the side). I have come up with the following ideas Cell Automata Do a massively parralel simulation on the CPU, using cell automata. With rules as simple as If there is a cell open to the bottom move to it. Check the left and right cells, choose a random one out of the two and move to it. Pros Simple to implement. Meaningful deterministic in a multiplayer system. Cons Probably really slow. Not convincing. Fluid Dynamics on the GPU Perform a rough approximation of fluid dynamics on the GPU against a texture like the following R G B A vX vY NULL Density Pros Probably really fast. Could be quite convincing. A further pixel shader could render it directly. Cons Difficult to implement. Difficult to tweak. I can't allocate a single texture the size of my level. I could overlap the grid areas, but this would add further complexity. Particles Use particles to simulate the water. During rendering using additive blending and then apply a multiplication function to the alpha channel to give the water crisp edges. Pros Will probably look nice. Easy to implement. Easy to render. Meaningful in a multiplayer system, although would require quite a bit of bandwidth to transfer. Cons Inter particle effects will probably be slow (neighborhood lookup). Could lead to water 'leaking' through solid spaces (because the solid space is small, e.g. 1px). Could lead to strange holes in the water depending on the particle size. Both of the above could be mitigated by allowing particles to drift closer together than their real size, however would cause problems with the inter particle and particle landscape performance. Any further ideas? Note This is an approximation, I am not looking for physically correct water here just something that 'is good enough' (bonus points for quick and dirty). The game is multiplayer, so unfortunately the whole level needs to be simulated continuously. |
6 | (Fat) ray cast with MPR OR GJK? I know that it's possible to see if a line segment or a swept shape (to make a "fat" line segment) intersects objects using MPR and GJK. Is it possible in those situations to find out the distance down the ray cast that the collision occurred? Thanks!! |
6 | How to handle player input with fixed rate variable fps time step? I've made a system which uses the ideas from "Fix your Time Step" in order update physics. I'm having trouble finding standard methods for dealing with this when user input affects player movement outside of a time step. If we want to integrate player movement within the "fixed time step, variable fps" system, I guess I would have to queue up player actions somehow, when accumulation hasn't yet completed. But then how do I integrate several different player actions within said timestep? IE lets say within timestep of N milliseconds, the player executes a move forward, move right and move backwards, where there is an infinite collidable wall in front. I could always calculate the last input, but in this case, it wouldn't be correct to do so. The player actually should be blocked by the wall, and then moving right and back would move them to the right, and back, to the right of where only processing the last input would lead. Similarly, if all movement was accounted for together, it might result in a player having an impossible vector for the final position, but if all moves were taken independently, there might have been a valid path (ie around a corner). If I process all inputs then the player made during the time step, it could conceivably be costly if they made a million tiny movements (collision check at each movement), though with exact physics (as far as a fixed time step simulation is concerned). Even if we thought the last bullet wasn't that bad, as soon as you add multiple players to the equation, it starts looking really bad, especially with a server. Are my only options to process all actions or only process a subset of them? |
6 | AS3 Flash Develop Radial Gravity (character on planet simulation) I am trying to create a program where a character shape will be constantly drawn towards the centre of a planet shape. I have taken on previous advice into using physics equations to generate the desired effect yet I think I am missing some and therefore it does not work (I am only using v 2 u 2 2as). Am I over complicating things? All I need is for the player object to be constantly drawn towards the centre of the planet object there will be no need for other planet objects to come into play and affect the player's gravity. edit To clarify, my question should have been "where did I go wrong?". I have now since solved the problem with the answers posted below, which were present because I wasn't going about trying to achieve what I wanted the right way. I didn't calculate the actual direction to move in as expected, and so the character could not move in the expected direction. Here is my Main.as package import flash.display.InteractiveObject import flash.display.Sprite import flash.events.Event import Math import flash.display.Bitmap import flash.display.DisplayObject import flash.events.KeyboardEvent import flash.text.TextField import flash.text.TextFormat import flash.utils. ... author Me public class Main extends Sprite public var planet1 Planet public var character1 Character public var initialXVelocity Number 0 public var initialYVelocity Number 0 public var finalXVelocity Number public var finalYVelocity Number public const gravitationalAcceleration Number 3 public var xDistance Number public var yDistance Number public function Main() if (stage) init() else addEventListener(Event.ADDED TO STAGE, init) private function init(e Event null) void removeEventListener(Event.ADDED TO STAGE, init) entry point planet1 new Planet character1 new Character place entites in position to test note planet 1 is 100 100 pixels, character 1 is 10 10 pixels planet1.x 350 planet1.y 250 character1.y 100 295 character1.x 396 395 addChild(planet1) addChild(character1) Make sure character has gravity applied constantly setInterval(playerMove, 1000) public function playerMove() void Calculate the distance between the character and the planet in terms of x and y coordinate xDistance (character1.x 5) (planet1.x 50) yDistance (character1.y 5) (planet1.y 50) Make sure this distance is a positive value if (xDistance lt 0) xDistance xDistance if (yDistance lt 0) yDistance yDistance Calculate velocity using physics equation v 2 (u 2) 2as finalXVelocity Math.sqrt((initialXVelocity initialXVelocity) (2 gravitationalAcceleration) xDistance) finalYVelocity Math.sqrt((initialYVelocity initialYVelocity) (2 gravitationalAcceleration) yDistance) trace(initialXVelocity) trace(gravitationalAcceleration) trace(xDistance) trace(finalXVelocity) trace(initialYVelocity) trace(gravitationalAcceleration) trace(yDistance) trace(finalYVelocity) Make sure the character is moving towards the centre of the planet at all times by reversing the appropriate velocity once it passes the axis of the centre of the planet if (planet1.x lt character1.x) finalXVelocity finalXVelocity if (planet1.y lt character1.y) finalYVelocity finalYVelocity Update the current velocity before new velocity is calculated initialXVelocity finalXVelocity initialYVelocity finalYVelocity Send the character into the correct direction character1.x finalXVelocity character1.y finalYVelocity |
6 | Using Minimum Translation Vector in SAT algorithm I am working on a simple rigid body physics engine ,I've already implemented SAT algorithm for collision detection and everything works fine, Now i get to step to use MTV to calculate the distance which objects might move to, In my case the two objects are cubes ,Actually i am a little confused about the distance and how to use it Here is the two cubes Both of them are on the same y axis and z axis, Only differs in x axis I am calculating MTV and i get samllest which refers to the smallest axis, So it looks like (x,y,z). overlapDistance which refers to the smallest overlap distance as a double variable. I know that overlapDistance is the distance that one of two cubes should move till no collision But how to use it , How cubes should respond to this distance ? Sorry if i am not clear, but for summary i know the smallest overlap distance but i don't know how to get use of it |
6 | How can I add an impulse to specific rigid bodies at rest? Scenario Rocks falling down a rocky slope, with a flat surface at the bottom. When they land on the surface, the rocks move slightly before coming to a rest. GLESDebugDraw shows the bright orange outline turning to a slightly darker orange once a rock comes to a rest, until the rock is agitated by another falling rock. Question I would like to add an impulse to the rock once it reaches the rest state. How would I implement that? |
6 | Friction due to gravity in an impulse based physics engine In my physics engine, I'm using impulses to solve collisions. I'm basing all calculations on these equations impulse desired velocity change mass impulse force time friction force lt normal force coefficient If an object moves along flat ground (infinite mass), after integration it'll be moving slowly "into" the ground due to gravity. This means that the impulse needed to react to that (given the restitution equals 0) will be the velocity in the direction of the contact normal, multiplied by mass. The issue here is that gravity is a constant acceleration, which means that the object, no matter the mass, will always "dip" by the same amount given a constant frame rate. So the mass is never a factor in this situation, outside of the impulse calculation, which is just a flat velocity change. Now, I can use impulse to calculate the force that was needed to react to the collision, this force can then be used in the friction equation as such friction impulse time lt normal impulse coefficient time Since time is always greater than 0, I can just multiply both sides by it, and then I can use the impulse equation, as such planar velocity change mass lt velocity change along normal mass coefficient And again, I can just remove mass from the equation, which leaves me with planar velocity change mass lt velocity change along normal mass coefficient This is the desired velocity change along the contact surface due to friction. The issue is, obviously, that none of this depends on mass, which means that no matter how heavy or light an object is, it'll always continue sliding along the surface by the same amount given a constant initial velocity. What am I missing? It really looks like there's a logical mistake here. Should the dynamic friction depend on the mass in the first place? Moving a heavy object requires higher force, so static friction should be modeled properly, since it just flat out removes velocity, though it'd be nice to hear if this has merit or just "looks good". |
6 | How to make character gain acceleration? I want to create more realistic physics for my 2D games. Currently, the character and the other game objects in my games start moving instantly (achieve maximum speed instantly) and stop instantly (achieve 0 speed instantly). There is no transition between speed levels resting and moving, moving and resting. I heard about 'steering behaviors', but am pretty sure they're mostly for designing AI agents' movements. Should I learn steering behaviors to make more realistic character movements in general? (In the physics aspect). Is this the way to go? If the answer is 'yes', could you recommend a good source to learn them? |
6 | Why do people like realistic' physics and graphics in games? If games are all about fun, then why do people tend to like realistic physics and graphics are good for games? Can you cite your source? |
6 | Change sprite angle on sloping ground I have a problem here with GameMaker built in physics environment.My player is designed to be on a skateboard. I want my player to rotate its sprite, according to the kind of fixture(up or down slopes) he is moving on.I've tried everything i could and everything i could find, but it didn't help me much, because the object is rotating in a very strange way.I enabled some flags to see the mask. Also, I've been studying vector algebra and i know it the angle between vector x speed and vector y speed should be the direction. Please help. Here's what i have so far 1 object which is the player Information about object obj Player Sprite sprite7 Solid false Visible true Depth 0 Persistent false Parent obj Static Parent Children Mask Physics Start Awake true Is Kinematic false Is Sensor false Density 0.5 Restitution 0.1 Group 0 Linear Damping 0 Angular Damping 0 Friction 0.2 Shape Polygon Points (76, 52) (76, 60) (0, 56) (0, 52) Create Event execute code Initialize the tires var half sprite width 2 var halfy sprite height 2 var tire instance create(x half 12,y halfy,obj Wheel) physics joint revolute create(id,tire,tire.x,tire.y,0,0,0,0,0,0,false) var tire instance create(x half 12,y halfy,obj Wheel) physics joint revolute create(id,tire,tire.x,tire.y,0,0,0,0,0,0,false) Step Event execute code Code facing point direction(0, 0, phy speed x, phy speed y) phy fixed rotation true phy rotation facing Move him if(keyboard check(vk space)) physics apply impulse(x,y,0, 100) if mouse check button(mb left) phy position x mouse x phy position y mouse y Information about object obj Wheel Sprite spr Wheel Solid false Visible true Depth 0 Persistent false Parent obj Static Parent Children Mask Physics Start Awake true Is Kinematic false Is Sensor false Density 0.05 Restitution 0.1 Group 0 Linear Damping 0.1 Angular Damping 0.1 Friction 30 Shape Circle Points (8, 8) (8, 8) Create Event execute code Keyboard Event for Key execute code physics apply torque( 100) Keyboard Event for Key execute code physics apply torque(100) And here is the result http i.stack.imgur.com sn1qh.gif |
6 | How to account for speed of the vehicle when shooting shells from it? I'm developing a simple 3D ship game using libgdx and bullet. When a user taps the mouse I create a new shell object and send it in the direction of the mouse click. However, if the user has tapped the mouse in the direction where the ship is currently moving, the ship catches up to the shells very quickly and can sometimes even get hit by them simply because the speed of shells and the ship are quite comparable. I think I need to account for ship speed when generating the initial impulse for the shells, and I tried doing that (see "new line added"), but I cannot figure out if what I'm doing is the proper way and if yes, how to calculate the correct coefficient. public void createShell(Vector3 origin, Vector3 direction, Vector3 platformVelocity, float velocity) long shellId System.currentTimeMillis() hack ShellState state getState().createShellState(shellId, origin.x, origin.y, origin.z) ShellEntity entity EntityFactory.getInstance().createShellEntity(shellId, state) add(entity) entity.getBody().applyCentralImpulse(platformVelocity.mul(velocity 0.02f)) new line added, to compensate for the moving platform, no idea how to calculate proper coefficient entity.getBody().applyCentralImpulse(direction.nor().mul(velocity)) private final Vector3 v3 new Vector3() public void shootGun(Vector3 direction) Vector3 shipVelocity world.getShipEntities().get(id).getBody().getLinearVelocity() world.getState().getShipStates().get(id).transform.getTranslation(v3) current location of our ship v3.add(direction.nor().mul(10.0f)) hack this is to avoid shell immediately impacting the ship that it got shot out from world.createShell(v3, direction, shipVelocity, 500) Edit I switched to v3.set(direction) v3.nor().mul(velocity) if (platformVelocity ! null) v3.add(platformVelocity) entity.getBody().setLinearVelocity(v3) And it seems to work (so adding the velocities and setting them on the body). However, I'm not sure what the drawbacks are and why the tutorial application used impulses instead of setting velocities. I also think that while this is physically correct it leads to strange results (gun range is two times further when shooting forward than when shooting sideways). The root cause is because really the shells are indeed too slow, but I like them slow as otherwise the gameplay is too fast paced, and they travel too far. I think I need some compromise between physics realistic and ignore platform velocity. |
6 | Are you supposed to be looping through all PhysicsObjects at every step in a physics engine? I am currently making a small 2D game and I am trying to implement some basic 2D physics. I currently have a list of around 100 PhysicsObjects which I loop through every frame in order to update and apply forces to that object based on user input. The basic code is as follows accumulator 0 dt 0.01 while running for each object in PhysicsObjects update object accumulator time between last frame and current frame while accumulator gt dt for each object in PhysicsObjects resolve forces to get new position of object based on dt accumulator dt for each object in PhysicsObjects render the object I was going to resolve the forces and calculate the new position in the update method of each object, but I was told the dt was necessary in order to make the movement and physics independent of frame rate, which is why it is in a separate loop. I also can't update the objects in the physics engine loop as the update method needs to occur every frame. This already seems incredibly inefficient, and I haven't even started to test for collisions or anything else more in the physics engine. Is there a better way to structure this where I don't need to loop through every object again in order to calculate their new position? |
6 | Can I use physics in Isometric map based games? I am trying to use physics in my game which is an isometric map based strategy game that the player deals with a city full of buildings, roads and people in it. I am writing the game with Swift and SpriteKit technology. (the following picture shows a snapshot of my game) MY GAME I like to use Spritekit's physics library so I would be able to simulate car accidents and preventing them to go throw the buildings and other kind of stuff that physics could provide. I am familiar with Physics and I have enough experience with Bullet and I can write a 3D game using OpenGL ES and physics, but I haven't really used physics in 2D isometric map games. I have also wrote a 2d physic game that was really 2d (an endless runner) which was actually a sample of a book but as you can see in the following picture the gravity vector is the Y axis and every thing is pretty easy. Here is the gravity vector that is used to create the game at the following picture. self.physicsWorld.gravity CGVectorMake(0, 9.8) Someone Elses Game, Book Sample Book Name iOS 7 Game Development Author Dmitry Volevodz You may find the book Here However, in an isometric map game you can't just set and assign the Y axis as a gravity vector. since the method which sets the gravity vector accepts two arguments it is a big hope that I can use physics in my isometric map games. For example something like this I Say!!! As I am still using a cartesian coordinate system (perpendicular axis) X and Y axis make a 90 degree angle and if I need to project the gravity quantity over the X and Y axis it would be gCos(45),gSin(45) I haven't tested it yet. self.physicsWorld.gravity CGVectorMake( 9.8 0.707, 9.8 0.707) May you please help me on setting the gravity vector and how should I define the moving objects like cars and humans and the static ones like buildings any other tips on modelling physics in isometric map are also welcome and appreciated. The main question is is it really possible to use physics in an isometric map based games? |
6 | Bullet Physics Scaling rotational part of 6DoF Spring Damper I am currently trying to scale up my setup (consisting of two rigid bodies connected by a btGeneric6DofSpring2Constraint) to fall within the suggested dimensions for a concise simulation. In order to do so, I followed to the provided Wiki http www.bulletphysics.org mediawiki 1.5.8 index.php?title Scaling The World. I scaled all the linear properties and concerning the resulting forces, everything turned out physically consistent. Note that I did not scale up the liner and angular stiffness and damping values. However I encountered significant deviations concerning the spring related torques resulting due to a angular spring offset. I guess that this issue arises due to the fact that the torques should be scaled ( scale 2) as well. However I do not see a way of scaling the internal torque representation of the btGeneric6DofSpring2Constraint. Should i simply scale up the angular spring stiffness and spring damping by a factor ( scale 2) or is there a better more elegant way to retrieve physically consistent results (forces, torques, motion) when trying to scale a world containing the btGeneric6DofSpring2Constraint? EDIT I was able to boil it down to the following The rotational stiffness and damping vales are chosen independent from the scale. The stiffness itself does not alter the behavior of the system. The deviations are caused entirely by the damping part. An experiment with altering the scale and non existent damping showed results independent from the scaling factor, just as desired (K stiff 20.0, K damp 0.0) . However when repeating the same experiment with no stiffness and a positive damping factor, significant differences arise when scaling up. (K stiff 0.0, K damp 9.0) The image denotes the system responses for different scales. I found the corresponding code snippet in btScalar fs ks error dt btScalar fd kd (vel) (rotational ? 1 1) dt btScalar f (fs fd) info gt m constraintError srow (vel f (rotational ? 1 1)) btScalar minf f lt fd ? f fd btScalar maxf f lt fd ? fd f printf(" .3lf n",f) if(!rotational) info gt m lowerLimit srow minf gt 0 ? 0 minf info gt m upperLimit srow maxf lt 0 ? 0 maxf else info gt m lowerLimit srow maxf gt 0 ? 0 maxf info gt m upperLimit srow minf lt 0 ? 0 minf info gt cfm srow cfm srow info gt rowskip count Interestingly, the scaling works just fine if the if clause is commented out. Any sugestions why this happens? |
6 | Aircraft trajectory prediction I have an aircraft that is controlled by player and i need to predict it's position at needed time. It's not a problem if the plane is just moving straight but most of the time aircraft is maneuring. So i came up with an aproximation that aircraft movement can be described as a helix. So i have a point A and linear velocity V 1 that aircraft had at a time of t 1. Point B and linear velocity V 2 that aircraft had at a time of t 2. In that approximation we may assume that V 1 equals V 2 so it will be a perfect helix. And i need to find a point C in that aircraft will be at a time of t 3. |
6 | Inertia in flight simulation using box2d I'm trying to simulate flight using box2d and libgdx. The main problem I am currently experiencing is with inertia since there is no air, the plane looks like it were drifting. I wasn't able how to turn off inertia. I have two ideas Imitate air resistance by applying force Imitate flight using linear velocity without using any box2d physics Are any of these two ways correct? Or maybe there is way to turn off inertia? |
6 | Friction using delta time returns inconsistent result Slowing down a character using the following formula returns different results depending on the frame rate this.y this.yVel delta this.yVel Math.pow(0.99, delta) Is there a better way to decelerate a player using delta time to allow for consistent movement across several framerates? |
6 | Why do physics engine use impulses to solve collisions? Usually, in most physics engines that are out there, the way that collisions are solved is by applying some impulse to both colliding bodies. While I understand that impulses are just force that is already integrated into time, and will result into velocity added at the end of the frame, why not simply project both bodies out of collision and removing their velocity component that is going towards the collision? I'm not really sure, but it really looks like classic platformers only stopped the character instead of adding impulse to it. Is this right? And if yes, why the added complexity of using impulses in modern engines? |
6 | Calculate gears rotation for a realtime simulation I'm trying to do a game with real time simulations of gears. There is a big Gear with inside a smaller gear. I managed to draw gears with different diameters but equal size teeth, but if i try to move the smaller one inside the bigger one the movement is odd. See the animated gif The biggest gear is in center C1 and the small in the center C2. I calculate C2 position in this way C2.x C1.x C1 RADIUS C2 RADIUS) cos(t) C2.y C1.y C1 RADIUS C2 RADIUS) sin(t) for t that goes from 0 to TWO PI in n steps. I apply as rotation the angle t, but maybe it is wrong and i have to calculate another rotation for get a perfect joint. EDIT I am using radians for rotations and I think this is OK. My main problem is that I want to achieve a perfect joint between teeth like this example. My teeth are overlapping in some odd way. EDIT a working example can be found here http www.openprocessing.org sketch 83665 |
6 | Is there any reasons to make sprites and bodies line up? So in LibGDX the Sprite objects position is where it's 0,0 mark is in the word. In Box2D a a bodies position is in it's center. So to line these up when you update the sprites position with the bodies position you would adjust it by half the width and height. But it seems to me theres no reason to worry about that. Because the relative position is always going to be the same, and that it'll just waste calculations lining it up. Is there any reason I should do it? |
6 | Radiometric quantities and time in rendering Often in papers people use various radiometric quantities, mostly radiant flux, radiant intensity, radiance and irradiance. It seems to me that all of these quantities are dependent on time. For example, radiant flux is defined as the amount of radiant energy per span of time (emitted by a light source). The other quantities contain radiant flux in some measure so they seem to depend on time as well. Yet when reading papers, people don't go into time at all. For example, some papers say "the radiant flux diffusely reflected by this area of the surface is x" and then they go on to explain that x is just light colored intensity surface color or something (depending on the illumination model used, of course), not factoring in any kind of time at all. Is this because the time frames observed are assumed to be 1 second? Is the time factored out somewhere (perhaps when defining the light intensity, which may be defined as radiant flux)? What am I misunderstanding here? |
6 | Lunar lander why is my descent module crashing I've been reading this awesome simulation of the actual Apollo 17 descent http www.braeunig.us apollo LM descent.htm I've been trying to make my own simulation using Euler integration, with a time step of 100ms. The problem is my descent module is crashing during the first two minutes with a vertical speed of 220 m s. During the initial stage of the descent (braking), the lander is tilted 90 and almost all the thrust is spent in the horizontal component, with no force to counter gravity. In my simulation the vertical speed quickly builds up while the pitch is 80 90 , and then gravity does it job. Here's a trace t 0 s x 0 y 17234.6112 vx 1697.1264 m s vy 20.4216 m s ax 1.2995855485404475 m s2 ay 1.6121564579144938 m s2 pitch 90 throttle 0.1297 fuel 8874.2Kg t 10.015 s x 17062.974621379497 y 16948.14950433809 vx 1710.2669538608811 m s vy 36.64853435841286 m s ax 1.3247309786564347 m s2 ay 1.628484797082333 m s2 pitch 90 throttle 0.1297 fuel 8855.501190599978Kg t 20.019 s x 34239.89169813059 y 16498.912567960208 vx 1723.6514116543285 m s vy 53.026163503416676 m s ax 1.3509707026458686 m s2 ay 1.6456786784409965 m s2 pitch 90 throttle 0.1297 fuel 8836.82291908347Kg t 30.026 s x 51527.03405575163 y 15884.74450896862 vx 1725.5675762461628 m s vy 69.5834660661016 m s ax 0.9584923539027193 m s2 ay 1.663174744204344 m s2 pitch 90 throttle 1 fuel 8756.011226046036Kg t 40.041 s x 68759.3217349438 y 15103.315677459259 vx 1715.7571868391299 m s vy 86.32821281208818 m s ax 1.0003892381595199 m s2 ay 1.6806337716945954 m s2 pitch 90 throttle 1 fuel 8611.841531365935Kg t 50.502 s x 86651.75776002374 y 14107.047450672597 vx 1705.0564069549016 m s vy 104.00697912916615 m s ax 1.0452064683102156 m s2 ay 1.6991809596193168 m s2 pitch 90 throttle 1 fuel 8461.251498809865Kg t 134.865 s x 226365.92349700694 y 5.915270639694082 vx 1602.384872970266 m s vy 225.9485740506923 m s ax 1.382111636427434 m s2 ay 1.224439728661491 m s2 pitch 78 throttle 1 fuel 7246.814359289593Kg FINISHED at t 2.24775 minutes However, in the original simulation, vertical speed never exceeds 20 m s. I don't know how could this be possible, as there's no drag due to atmosphere. And I've coded initial acceleration and velocity values exactly as in this very same page. You can check the original trace here http www.braeunig.us apollo LM descent.pdf Here we can see the Moon's gravity is aprox. 1.5 m s which heavily influences ay in my simulation. However in the real descent trace it was kept to lower values ( 0.1) most of the time, even during the first minute when there was no vertical thrust due to the engine. I must be making very stupid mistakes but right now I can't see where. BTW this is how I update my vars in each step Calculate acceleration as a function of mass, velocity, thrust and gravity ax vx vx (y MOON MEAN RADIUS M) (thrust x mass) ay (vx vy (y MOON MEAN RADIUS M)) g (thrust y mass) This would be the acceleration for a flat moon. Don't work either. ax thrust x mass ay g (thrust y mass) Update velocity as a function of acceleration and time. vx vx ax dtSecs vy vy ay dtSecs Update position x x vx dtSecs y y vy dtSecs Any hint would be appreciated. Thanks in advance. |
6 | Leapfrog integration vs Euler integrator I am looking at various integration methods for my n body simulation and I'm slightly confused about actual implementation of leapfrog integration. According to the wikipedia page leapfrog method is defined like this When I imagine how to code it, i come up with something like this while true dt time since last frame for every object object.position object.velocity dt for every object acceleration object.calculate acceleration() object.velocity acceleration dt render() But this is Euler integration, right? So moving the initial velocity back by one half step makes a first order method into a second order method? But for me a small change of initial velocity is not important, it will be set as a random value anyway... Why I won't just use velocity verlet This is for a game where tens of thousands particles fly around affected by forces roughly resembling gravity. I'd like to keep amount of data stored in every partile as low as possible to improve cache locality, which is why I don't want to use a method that requires storing acceleration (and recalculating it would be too slow). |
6 | Orbits Combine the Pros of RK4, Symplectic Euler, and Verlet Velocity Integrator Recently, I've implemented and compared a number of basic integrators for my physics engine. The 3 that gave me the best results are RK4, Symplectic Euler, and Verlet Velocity, but I think I need something a little more advanced. I've done many Google and StackExchange searches but haven't found what I'm looking for. I'm looking for something that combines the strengths of those integrators without their weaknesses. I'm only concerned about orbital mechanics. Drag and other similar forces will not be put through the integrator because it's not important that I get perfect answers for those other forces, but (near) perfect answers are very important for my orbital mechanics. Computationally expensive algorithms (within reason) are not as much of a concern as accuracy is. My thoughts and primary concerns are as follows RK4 Pros Very accurate. RK4 Cons Loses energy over the long term. This sim needs to be able to run for a VERY long time, so experiencing this kind of "orbital decay" is quite undesirable. Symplectic Euler and Verlet Velocity Pros Symplectic Don't lose energy. Symplectic Euler and Verlet Velocity Cons Much less accurate. Highly eccentric orbits make this apparent very quickly...even with a simple massless satellite orbiting a massive object scenario, the satellite's orbit "rotates" around the parent object over longer periods of time. This is extremely undesirable behavior. For my purposes, I cannot resort to orbits "on rails". TLDR I am looking for an algorithm that gives me the accuracy of RK4 without the slow decay. Computational expense is not a major concern. Thanks in advance for the help! Update 1 I found a similar question here https stackoverflow.com questions 3680136 help with symplectic integrators There might be good answers in the accepted answer, but after several hours of study, I have only determined that they are very difficult to understand. I will keep studying the accepted answer's linked paper and source code and post an answer if I get results. However, I suspect that while the algorithm is not much more complicated than RK4, the symbology and style of the linked explanations source code are making it very difficult for anyone without a heavy math physics background to understand. Unfortunately, as a comment noted, the OP accepted that answer, but never came back and gave a clearer explanation himself. I'll leave this question open and keep studying myself. Hopefully, together we can come up with a clearer answer for future searchers! |
6 | Calculating collision of polygons Say I have a multitude of 2D polygons floating about on a plane. These polygons can have any side count and aren't necessarily regular. Assuming I know absolutely everything about the polygons (area, collision point, location, velocity, rotation, angular velocity... etc) how to I calculate what happens to two polygons after collision? I.e. what will their resultant velocities and angular velocities be after collision? If not an exact solution, what resources could help me learn how to accomplish this? |
6 | Implementing a motorized hinge joint I have a 2d physics engine, with three boxes "body", "left wing" and "right wing". The wing boxes are connected to the body using a hinge joint. The physics world has no gravity. I'm attempting to rotate the wings around their hinge connection, as if the joint is motorized but I'm not exactly sure how to achieve that. If I exert force with a downward vector on the center of the wings, the body itself flies down. This is undesirable. With an actual hinge motor, only the wings will rotate about the hinge, affecting the body only when they hit it. Which forces should be added to the wings, and at which origin points? I'm using Phaser.io, with P2.js physics, but the question is platform agnostic. |
6 | What is a simple deformer in which vertices deform linearly with control points? In my project I want to deform a complex mesh, using a simpler 'proxy' mesh. In effect, each vertex of the proxy collision mesh will be a control point bone, which should deform the vertices of the main mesh attached to it depending on weight, but where the weight is not dependant on the absolute distance from the control point but rather distance relative to the other affecting control points. The point of this is to preserve complex three dimensional features of the main mesh while using physics implementations which expect something far simpler, low resolution, single surface, etc. Therefore, the vertices must deform linearly with their respective weighted control points (i.e. no falloff fields or all the mesh features will end up collapsed) as if each vertex was linked to a point on the plane created by the attached control points and deformed with it. I have tried implementing the weight computation algorithm in this paper (page 4) but it is not working as expected and I am wondering if it is really the best way to do what I want. What is the simplest way to 'skin' an arbitrary mesh, to another arbitrary mesh? By skin I mean I need an algorithm to determine the best control points for a vertex, and their weights. |
6 | Box2d Body to follow mouse movement I am trying a box2d body to rotate following the mouse. Here's an image to clarify what I mean. The red and blue circles are current point of the mouse and the body (of corresponding color) moving rotating to follow it. Basically the rectangle should rotate with its one end pointed towards where the mouse pointer is. Here's my code so far, World world Body body, bullet Box2DDebugRenderer debugRenderer OrthographicCamera camera Override public void create() world new World(new Vector2(0, 0f), true) debugRenderer new Box2DDebugRenderer() float w Gdx.graphics.getWidth() float h Gdx.graphics.getHeight() BodyDef bodyDef new BodyDef() bodyDef.type BodyDef.BodyType.DynamicBody bodyDef.position.set(10, 10) body world.createBody(bodyDef) PolygonShape shape new PolygonShape() shape.setAsBox(2, 5) FixtureDef fixtureDef new FixtureDef() fixtureDef.shape shape fixtureDef.density 1f Fixture fixture body.createFixture(fixtureDef) shape.dispose() Gdx.input.setInputProcessor(this) camera new OrthographicCamera(200, 100 (h w)) camera.position.set(camera.viewportWidth 2f, camera.viewportHeight 2f, 0) camera.update() Override public void render() Gdx.gl.glClearColor(1, 1, 1, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) world.step(Gdx.graphics.getDeltaTime(), 6, 2) camera.update() debugRenderer.render(world, camera.combined) Override public boolean mouseMoved(int screenX, int screenY) int mouseX screenX int mouseY Gdx.graphics.getHeight() screenY float rotateAngle MathUtils.radiansToDegrees MathUtils.atan2((float) mouseY (float) body.getPosition().y, (float) mouseX (float) body.getPosition().x) body.setTransform(body.getPosition(), rotateAngle 57.2957795f) return true And here's a gif of how it appears now. as you can see the body gets skewed and also doesn't rotate properly. What am I missing? |
6 | What are the advantages of having a real time based physics? Possible Duplicate Fixed time step vs Variable time step Now just let me clarify what I mean by "real time based physics", which I will call RTBP from now on. Well, basically, it implies taking, you guessed it, actual time into calculations. For example timePassed time lastTime positionx vx timePassed positiony vy timePassed lastTime time This would be a simple RTBP model. What's the alternative? I call it "step based physics" (SBP from now on), which would just be this positionx vx v in SBP is obviously smaller than in RTBP positiony vy I currently use SBP, but I see that many people actually include time in their calculations. Why is that? I of course limit the update time to 1000 60ms. Once the update interval is limited, both models would behave the same. The only difference is when the FPS drops. I believe that here is where PBS excels over RTBP. In PBS the game would, yes, run slower, but would always produce the same results! In RTBP, the position might increase so much that an object actually passes through a wall! Anyway, there must be something that I'm missing. |
6 | Box2d topdown racing game killing "residual" forces I'm making top down race game in GM S with Box2D, the car is controled in unusual way player sets direction and engine's speed, and the car uses them turns to the desired direction and reaches speed. But the question is about the "residual" speed after the turn. Here is what I mean I make rotation by applying torque and move with applying force. I don't have tyres, it's just one plain object. So how can I get rid of this momentum? I'm working in GM S, but I'd like to hear any solution, I can adapt it easily. Movement code var ad angle difference(phy rotation, desiredDir) physics apply torque((angleTorque) sign(ad)) rotate the car dx lengthdir x(spd, phy rotation) dy lengthdir y(spd, phy rotation) physics apply force(phy position x, phy position y, dx, dy) move the car |
6 | How do you convert angle with velocity to x velocity and y velocity? This question can be simplified to If you lean a pencil of a certain length at a certain angle what is the x and y position of the tip? So, basically, I am making a game that plots a balls path through the air as it travels. I want the user to enter an angle and velocity to launch a ball at and get the program to convert that to an x and y velocity so that it can work out how to plot the balls movement across the screen. The x velocity doesn't change through the simulation but the y velocity will decrease constantly until the ball touches the ground again. This is why I referenced to a pencil because it relates to turtle graphics calculations. |
6 | How to convert strict limit in position into gradual slow down? The player moves a spell object, the spell must stay withing a certain range of the player. The spell is moved using a physics system and it has mass and velocity. Currently when the spell goes out of range of the player it's being moved back into range, this has the effect stopping the spell abruptly at the edge. I want to smooth out this abrupt stop so that it gradually slows down. I tried to apply an easing function but because the time and distance change every frame I couldn't figure out the formula. Is there some sort of physics or easing formula I can use to gradually slow down the spell before it gets to the edge of its range, while at the same time guaranteeing that it never leaves the range? Additional Info The spells range is a circle. I only care about the center of the spell object. Movement forces are continually being applied to the spell. |
6 | Objects are stumbling in place continuously. How to fix that? I have a nasty problem with my physics engine. Objects sometimes just jump in place, or roll left and right. Main game loop works in that manner Every living object is updated (it changes velocity, the logic is different for each object) Engine computes collisions using objects' positions and velocities and resolves them. Imagine that we have a grenade positioned at one pixel above ground, with zero speed, and the gravity is 1 px tick 2. Normal bounce coefficient is 0.5, so an object will bounce with half speed. According to the algorithm Object's controller adds gravity to its velocity, so now v 1. Engine moves object to y 0, no collisions happen. Velocity is changed to 2 by the controller. Engine tries to move the object, the collision happens immediately, v is set to 1, and object moves to y 1. Velocity is changed to 0 by the controller. The object remains in place. Initial conditions has reproduced. The object will bounce forever with a period of 3 ticks. These situations vary, but they all are caused by discrete nature of the engine described above. This bug was in every version of my game. Objects may vary in shape and size, and the terrain is destructible Worms like. I use my own engine that uses swept collision detection customized to work with small and fast objects, never letting them go through impassable object unless they were spawned inside, and the only acceptable option for me is to modify it. One thing that I have in mind that I can detect if object had very low speed for some time, make it "immobile" and call different controller functions depending on "immobile" flag. It's an ugly solution though, because the complexity of my logic will increase. Also, when a round object stands on two points and we remove one, it will not fall. So this approach is wrong at all I guess. What is the right approach to fix that? |
6 | Verlet collision with impulse preservation I came across this article, recently, that presented a technique for impulse preservation with position based verlet integration. What was interesting was that the integration steps are seemingly done differently from typical position based verlet schemes, as well as the ordering of the integration step and collision resolutions. Specifically, the typical verlet position integrator is newPosition 2 position oldPosition acceleration timeStepSquared oldPosition position position newPosition DoConstraints() Where the article has position acceleration timeStepSquared DoConstraints() newPosition position 2 oldPosition oldPosition position position newPosition Which ignoring constraints for a moment works out to be newPosition 2 position oldPosition 2 acceleration timeStepSquared oldPosition position acceleration timeStepSquared position newPosition Which is different in a term of acceleration timeStepSquared. I haven't quite convinced myself that those terms cancel out through the iteration, as the prior acceleration timeStepSquared term may not be the same as the current one. Could someone explain the reasoning for this, and if indeed it makes sense? |
6 | What to do after detecting OBB OBB intersection I'm using this code to detect intersections between two OBBs. The problem is that i don't know what to do after detecting it. I tried using a simple algorithm if (collision detected) move character back to its position on previous frame But this is not what i need, because the character is rotating and moving to certain points (usually to mouse click position). When it's close to an object with OBB and it rotates to a point, its OBB updates (the position of all OBBs corners is recalculated) and most of the time the updated OBB intersects with an object that is near, so the charecter gets stuck at its position. How can i deal with the rotation problem or what other methods can you offer for stoping character when its OBB itersects with another? |
6 | How to get the physics just right in a physics driven game I'm working on a physics driven game using a java port of Bullet (JBullet). In our game we have a ball that can have collisions with the other objects, including the objects that define the boundaries of the playing area. Since we consider collisions between the ball and other objects as a very important aspect of the gameplay we wish to handle those collisions in our own code. This allows us to get non realistic but very controllable behavior for the ball. The other gameobjects also collide with each other, but JBullet handles those collisions well and we have no issues there. The problem is that we have great difficulty triggering the custom behavior in the correct way. In our first set up called our custom collision handling code every time JBullet reported a collision for the ball. This caused undesired behavior as a single hit could trigger multiple reported collisions. Which caused the ball to be sort of glued to the wall. Our "fix" for this was to have the ball keep a timer and to ignore subsequent collisions occurring within let say 0.1 second of another. However, this caused ball to bounce through walls in some cases, probably because the first reported collision isn't the one we expect, and the ball wall collision occurring shortly after is sadly ignored. So that brings me to my question. How does one sort this out without resorting to all sort of "fixes" that only make the problem more complicated and less predictable? Would for instance placing the ball at the last known position before the collision and handling the collision from there work? But what if another object has moved to that position in the mean time. Or maybe calculate future collisions with the ball for non moving objects and enforcing them if they are missed by the physics? Any feedback thoughts revelations would be greatly appreciated! |
6 | Where should the collision response resolution code go? I've got a collision response resolution function that does the same for any pair of two entities. It's is in the World class right now. But right before that function is invoked, I have some entity specific logic A specific pair of entities should never have their collisions resolved (this is literally to keep the player from hitting itself with a carried object) When two specific entities collide, an event should be triggered Because of this, I'm starting to wonder if I should move the collision resolution function as a method into Entity, that'd allow me to use polymorphism. However, this sound very messy to me If both entities involved in a collision can resolve it, how can I figure out which one should do it? Is there another way to move these special cases out of World? |
6 | How can I synchronize ocean waves over the network? I've been performing a little bit of research in my spare time on ways to increase the interactivity of environments in a networked game or simulation. One of my areas of research is fluid dynamics and whether it would be possible to synchronize it over the network. I believe the short answer to that is Yes of course you can. But there will obviously be trade offs as there are with any network synchronization problem. I was recently playing Battlefield 4 and a number of their maps have playable ocean areas with fully functional waves large enough to obscure entire boats during gameplay. It seems to work quite well as well. My assumption here is that the ocean simulation is completely offline and each client performs synchronization with the server during initialization. This would allow all clients to run the exact same ocean simulation that appears to be dynamic but is in fact the same offline simulation every time. Interaction with the ocean simulation appears to be only superficial with local splash wave depression. I assume that is entirely local to the client and not synchronized. My question here is Would the above be an appropriate way to synchronize fluid simulation over a networked game? If not, what would you suggest? |
6 | How can velocity be normalized after a collision if a projectile needs to maintain its height? I want a thrown disc to travel along the same height, even after collisions. The problem is, there's an edge case that I'm not sure how to deal with. The lowest tech solution would probably be to quickly interpolate the rotation of the disc so that it's flat, and also interpolate its height so that it never collides with another object in a way that would impact its height, but that might be a bit heavy handed. I worry that it would look really bad if you're holding the disc at an angle when releasing it for a throw, and it just suddenly "swooshes" flat mid flight. Would that seem janky? If I don't do that, and I simply retain the disc's rotation as it flies along its path, then it might collide with an object's edge in a way where the correct bounce angle would send it upwards or downwards, which I don't want. But if I simply hard code the y velocity to 0, then in those instances, the lateral velocity becomes very low. Should I just check for a "minimum" speed, and increase it to that if it falls below that? Because the issue is that in the case where it bounces upward, there's a good chance that the correct bounce angle, if the y velocity is ignored, results in the disc continuing in the same direction rather than bouncing. So I'm honestly leaning towards extending the collision boxes for these objects really far above and below where the disc could possibly be thrown, that way regardless of its orientation, it would always be the side of a cylinder colliding either with the side of a box or one of its vertical edges, and the velocity change should thus (hopefully) always look like it makes sense. |
6 | How do I figure out if a point is infront or behind my vehicle? I need to figure out whether a point is infront or behind my vehicle. I have the vector of it's position, forward direction. So far I have tried finding the vector perpendicular to its forward direction and then calculating what side of the line it is positioned on. This works fine at first. But then I realised it is only calculating around the origin. bool Car isInfront(ngl Vec2 pos) http stackoverflow.com questions 1243614 how do i calculate the normal vector of a line segment if we define dx x2 x1 and dy y2 y1, then the normals are ( dy, dx) and (dy, dx). create vector per to the direction of travel. ngl Vec2 fwdVec m carPhysics gt getForwardVec2() ngl Vec2 pos m carPhysics gt getPosVec2() ngl Vec2 dir pos fwdVec float dx dir.m x pos.m x float dy dir.m y pos.m y ngl Vec2 v1( dy, dx) ngl Vec2 v2(dy, dx) ngl Vec2 perp (v1) (v2) int turn getLeftOrRight( pos, perp) if(turn LEFT) return true else return false int Car getLeftOrRight(ngl Vec2 dir, ngl Vec2 fwd) http gamedev.stackexchange.com questions 34536 calculating angle between two vectors to steer towards a target cross product float val ( dir.m x fwd.m y) ( dir.m y fwd.m x) if(val gt 0) return LEFT else return RIGHT |
6 | Implementing proportional navigation in 3D Good afternoon guys, a N ' V is the formula for the commanded acceleration required to hit the target, where N is the proportionality constant, ' is the change in line of sight and V is the closing velocity. Data I natively have x,y,z position of both missile and target vx,vy,vz velocity vector of both missile and target x,y,z vector which points from missile to target and opposite This is set by me but still maximum speed of missile. Data I can get with some calculations Vertical angle between missile and target (and opposite) Horizontal angle between missile and target (and the other way around). That's the reference system of the game ' or the derivative with respect to time of the Line of Sight it's a concept I really didn't understand... its unit should be, in theory, Hz or (s 1) since m s 2 ' m s ' 1 s V should be pretty easy to calculate V v(missile) v(target) OR Vx (v(missile) v(target)) cos (x0y) Vy (v(missile) v(target)) sin (y0z) Vz (v(missile) v(target)) cos (y0z) N well it's a scalar number, usually 3. The computed acceleration will then be passed to a RK4 integrator which will move the interceptor towards its target. To steer the missile, I will simply change its velocity vector at every update (every 1 60th of a second) and its orientation accordingly. For example if the missile has a velocity of 0,100,0 , he's going 100 m s due y axis. If at the next frame it should slightly turn right, then he'll be going to have a velocity of 10,99,0 and so on. That's the only thing left to finish off my little thesis and unfortunately I'm stuck here. In the meantime, thank you very much! Here's a video I made, but it doesn't still actually use the Proportional Navigation law it checks if the missile is "aligned" to its target and eventually correct its route. That's my actual code pastebin That's what i've come up with but sadly doesn't work as expected params " n"," missile"," target" private " a" vm velocity missile rm getPosASLVisual missile vt velocity target rt getPosASLVisual target vr vt vectorDiff vm r rt vectorDiff rm omega ( r vectorCrossProduct vr) vectorMultiply (1 ( r vectorDotProduct r)) a ( vr vectorCrossProduct omega) vectorMultiply n a Similar questions Finding the components of Proportional Navigation in 2D |
6 | Change sprite angle on sloping ground I have a problem here with GameMaker built in physics environment.My player is designed to be on a skateboard. I want my player to rotate its sprite, according to the kind of fixture(up or down slopes) he is moving on.I've tried everything i could and everything i could find, but it didn't help me much, because the object is rotating in a very strange way.I enabled some flags to see the mask. Also, I've been studying vector algebra and i know it the angle between vector x speed and vector y speed should be the direction. Please help. Here's what i have so far 1 object which is the player Information about object obj Player Sprite sprite7 Solid false Visible true Depth 0 Persistent false Parent obj Static Parent Children Mask Physics Start Awake true Is Kinematic false Is Sensor false Density 0.5 Restitution 0.1 Group 0 Linear Damping 0 Angular Damping 0 Friction 0.2 Shape Polygon Points (76, 52) (76, 60) (0, 56) (0, 52) Create Event execute code Initialize the tires var half sprite width 2 var halfy sprite height 2 var tire instance create(x half 12,y halfy,obj Wheel) physics joint revolute create(id,tire,tire.x,tire.y,0,0,0,0,0,0,false) var tire instance create(x half 12,y halfy,obj Wheel) physics joint revolute create(id,tire,tire.x,tire.y,0,0,0,0,0,0,false) Step Event execute code Code facing point direction(0, 0, phy speed x, phy speed y) phy fixed rotation true phy rotation facing Move him if(keyboard check(vk space)) physics apply impulse(x,y,0, 100) if mouse check button(mb left) phy position x mouse x phy position y mouse y Information about object obj Wheel Sprite spr Wheel Solid false Visible true Depth 0 Persistent false Parent obj Static Parent Children Mask Physics Start Awake true Is Kinematic false Is Sensor false Density 0.05 Restitution 0.1 Group 0 Linear Damping 0.1 Angular Damping 0.1 Friction 30 Shape Circle Points (8, 8) (8, 8) Create Event execute code Keyboard Event for Key execute code physics apply torque( 100) Keyboard Event for Key execute code physics apply torque(100) And here is the result http i.stack.imgur.com sn1qh.gif |
6 | How do fluid dynamics work? How would I go about implementing fluid dynamics in a game, such as can be seen in this video? |
6 | How to implement stress strain mechanics in voxel terrain? I am in the process of developing a Minecraft like world where the terrain is divided into voxels. However, I would also like for unstable configurations of landscapes to collapse predictably. For example, an overhang that is too heavy would fracture and break off at 'high stress' voxels, as would a pillar formation with an asymmetrically eroded base. I was thinking about adding a 'stress vector' field to each voxel in the terrain, and doing the following (pseudocode) foreach voxel in terrain foreach neighbor in voxel.neighbor voxels() if magnitude(voxel.stress neighbor.stress) gt stressThreshold detach voxels(voxel, neighbor) But the problem is that I don't know how I would go about calculating these individual stresses. Is there some kind of FEA based algorithm specialized for voxel discretizations that I can use to calculate the stresses on a per voxel basis? Or am I approaching this all wrong and there's some other way to do this? |
6 | How do I set the size of a single 'unit' in my game? I'm currently trying to remake port an old game created on Unreal Engine 2.5 to my own engine, and I have access to its physics data. It's using a scale of 80 units per meter, or 1 unit 1.25cm. The walk speed value for example is 5, and physics is simulated at 60 FPS, so the walking speed I need to implement would be 3.75 meters per second. But I don't exactly know what the size of a game engine's quot unit quot actually means. I of course want my own engine (I'm using C , OpenGL, and GLM) to use this same scale, but I'm not sure how to go about that. I'd assume this affects not only physics movement code, but the scale of models and maps I load in as well, so it's important to make sure it's the same as in the original game. How would I implement this? What parts of a game does the size of a 'unit' affect and how? Just the physics and movement calculations, or the graphics side as well (matrices, clipping space, FOV, etc.)? (I'm not sure if I'm overthinking things) |
6 | Is there a benefit to applying forces to my camera? I have implemented a camera system and a rudimentary physics system. I now have a decision to make regarding steering the camera Option 1 Update the camera movement directly. eg. position (0, 0, 0) Key 'W' gt position (0, 0, 1) Option 2 Apply a force to the camera and let my physic's integration sort it out. eg. position (0, 0, 0) Key 'W' force (0, 0, 0.2) gt ...? How should I implement camera movement? |
6 | Integration of gravitational interaction I don't know if this question get her place in physics.stackoverflow forum. I prefer post here, with code etc. So, I want simulate 2D movements (no rotation) of an asteroid in space affected by a planet's gravity, the problem is how integrate that ? Any better integration for performance ? Here is the code in C struct vec2 float x float y struct body double mass kg struct vec2 prev pos for semi implicit euler method struct vec2 pos position struct vec2 v velocity void move asteroid(float dt) semi implicit euler integration 1 moving the object asteroid.pos.x asteroid.v.x dt asteroid.pos.y asteroid.v.y dt START float x planet.pos.x asteroid.pos.x float y planet.pos.y asteroid.pos.y float d x x y y distance 2 between asteroid and center of planet acceleration float ah G ((planet.mass asteroid.mass) d) gravity get components of gravity float rad atan2(y, x) float ax ah cos(rad) float ay ah sin(rad) semi implicit euler integration 2 update velocity asteroid.v.x ax dt asteroid.v.y ay dt this is for 'fun' and sadly my knowledge is quite not good, I try to find with my vocabulary (not native english), if you have directions, ideas for better implementation (like study RK4 for correctness etc), it's welcome |
6 | Box2d Body to follow mouse movement I am trying a box2d body to rotate following the mouse. Here's an image to clarify what I mean. The red and blue circles are current point of the mouse and the body (of corresponding color) moving rotating to follow it. Basically the rectangle should rotate with its one end pointed towards where the mouse pointer is. Here's my code so far, World world Body body, bullet Box2DDebugRenderer debugRenderer OrthographicCamera camera Override public void create() world new World(new Vector2(0, 0f), true) debugRenderer new Box2DDebugRenderer() float w Gdx.graphics.getWidth() float h Gdx.graphics.getHeight() BodyDef bodyDef new BodyDef() bodyDef.type BodyDef.BodyType.DynamicBody bodyDef.position.set(10, 10) body world.createBody(bodyDef) PolygonShape shape new PolygonShape() shape.setAsBox(2, 5) FixtureDef fixtureDef new FixtureDef() fixtureDef.shape shape fixtureDef.density 1f Fixture fixture body.createFixture(fixtureDef) shape.dispose() Gdx.input.setInputProcessor(this) camera new OrthographicCamera(200, 100 (h w)) camera.position.set(camera.viewportWidth 2f, camera.viewportHeight 2f, 0) camera.update() Override public void render() Gdx.gl.glClearColor(1, 1, 1, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) world.step(Gdx.graphics.getDeltaTime(), 6, 2) camera.update() debugRenderer.render(world, camera.combined) Override public boolean mouseMoved(int screenX, int screenY) int mouseX screenX int mouseY Gdx.graphics.getHeight() screenY float rotateAngle MathUtils.radiansToDegrees MathUtils.atan2((float) mouseY (float) body.getPosition().y, (float) mouseX (float) body.getPosition().x) body.setTransform(body.getPosition(), rotateAngle 57.2957795f) return true And here's a gif of how it appears now. as you can see the body gets skewed and also doesn't rotate properly. What am I missing? |
6 | Calculating the resulting velocity after a reflection I am trying to do a simple reflection of a point entity off of an arbitrary surface that contains it. It doesn't have to be physically correct but essentially the goal is to do the following if (isOutsideOfContainer()) placeOnNearestEdgeOfContainer() float2 container getContainerNormal() float2 newVelocity f(velocity, container) So essentially I am placing the out of bounds point on an edge of the container, getting the normal of the edge at that point on the container, and using that to calculate the new velocity vector. How exactly do I do this? I am doing this so that particles can "bounce" off of the edge of the screen as computationally cheaply as possible. Sometimes the screen will be a boring rectangle but other times it might be an iPhone X, or have half of its corners rounded. No matter what the screen I want to properly simulate its bounce. |
6 | How can I control a game 2d car mechanic from acceleration speed to just 1 value? So I have a car in a 2d game that runs on acceleration and speed, two values that have a max. The acceleration is small, under the value of 1 and it rises by an incrementation. The speed is large number like 100 and it rises by incrementing the current acceleration. They are both incremented relative to the fps but that's not important. What I am trying is to have a formula with having only one value (with a max) instead of two as I am trying to simplify the UI for the player. Alternatively, I was thining of having a value (lets call it speed) that gets incremented by something, without a max, but is limited by, lets say road friction (like multipling it with 0.99). Such a thing would be felt lower when the car is slow but eventually the friction would act as a max limit, the car oscilating to near max values. I know too little of physics and car stuff to figure this out on my own so I am reaching out for help. Thanks! |
6 | Perlin noise example the same on CPU as GPU? I am looking for an example site with a Perlin Noise implementation in both CPU and GPU, that generates somewhat the same results in those two places. I see many CPU implementations of Perlin Noise, but they don't match up with the GPU implementations that I found. The reason I need this is for physics. The map is generated with Perlin Noise on the GPU in 2D, but this also means that to do physics, I must have a CPU version of the algorithm that generates the same results. |
6 | Frame rate independent friction on movement in 2d game I have been trying to implement a simple physics system for a 2D space game I am making. I have it pretty much working, but I have encountered an issue with the way I apply friction. I have tried several different ways of solving it, with different guides found online, but my math skills are lacking and it's difficult for me to translate the solutions to fit my problem. I made a unit test that shows my problem Simulate a low FPS. Accelerate body1 with 100 pixels second, for a deltaTime of 1 (A single frame that took 1 second) body1.accelerate(100, 1) Performe the physics with the dame deltaTime. body1.doPhysics(1) Simulate a higher fps. Accelerate body2 10 times, with 100 pixels second for a deltaTime of 0.1 (A single frame that took 1 10'th of a second. for(int j 0 j lt 10 j ) body2.accelerate(100, 0.1) body2.doPhysics(0.1) Debug.Log("Straight movement result " body1.getPosition() " " body2.getPosition()) Which gives the result "Straight movement result 0.0, 50.0 0.0, 39.31200662855 " My acceleration does not seam to be a problem. I have a unit test like the other one, to test the acceleration, and it shows no problems. public void accelerate(double acceleration, double deltaTime) Vector2f accel new Vector2f(0, (float)(acceleration)) If power is negative, we want to go backwards. if(acceleration lt 0) accel.setTheta(angle 90 180) else accel.setTheta(angle 90) velocity.x (accel.x deltaTime) velocity.y (accel.y deltaTime) In the doPhysics method, is where I calculate the friction. If I remove the friction calculations, the two values printed from the unit test are equal. private static final float friction 1.0f 0.96f private void doPhysics(double deltaTime) Save the velocity before applying friction. Vector2d velBefore new Vector2d(velocity) Then apply friction, with deltaTime. velocity.x (velocity.x friction) deltaTime velocity.y (velocity.y friction) deltaTime And then calculate the average of the friction before and after friction and factor in deltaTime double realVelX ((velBefore.x velocity.x) 0.5) deltaTime double realVelY ((velBefore.y velocity.y) 0.5) deltaTime Add the calculated velocity. position.x realVelX position.y realVelY I hope someone can see what I am doing wrong. I would really like my physics to be frame rate independent and simple enough for me to understand. |
6 | How are real world car characteristics translated to in game? I am just entering the world of game development, starting with the racing genre of games. Let me clarify that this question is not about car modelling or external detailing it is about the way a car drives, handles, and the way it feels (how heavy or torque y it is, or how fast and nimble it is, the way it moves in place when you hit the brakes, etc.) in game. I am looking to understand the process game developers take to translate real world car characteristics and physics into in game cars. I am not talking specifically about simulation games I'm including even arcade games where driving a muscle car feels very different from driving a tuner, or a sports car, or super and hyper cars. Questions such as the following arise (1) Do developers have get their hands on a car physically in order to be able to map it into an in game car? When they drive it around, what metrics are they looking to capture so their in game car can feel as true to the real one? (2) What if they can't get a physical car, or if the car is a concept with no drivability? What metrics, data and telemetry should the car manufacturer supply in order for the car to be represented in game? (3) Within cars of the same kind, such as muscle cars, how do developers ensure that a Ford Mustang, a Dodge Challenger, a Chevrolet Camaro, all feel sufficiently distinct from each other in game? How do they ensure a Porsche 911 Turbo, a 911 GT3, a 911 GT2 all feel different, just as the real cars do? |
6 | Cocos2dx Chipmunk Fully elastic collision between moving bodies I'm using Cocos2dx and the built in Chipmunk physics engine, and currently I've got my PhysicsBodys' materials set up with Density 0 Restitution 1 Friction 0 in order to get fully elastic collision, and keep moving bodies moving at a constant speed. This works great if they collide against a static element, like a wall, not so much if they collide with other moving objects. I'm moving these bodies by applying an initial force Vec2 velocity moveDirection.getNormalized() moveSpeed myPhysicsBody gt getVelocity() Vec2 newForce myPhysicsBody gt getMass() velocity deltaTime myPhysicsBody gt applyForce(newForce) So I'm guessing that even though their materials would result in fully elastic collisions, the moving objects both carry an impact force, this modifies the resulting force into one with different magnitude? All these moving bodies have the same mass. Currently I'm manually catching the impact start and manually generating the resulting force in the right directing, and using the object's speed to apply it with the same previous magnitude, effectively overriding Chipmunk's collision resolution. Is this the best way to do this, or can I configure my bodies in a way that allows Chipmunk collision resolution to achieve the same effect? I'm a bit rusty on my physics.. heh.. |
6 | Strange behavior of RigidBody with gravity and impulse applied I'm doing some experiments trying to figure out how physics works in Unity. I created a cube mesh with a BoxCollider and a RigidBody. The cuve is laying on a mesh plane with a BoxCollider. I'm trying to update the object position applying a force on its RigidBody. Inside script FixedUpdate function I'm doing the following public void FixedUpdate() if (leftButtonPressed()) this.rigidbody.AddForce( this.transform.forward this.forceStrength, ForceMode.Impulse) Despite the object is aligned with the world axis and the force is applied along Z axis, it performs a quite big rotation movement around its y axis. Since I didn't modify the center of mass and the BoxCollider position and dimension, all values should be fine. Removing gravity and letting the object flying without touching the plane, the problem doesn't show. So I suppose it's related to the friction between objects, but I can't understand exactly which is the problem. Why this? What's my mistake? How can I fix this, or what's the right way to do such a moving an object on a plane through a force impulse? |
6 | Rotation of a 3D ball on a plane This used to be on the physics stack exchange but I was told to put it here I'm making a game (with physics) and I have a 3D ball rolling down a flat plane. It moves perfectly fine, but the rotation is messed up. It seems way too fast, and the axis seems to be all wrong. Here's the code that runs every tick (20 times per second). (normal is the normal to the plane, acceleration is gravity vector projected onto the plane, in m tick2, and velocity is the velocity in m tick.) vec3 rotationAxis normalize(cross(normal, acceleration)) quat newRotation rotate(oldRotation, length(velocity) sphereRadius, rotationAxis) rotate by v r radians about the rotationAxis I'm not sure why this doesn't work, since according to angular mechanics, v r and v t r (and t 1 since velocity is in meters tick). Am I doing something wrong? Why is the rotation so much faster than it should be? And is my axis of rotation correct? Rephrased in a more physics way, is this correct in 3D hat x frac hat N times vec a hat N times vec a Delta theta textrm about hat x frac v r Delta t And if it is correct, then what s wrong with my code? |
6 | Infinite ball bouncing problem (Unity) I am trying to develop a basic Breakout game using this tutorial using Unity 5. But the ball starts to bouncing infinitely very easily. I cannot understand why this happenes. In my physics knowledge starting an infinite bounce is very hard, and even impossible. To return the ball to same position after bouncing we must send the ball with zero degrees with the vertical axis. To send the ball with zero degrees with vertical axis we must receive the ball with zero degrees with the vertical axis. To receive the ball with zero degrees with the vertical axis we must send the ball with zero degrees, and so on. We can send a ball with zero degrees only in initial ball throw. In all the other cases there must be an angle which is not equal to zero. Am I wrong? I mean the ball does not change its rotation. Ball moves between two plates which are parallel to each other infinitely (for example between paddle and upper wall) I added physics material to ball, paddle and the walls. This material has following settings Dynamic friction 0 Static friction 0 Bounceness 1 Settings of the ball Mass 0.5 Drag 0 Angular Drag 0 Is Kinematic true (I changed to false just before firing) Use Gravity false Settings of the paddle Mass 0.5 Drag 0 Angular Drag 0 Is Kinematic true Use Gravity false |
6 | Soft body, where to start learning? I want to ask you about some resources to learn simulating soft bodies, do you know some good knowledge sources? I asking because I want to make car crash simulator, I've made something but it didn't work well. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.