gravity simulation implementation this.attract function () for (let i 0 i lt numofplanets i) var r Math.sqrt(Math.pow(blackhole.x planet i .x, 2) Math.pow(blackhole.y planet i .y, 2)) planet i .acclx (blackhole.mass(blackhole.x planet i .x)) Math.pow(r, 3) planet i .accly (blackhole.mass (blackhole.y planet i .y)) Math.pow(r, 3) planet i .acclx (blackhole.x planet i .x) 60000 without force implementation in which planets get sucked inside the blackhole planet i .accly (blackhole.y planet i .y) 60000 without force implementation in which planets get sucked inside the blackhole) planet i .speedy planet i .accly planet i .x planet i .speedx planet i .y planet i .speedy i am trying to create gravity simulation model for a game in JavaScript.i need planets to move around a black hole in elliptical orbits. first i calculate acceleration and then add it to velocity and according to that i calculate the next position of planet. i first tried with just calculating distance vector between planets and black hole but in that scenario planets directly gets sucked inside the black hole and i need them to move in elliptical orbits. i tried calculating acceleration due to gravity but i think formula is wrong so can you correct it or provide some other implementation.


Why does this whirlpool simulation not work? I am trying to create a simple whirlpool simulation, where particles are constantly compelled to move towards a point in a whirlpool like fashion. To do this I do the following (in sudo code) variable speed 1.0 This can vary to speed things up Rotate by (70 speed) degrees Move Forward (4 speed) Steps Point Towards center And this works quite nicely, however as the particles get nearer to the center it breaks down causing there to be an area where they just circle around never getting closer to the center. The larger the speed variable is the larger the radius is that they begin to not move closer to the center. If one decreases the rotate by to a value of like 50 degrees the anomaly is much smaller, however the points rotate around the center many less times. Why is this happening? How can I fix this? I am open to completely changing the method I use even if it means physics, however polar coordinates will not work because of the way the center moves among other simulation reasons.


Rotate a rigid body not around its centre of mass I have a rigid body (a boat) whose centre of mass is towards the front of the object. However, this makes the rotation look strange as the rudder that is turning the object is at the back of the boat so the rotation would be around that point. How can I rotate the object from the a separate point (using forces) without changing the centre of mass? Applying a force at a location still causes the object to rotate around the centre. In real life, you need to pin down the point that you want to rotate around, forcing the object to rotate around that point. This would suggest using constraints but I can't figure out how that would work. You sort of need the rotation point to act as a hinge, but when I apply a suitable constraint, but that would just block the rotation rather than convert it into a rotation around the new point. I want to resolve this using physics driven operations in Unreal Engine 4. I don't want to move the Centre of Mass, admittedly for not a particularly good reason, but this still feels like a valid question even if that was an option what if you want to rotate around two different points.


Voxel blocks world physic I'm making a game like Minecraft. I have a world made of blocks and I'm trying to implement a basic physic system that applies gravity and checks entities colliding with the blocks of the world. I tried using Bresenham's algorithm, on player move, to get all blocks between, and then get the first solid and set the player on colliding position. That works well if the player is a point, but if it's a complex AABB and the block too, it becomes difficult. Is there a simple way to make physic in a voxel world like Minecraft?


How to search through large numbers of discrete objects that interact with each other, like Minecraft blocks? Imagine you had a world like Minecraft, but wanted to bake in some sort of physics (okay, I was playing minetest actually). For example, blocks under too much pressure might break, limiting how many blocks can be stacked on top of one another. I see one approach to this Systematically check each block. See if there is a block on top of that, a block on top of that, ect. Then, determine the pressure on the block that you just started with. Do this for each and every block. I also imagine you could somehow check each block, then have it modify the properties of the blocks around it. If all force was from top to bottom, you could just start at the top. But if you want to have a "net force" (so unsupported blocks accelerate) I have no idea how this could be implemented. For instance, three blocks are floating in mid air. How can I solve this class of problem?


Detect collision point I'm writing a 3D rigid body physics engine, I am using OpenGl for simulation. Only convex objects are considered. My question involves how to detect the point of collision, so that when I apply a response force, I can also calculate torque. I have used SAT algorithm to detect collision according to this reference, Everything seems to be work fine , But as i get SAT only gives for objects are they colliding? as well as by how much?, it does NOT give you a reference point at which to apply the response force (and thus calculate torque). I have looked at Resource 1 Resource 2 Resource 1 None of them seems to be an answer


Uncover Physics Object to Pick it Up I want to be able to have physics objects semi buried in leaves, dirt, or whatever and be able to have the player click on the area a couple times to uncover them, and he can't pick it up until he has uncovered it. (He picks it up also by LMB.) How can I achieve this? I am using blueprints. Can anyone show me how?


Best physics engine for OpenGL ES (different implementations)? Can you recommend a good physics engine which is easily portable between WebGL and other OpenGL ES implementations like in Android and iPhone? I don't want a game engine. Only the physics part.


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


How can I approximate walking physics via simpler sliding physics? I am modeling walking insects. I implement them as cuboids and use forces (including friction and drag), to control motion. However, the movement characteristics of this 'sliding box' physics don't match those due to a legged creature. For example, legged creatures near instantly accelerate to their top speed whereas applying a force to a box takes time to accelerate it. The applied force can be increased along with the counteracting drag, giving much quicker acceleration (via force) to a max speed (via drag). However, this also means the force that creatures can exert when pushing on other objects is increased. Does anyone know of any techniques using a physics engine to cheaply model walking creatures?


How is 'mass' handled in video games? Mass is one of the basic scalar quantities, which is required in most rigid body physics calculations. In a game, does every moving object have mass defined in the code, or is it allotted by the rendered objects size? Size should not be the only solution, though, since density also comes into play. For example how does the physics engine handle mass in the Frostbite engine used in "Battlefield 3"?


Numerical differentiation to calculate size of circular buffer I'm using Allegro 5 to create a software generated "motion blur" effect for my 2D sprites. I basically just have a boost circular buffer of some length which holds "snapshots" of the sprite going back in time. Each render cycle a new "snapshot" of the main sprite is pushed onto the front of the buffer, and the last is popped off the back. The "snapshots" are then rendered with alpha values scaled by how old far back in the buffer they are. To save on CPU power I'd like to have the circular buffer dynamically resized so that the length of the trail is proportional to the object's velocity, i.e. don't store and push back lots of snapshots for trail sprites that won't be needed anyway because the object is moving too slowly. The inputs I have to the data structure that holds the main sprite and its associated effect buffer are just the dx and dy values of how much its position vector changed since the last update cycle of the game logic. So I'm looking for a suggestion for an algorithm that can use that to increment decrement some kind of unsigned counter that can be used to resize the buffer proportional to velocity.


Detecting overlap with Phaser P2 physics In a 2D platformer, I'd like to implement a ladder. I have collision working between the player and ground tiles. Now I would like to be able to detect when the player walks through a ladder tile (which can be one of three tile indices). When the player is overlapping a ladder and up is being pressed, the climbing state would be set. Ideally, I'd like to get a callback when this happens. It seems that the overlap method from Arcade physics is not available in P2. What is there instead to implement overlap detection?


Why are my objects becoming permanently stuck to walls using Box2D? I setup a simple simulation environment something like billiards. There are four circle balls (dynamic) and four box walls (static). Simulation works... except one thing. Sometimes when a ball rest against a wall, it sticks to the wall eternally. The other balls hits the stuck ball so many times, but the ball never wants to separated with the wall. The only situation where the ball will become unstuck from the wall is another if another ball is rests against the same wall such that it hits the already stuck ball. Why does this situation occur? How can I avoid it?


Bouncy Ball stops without enough force I am building a 3D Pong clone and want to implement a frictionless bouncing ball. These are the steps i took Create a box in which the ball can bounce, consisting of standard cubic objects. Create a ball using a spherical object Add a Rigidbody to said ball (Mass 1, Drag 0, A.Drag 0, no Gravity) Add a bouncy Physics Material to the balls Sphere Collider (D.Friction 0, S.Friction 0, Bounciness 1, Fraction Combine min, Bounce Combine max) Add a script to the ball that adds force to the ball on start Script Snippet void Start() this.getComponent lt RigidBody gt ().addForce(0, 0, 100) When i play the scene, the ball will fly towards the wall and then stop. If i change the added force to (0,0,101) it works as intended. If i lower the mass of the ball and use the old force (0,0,100) it also works. But it will always stop at the wall, if the added force is lt mass 100. What am i missing?


How can I implement fixed joints in a 2D physics system? I'm developing a simple, 2D physics system to complement an entity component game object framework. So far, I have implemented some basic, tutorial level physics. An entity that is affected by physics must have two components Transform (translation, rotation, scale may have parent transform) Rigidbody (mass, list of forces) The physics engine currently uses Verlet integration to move entities that is, velocity is derived from the current and previous positions of an entity, and is not explicitly stated anywhere. I would now like to start implementing some joints, starting with the basics and perhaps expanding as I grow more familiar with the concepts. The first joint I attempted to implement was extremely simple the fixed joint, whereby two entities are 'fixed' together and their transforms may not change relative to each other. My approach was to make one entity an immovable child of the other that is, to set the transform of A as a local transform relative to B and disable movement of A by passing all accumulated forces of the rigidbody of A to the parent, B. Already this seems hackish and inflexible and has issues with gravity (B ends up with two gravity forces acting on it) I'm clearly heading in the wrong direction. I have searched for some literature on the subject but have only found either very basic tutorials that only cover what I've already done, or articles with advanced mathematical formulae that are difficult to follow or relate to simulation in any meaningful way. This leads to two questions How are fixed joints normally implemented? Are there any good 2D physics simulation tutorials aimed at those without a degree in physics or mathematics?


Can I change shape of a rigid body after it created in Bullet3D? I'm beginning Bullet3D. Can I change collision shape of a rigid body after it created? A rigid body accepts a collision shape when it's creating, but it's hard to find options changes the collision shape of an instance.


Pseudo magnet implementation with chipmunk How should I go about implementing "natural" magnet on a certain body in chipmunk space? Context is of simple bodies lying in the space (think chessboard). When one of the figures is activated as a magnet others should start moving towards it. Currently I'm applying force (cpBodyApplyForce)to the other figures with vector calculated towards the activated figure. However this doesn't really feel "natural". Are there any known algorithms for imitating magnets?


Box2D Making it Determinsitic? From articles on the web, I found that floating point math generally has accuracy of at least 6 digits. With this in mind, is it possible to make Box2D which uses floats fully deterministic through the use of heavy rounding (i.e. 1st or 2nd decimal place)?


How to connect a UPhysicsConstraintComponent of an AActor to an FKSphylElem (capsule body) of a ragdoll? I'm trying to connect an Actor's UPhysicsConstraintComponent to a capsule body of a ragdoll. The reason I do it this way, instead of just using sockets on the constraint, is bodies may have offsets from bones, and than connected things things would look incorrect. I'd like to connect to the physics bodyFKSphylElem instead of the bone socket. The Physics Asset has a TArray lt UPhysicsConstraintTemplate gt called ConstraintSetup, which I am adding my quot Actor constraint quot to. It also has a TArray lt USkeletalBodySetup gt . These USkeletalBodySetups contain the geometries I'd like to connect to,in this case capsules as FKSphylElems. I wrote some code to give my idea a test. I am setting up bone and component names for the new constraint, but it does not connect objects, although the new UPhysicsConstraintTemplates and FConstraintInstances are added to the Phats ConstraintSetup (checked in the debugger). void UBPLibrary ConnectConstraintToSkeletalMeshActorPhysicsAsset( UPhysicsConstraintComponent Constraint, USkeletalMeshComponent Mesh, FName BoneName) if (!IsValid(Mesh) !IsValid(Constraint))return UPhysicsAsset Phat Mesh gt PhysicsAssetOverride if (!IsValid(Phat))return UPhysicsConstraintTemplate constraintTemplate NewObject lt UPhysicsConstraintTemplate gt () FConstraintInstance ConstraintInstance amp Constraint gt ConstraintInstance ConstraintInstance gt ConstraintBone1 BoneName ConstraintInstance gt ConstraintBone2 FName(Constraint gt GetName()) constraintTemplate gt DefaultInstance ConstraintInstance if (!IsValid(constraintTemplate))return Phat gt ConstraintSetup.Add(constraintTemplate) apply changes to the ragdoll UWorld world GetWorld(Constraint) FPhysScene PhysScene PhysX world gt GetPhysicsScene() Mesh gt TermArticulated() Mesh gt InitArticulated(PhysScene PhysX)


Bullet Physics Difference between Motion State and World Transform In Bullet Physics, when I create a new btRigidBody, one of the parameters passed to the constructor is the btMotionState, which defines the initial pose of the body. However, if I then later want to change the pose of the body manually (for example, if it is a kinematic body), how can I do this? What I have tried so far, is to use the body's setWorldTransform() function. For example glm mat4 pose pose 3 0 0.5 pose 3 1 2.0 pose 3 2 1.0 btTransform new transform new transform.setFromOpenGLMatrix((float ) amp pose 0 ) my body gt setWorldTransform(new transform) However, when I then try to read the pose of the object again btTransform trans my body gt getWorldTransform() std cout lt lt "Y " lt lt trans.getOrigin().getY() lt lt std endl It returns the value set in the body's constructor, not the value set in setWorldTransform(). Please can somebody explain the different between the motion state, and the world transform, and how I should go about manually updating the pose of a kinematic object?


Lunar lander How to calc acceleration in each step I'm trying to make a lunar lander simulator. I'm going to use a simple Euler integration. AFAIK all I've to calculate is the acceleration in each step, and then I should be able to update velocity and position. I'm following this page http www.braeunig.us apollo LM descent.htm There's a paragraph I don't really understand Although most operations are self explanatory, a brief description of acceleration is warranted. Acceleration is broken down into vertical and horizontal components, where the vertical component is normal to the Moon's surface. The instantaneous vertical and horizontal accelerations of a moving body in reference to this surface are Av Vh 2 r and Ah VhVv r. To this we add the accelerations resulting from gravity and thrust. Gravity, of course, acts vertically downward. The vertical and horizontal components of thrust are a function of the pitch angle. The author is making a much more realistic simulation here and because of that he is not assuming the Moon is flat. He comes up with two initial values for each acceleration component Av Vh 2 r Ah VhVv r 1 Seems that Av is the centripetal acceleration, but where does the Ah come from? 2 Are those initial values really needed? In my game the Moon is going to be flat. I thought taking into account thrust mass and gravity would suffice. Thanks in advance.


Does friction only apply in opposite direction of motion? Let's say an object is sliding on a slope and is the object has a velocity of (0,0,5). The friction would be acting in the opposite direction of motiong, being (0,0, 1). However, gravity is also affecting the object on the slope. The gravity is doing an impulse of ( 1, 1,0) every frame in the direction of the slope tangent. Should the object also experience friction in the direction of (1,1,0)? Or would it only experience friction in the direction of (0,0, 1)? I find the notion that friction always opposes the direction of motion strange, because this means that when an object is sliding downwards slightly on a slope, but not much, due to friction acting in opposite direction of gravity, when you add an impulse in a perpendicular direction, suddenly the object will be sliding downwards much more because friction is no longer resisting gravity. Is that correct?


Transfering an inertia tensor from local coordinates to another one If we have an inertia tensor in local coordinates with a basis matrix B and we want to transform it to other local coordinates with basis matrix A, is it right to do the following A inv(B) Inertia Tensor Where my idea is to shift the inertia tensor to world coordinates by multiplying it by the inverse of B, then from the world coordinates to the A coordinates by multiplying it with A matrix?


How do you properly implement level boundaries in a physics room? I have an issue with creating a proper boundary in GameMaker Studio when using a physics enabled room. My room has a gravity of 0, as it is in Space. My player object has the default values, but a friction of 10 with a box shaped collision shape. I also use View0 on a 1280x720 room with a 1280x720 view. That is to be able to do screen shakes and other neat effects. I really struggle with containing my player object properly to the room. When I use a collision with view0 boundary and add phy position x phy position previousx phy position y phy position previousy then my ship would get stuck at the screen borders very frequently. I also tried adding some sprites that block the player off the room and created a sprite, 1280x720 and spawned them at the borders. I gave my player empty events for them and set their density to 0, making them static. However, this resulted in the same problem, I got stuck in them. I need a smooth solution for this, obviously, to have a fun experience. I have this problem quite for a while, so please help me understanding how to do this properly.


Physics for space game I am making a space game where you fly a ship. I am trying to work out the physics for such a game and so far came up with var thrust between 1 amp 100 how much the engines are pushing var mass the mass of the spaceship var speed the speed at which the spaceship is moving Now big ships will have more mass to therefore take longer to speed up and longer to slow down once the thrust is off. Big ships will be slow because of the mass. Small ships will speed up faster and slow down faster but also go faster. How will I implement this into a game? I can do the keyevents, if up is pressed for 5 frames for example will I make the thrust raise to by 10 each frame(example) and then increase the speed of the ship based on some formula of the mass amp thrust? This is the game Only UI and menus made but wan to get an idea of my physics before I implement the movement http www.taffatech.com DarkOrbit.html


Deformable meshes based on torsional spring I am trying to learn physics based animation thanks to the book "Foundation of Physically Based Modelling and Animation". They introduce the mass spring model for deformable meshes. Although making each pair of vertices a mass spring system would give good results, it would be too heavy to compute. So, the authors introduce another technique between each pair of adjacent triangles, the evolution of the angle is based on a torsional spring model. I don't know if you can read it on the Google preview. It's on page 161 https books.google.fr books?id vaqdDQAAQBAJ amp printsec frontcover amp dq torsional spring foundation of physics based animation amp hl fr amp sa X amp ved 0ahUKEwj oPTkvobcAhVDtBQKHfj2AaYQ6AEIKzAA v onepage amp q amp f false I struggle to understand this model. For instance, let's imagine we have two adjacent triangles ABC and BCD . Let's theta be the angle between both triangles. The torque is tau k( theta theta 0) . We want to compute the equivalent forces f A , f B , f C , f D , and torques tau A , tau B , tau C , tau D relatively to B . They state that all sums must be equal to zero f A f B f C f D 0 tau A tau B tau C tau D 0 I don't understand why. Can you give me some help ? Thanks.


Solving constraints joints in 1D For n points moving in 1 dimension. Position and velocity are known for each point. Each frame a basic integration is done for each point velocity forces timestep forces 0 position velocity timestep Each point (except for the first one) is attached to the point following it (e.g to its right) with a distance joint of the form point2 point1 lt distance amp amp point2 point1 gt 0 Which means that the points shouldn't be further appart than distance or closer than 0. Energy should be conserved, i.e a point should be able to push pull another. I tried to solve every constraints with impulses, but it messes with velocities. (at least the way I did it..) Searching around, I found a lot of resources but I'm unfortunately not able to understand all of it. If anyone can give me a general idea starting point ?


Best physics engine for OpenGL ES (different implementations)? Can you recommend a good physics engine which is easily portable between WebGL and other OpenGL ES implementations like in Android and iPhone? I don't want a game engine. Only the physics part.


Find Initial Velocity for Parabolic Arc with Fixed Angle that Crosses Target Position In my game I want skeletons to occasionally lob bones at the player. The player can be anywhere in relation to the skeleton (above or below, to the left or right), and I want the skeletons to throw a bone such that it lands on the player (or its parabolic arc intercepts them while rising, if the player is above the skeleton). Given an arbitrary starting position, an arbitrary target point, and an arbitrary launch angle, how can I calculate the initial velocity of a ballistic projectile (assuming no air resistance) such that its parabolic trajectory intercepts the target point? I know there are a number of similar questions on this site, but none of them appear to have this particular set of requirements Calculating initial velocities given trajectory parabola requires a known fixed apex height. Calculating velocity needed to hit target in parabolic arc and Throw object towards predefined place? assume a known fixed travel time. I want to have a fixed launch angle, initial position, and final position, and from those determine the initial velocity. The Wikipedia article Trajectory of a projectile comes close, but I have no idea how to solve that for velocity. Reference In computer coordinates, the Y axis is inverted from Cartesian coordinates. The accepted formula operates independently of this, but it's unintuitive to deal with. This means that gravity will be a positive number, while being above the projectile will result in a negative displacement. This also means that the fixed angle you choose will be the negative of what the habitual version would suggest. As a final note, I adjusted for the absolute value of Vx by performing this manipulation before calculating Vy if sign(x velocity) ! sign(delta vector.x) x velocity 1 x velocity var y velocity x velocity tan(angle) Full pseudocode reference static func get velocity of arc intercept(initial position, target position, angle) var delta vector target position initial position var x velocity sqrt((gravity delta vector.x delta vector.x) (2 (delta vector.y (tan(angle) delta vector.x)))) Adjust for lost sign. if sign(x velocity) ! sign(delta vector.x) x velocity 1 x velocity var y velocity x velocity tan(angle) return Vector2(x velocity, y velocity)


collisions How to handle contact constraints for a rigidbody constrained to a line segment I'm trying to come up with a strategy to handle a situation in 2D, where a rigidbody moves along a straight line segment, and can collide with other similar bodies and also static tiles. A naive approach was to handle collisions by projecting the displacement vectors onto the line segment (worked ok for aabb), and then at the end snap the position of the rigidbody back to the line, which had lots of conflicts. I'm trying to implement impulse based physics, so far only handling contacts, and unsure how to both constrain the rigidbody to a line segment and handle contacts at the same time. Or is it better to do in two separate phases. It's probably easier to allow some displacement from the line and then gradually move the body back to it. Any suggestions?


Simple collision resolution in a platformer game I want to make a 2d platformer with moving, jumping and wall sliding. How can I make a simple pleasant collision resolution system that works for the following rectangles. Player is red, platform is black, I want to detect if the player is sliding a wall, or hitting the ground, or doing both ( as in third example). Also take the appropriate response. Also I have no idea what I am talking about so a little context might help. These resources helped me How to resolve collision 2D AABBs and resolving multiple collisions How to detect overlap between aabb vs aabb http noonat.github.io intersect


How can I predict player to projectile collisions in Box2D? I'm making a real time shooting game with Box2D as the physics engine. The gameplay is mostly about trajectory, like Angry Birds. I want to make a slow motion effect and move camera to the player when he's killed, but the effect should start when the stone is still in the air, before the collision actually happens. The magnitude of damage is only calculated at collision, based on impulse. Because it's a real time game, the player must be able to move their character's physics body without lag. How can I predict their death? Is it even possible? I could raycast, but what if another object moves to block its path?


Correct order of tasks in each frame for a Physics simulation I'm playing a bit around with 2D physics. I created now some physic blocks which should collide with each other. This works fine "mostly" but sometimes one of the blocks does not react to a collision and i think that's because of my order of tasks done in each frame. At the moment it looks something like this function GameFrame() foreach physicObject do AddVelocityToPosition() DoCollisionStuff() Only for this object not to forget! AddGravitationToVelocity() end RedrawScene() Is this the correct order of tasks in each frame?


Costs for developing an Iphone physics game? I recently made a game demo inspired by a wooden board game where you drop the ball trying to make a score, is fully playable so take a look (Works best on firefox) https dl.dropbox.com u 62131673 LuckyBall Chrome index.html I want to build this game for the Iphone's App Store, add accelerometer features, menus, unlockable levels, best scores, etc. I'm a graphic designer so I prefer to keep working on the presentation (graphics, assets, sound, music) and leave the rest to the programmer. I want to know how much this game would cost for a programmer to be developed, so I can make a video at kickstarter.com and sell the idea, with luck this game will see the light. I don't want to open a debate on the subject, I just need advice on the costs so I can hire someone.


3D Physics in Marmalade SDK I am trying to make an 3d game in Marmalade. I am completely new to Marmalade. How to add 3d physics, gravity, dynamic object, sensors, colliders in Marmalade. I was going through the API and did not find anything. Can you guys let me know how to accomplish these things


What is a collision shape? I am a business developer who is new to game programming. In learning Stencyl, I see that there are things called collision shapes associated with tiles. This seems to be a standard term in game programming. What is a collision shape?


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


How does server correct late input Imagine the following scene The height one player can reach on jumping depends on how much time the button for jumping is pressed. When the player jumps, the input is sent to the server and physics are updated. Now, imagine that for some reason, one input packet is lost or due to lag it begins to arrive late. From the point of view of server, the player is not jumping anymore, and its character will start its fall. Every other client will receive this information and let the character fall. Then, a new packet arrives that corrects this problem. From the perspective of the player, the character is still jumping. Maybe, thanks to this extra input the character can reach a higher slope. But from the point of view of the server and rest of clients, it wont make it. This could happen, but online games that i have played (except for long jumps and high lag) it doesnt happen. My question then is How does the server handle this situation? It cannot wait forever for input, it must update physics and acknowledge other clients on what's going on.


How do I set angular velocity torque so that it's pointing to velocity direction? Right now, when I spawn a shootable object, it goes like this Because I just set it's angle to this float aimAngle (float) Math.atan2(velocity.y, velocity.x) bullet.setBodyAngle(aimAngle) I want it to be like this I think I should use angular velocity or torque, but I have no idea how. I can't just set it's angle like in previous code every frame, because it makes physics collisions glitch.


Physics engine recommendation which can simulate pool game correctly? I'm making a pool game like game. This game requires correct (or very accurate) reflective bounces. I tried Box2D and Bullet Physics, but they both have this problem. If there is a wall on top of this image, red line is expected course of a real ball in a pool game. But the engines often shows green line course. Especially, This happens after a slowly moving ball hits the wall. Sometimes a rapidly moving ball get slower suddenly. I'm finding a physics engine which can simulate pool game accurately as much as possible without these problems. Can I get some recommendations? Now I'm digging Newton Game Dynamics, but I am not sure the engine will show what I want. I'm considering the PhysX engine as a next trial, and have to make my own if nothing works. But it's obvious it'll take very long time, so I wish I won't do that. I'll be very appreciated if you save my time. And of course, solution with Box2D Bullet Physics are also welcomed. I am working with C C Objective C on iOS. I attach my configuration with Box2D. Walls static box shape linear angular damping 0.1 restitution 1.0 friction 100 density 10 bullet false fixed rotation false inertial scale 1.0 Balls dynamic sphere shape linear angular damping 0.1 restitution 1.0 friction 100 density 20 bullet true fixed rotation false inertial scale 1.0


AS3 Flashdevelop Controlling a 2D character to move around a planet with gravity With a little help I have managed to create a 2D planet with working gravity that constantly pulls a character towards its center. The only problem now is that I am completely stumped on how to make it so the user is able to make this character traverse the planet as one would expect rather than the simple up down left right we are used to in natural platformers. It should be noted the planet being traversed will have platforms layers to jump and fall onto, so the moving and jumping should be in relation to the center of the planet, where the center of the planet acts as "down" would in a traditional platformer (which is why I seem to think I need a complicated way to create this kind of natural movement). I had the idea of recalculating a new left and right direction to move in every time position is changed but the logic I have to work out to achieve this is beyond my knowledge. Is this the only way to go or should I try tackling the problem differently? I hope not because I don't think I'd be able to achieve this otherwise. This is my current code showing how the gravity works, with a simple placeholder for movement that just allows the character to move up down left right on the screen public function moveChar(event Event) void if (leftPressed) character.x mainSpeed if (rightPressed) character.x mainSpeed if (upPressed) character.y mainSpeed if (downPressed) character.y mainSpeed public function gravity() void tan2(planet.y player.y, planet.x player.x) angle Math.atan2((planet1.y 2245) (character.y 5), (planet1.x 2245) (character.x 5)) gravityX Math.cos(angle) gravitationalAcceleration gravityY Math.sin(angle) gravitationalAcceleration distance Math2.Pythagoras(planet1.x 50, planet1.y 50, character1.x 5, character1.y 5) distance Math.sqrt((yDistance yDistance) (xDistance xDistance)) Calculate the distance between the character and the planet in terms of x and y coordinate xDistance (character.x 5) (planet1.x 2245) 320 to 50 yDistance (character.y 5) (planet1.y 2245) 320 to 50 Make sure this distance is a positive value if (xDistance lt 0) xDistance xDistance if (yDistance lt 0) yDistance yDistance Update the current velocity before new velocity is calculated initialXVelocity finalXVelocity initialYVelocity finalYVelocity Send the character into the correct direction character.x gravityX character.y gravityY Basic collision detection of the surface, basic stop of gravity if (distance lt planet1Radius) trace("hit!") if (planet1.x 2180 lt character.x 5) 320 to 50 character.x gravityX 1.025 else character.x gravityX 1.025 if (planet1.y 2180 lt character.y 5) 320 to 50 character.y gravityY 1.025 else character.y gravityY 1.025 else trace(" no hit!") edit1 I now have this code thanks to DMGregory var characterPosition Point new Point() var planetPosition Point new Point() characterPosition.x character.x characterPosition.y character.y planetPosition.x planet1.x planetPosition.y planet1.y var localUp normalize(characterPosition planetPosition) var localRight new vector2( localUp.y, localUp.x) However, I have trouble understanding the syntax I should be using here, and also for when I need to move the character. Should it look something like this if (rightPressed) character.x localRight if (leftPressed) character.x localLeft


Inelastic ball collision I'm trying to implement basic inelastic ball collision. The example on the link above is for one dimension. It explains that it's the same for 2D but where the velocities are the components in the direction of the normal in the point of collision. I have tried calculating these components by projecting on the normal vector, and then calculating the new velocities. But then I got stuck. How do I get the new velocity vectors? My attempt below does not produce any good result. Can you help me out? (The two balls are intersecting in one common point when I run the code below) UPDATE I have edited the code now so that the two last lines is more correct I think. The thing is I have to combine the new velocity vector component with the old velocity vector component that was first subtracted in the projection operation, to get the complete new velocity vector. Now the animation looks a lot better. I still get occasional ball merging and popping but that could be some other part of my code thats wrong. var m this.Mass other.Mass normal in the point of collision var n (this.Position other.Position).Normalized velocity component perpendicular to the tangent in the point of collision for ball A var ua (float)(this.Velocity.Magnitude Math.Cos(this.Velocity.Angle(n))) velocity component perpendicular to the tangent in the point of collision for ball B var ub (float)(other.Velocity.Magnitude Math.Cos(other.Velocity.Angle(n))) the new velocity for ball A var va (0.9f other.Mass (ub ua) this.Mass ua other.Mass ub) m the new velocity for ball B var vb (0.9f this.Mass (ua ub) this.Mass ua other.Mass ub) m the new velocity vector for ball A this.Velocity n (ua va) the new velocity vector for ball B other.Velocity n (ub vb)


How to resolve multiple simultaneous ball collisions in a pool game? I'm trying to simulate a break shot in billiards (1 ball hits a pyramid of 15 balls). The formula for 2D ball collision works correctly in my game. But when it is applied to the break shot, the result doesn't look realistic. (Only the 2 balls in the corners of the pyramid move, but the rest stays in place). The problem is that because 15 balls are touching each other, there is an "infinite" number of simultaneous collisions following the first one. What algorithm or formula can be used to resolve that?


How to apply force to rigid bodys at a specific point? I am trying to write a physics engine from scratch to get a better understanding of them. It worked pretty good so far, but there is one thing, i can't get my head around If i have a rigid body ( for example circles or rectangles) and i am applying a force F at a point P to it. Now my problem is to figure out, how this force will affect translation speed and rotation speed of the rigid body. So far i have figured out, that it might has to do with the center of mass and the moment of inertia.


How can I fix my velocity damping to work with any delta frame time? I am decreasing my velocity by 50 every second using a guide I found online. I am using the code here and it gives the right result but only for very small values for dt float dt, velocity, position dt 0.002f velocity 1.0f position 0.0f for (float t 0.0f t lt 1.0f t dt) position velocity dt velocity lerp(velocity, 0.0f, 1.0f std pow(0.5f, dt)) printf("dt f, p f, v f n", dt, position, velocity) dt 0.09f velocity 1.0f position 0.0f for (float t 0.0f t lt 1.0f t dt) position velocity dt velocity lerp(velocity, 0.0f, 1.0f std pow(0.5f, dt)) printf("dt f, p f, v f n", dt, position, velocity) return 0 But I am getting roughly the right velocity BUT two different final positions back when I use two different delta times (not due to floating point issues) dt 0.002000, p 0.722848, v 0.499308 dt 0.090000, p 0.784219, v 0.473029 How can I fix this difference inside of my update loop? How do I account for the extra acceleration between timesteps?


Detect collision point I'm writing a 3D rigid body physics engine, I am using OpenGl for simulation. Only convex objects are considered. My question involves how to detect the point of collision, so that when I apply a response force, I can also calculate torque. I have used SAT algorithm to detect collision according to this reference, Everything seems to be work fine , But as i get SAT only gives for objects are they colliding? as well as by how much?, it does NOT give you a reference point at which to apply the response force (and thus calculate torque). I have looked at Resource 1 Resource 2 Resource 1 None of them seems to be an answer


How to implement a configurable spring force to SpringJoint2D like SpringJoint does? I'm working in unity 5.3.4f1. Looking at the SpringJoint2D class I can't seem to find a similar "spring force" as in spring in SpringJoint. Is there any other way to make a spring stronger in SpringJoint2D? If not, the only option I see is to inherit the Joint2D parent class and build my own spring joint 2D.


Algorithm to propagate internal Physics force in a structure of building Scenario A floating structure composes of many nodes (or in more visual meaning a cubic block). Every node is snapped to the same 3D grid. (similar to a minecraft castle) There are external forces apply to each node at different values. For example, node A receives force Vec3(1,0,0) at time 1s 3s, node B receives force Vec3(0,1,0) at time 2s 4s. Most external forces apply to center of mass of node. Every pair of adjacent nodes (6 neighbors) is tied together by a "joint" i.e. glue. Each joint can received some (but limited) pulling pushing force torque. Question How to calculate approximate force of each and every joints? I want to use them to break object apart create some spark graphics. Maximum flow problem is fast, but too limit for this case. Although it is quite efficient to propagate force like fluid in pipe system, it don't support Torque and many sources sinks. https en.wikipedia.org wiki Maximum flow problem Networks of Torque Propagation requires a solid ground, so it can't be used for this problem. http www.cs.brandeis.edu pablo thesis html node29.html Bullet Physics Engine I tried to use its constraint, but for very high amount of nodes (400), they are not stable, i.e. become divergent amp explode. My poor approach I initialized all force between joint Vec3(0,0,0), and then use Newton Rules (F ma amp T Ixw) to propagate force gradually in each iteration. It always yields perfect result but take too much time (10 ms), so it is unusable. Note that the algorithm can provide non optimal solution and can have some limitation (e.g. no torque). Performance is important (500 nodes within 1 2 ms, C ).


What are the parameters for btHingeConstraint setLimit? What does each parameter in btHingeConstraint setLimit do to the hinge constraint? void btHingeConstraint setLimit ( btScalar low, btScalar high, btScalar softness 0.9f, btScalar biasFactor 0.3f, btScalar relaxationFactor 1.0f )


How do I set an object's speed to arrive in X seconds? I want to move an object to a point in the game world, I have the distance value which is far the player should move. I want to complete the movement in X seconds. I have tried many equations and formulas to no success. Speed Distance Time This one doesn't seem to give me the right result. Thing is the game is updated 60 times a second and the movement is affected by delta time. I'm pretty sure I am not taking the framerate in consideration. What am I doing wrong? Edit This is how I calculate the speed int dst 500 int time 2 in seconds float speed dst time Doing it this way is making the movement instant and the game object is not traveling the distance in 2 seconds. Every frame each game objects gets updated this way p.x dir.x speed deltaTime p.y dir.y speed deltaTime The dir vector holds the direction of movement which is calculated on mouse click Vector2 dir new Vector2(mouseX, mouseY).subtract(objectX, objectY).normalize() Delta time calculation long time System.nanoTime() float deltaTime (time lastTime) 1000000000.0f lastTime time Please note The game object stops upon arrival.


cocos2d syncing CCAnimation frames with Box2d Shape manipulations my cocos2d game currently has a ccsprite attached to a box2d body. during the game i apply different CCAnimations on my sprite, i would like to perform certain manipulations to the box2d body according to the frame currently displayed by the sprite (change rotation of the body, etc.) my current idea on implementing this is to subclass ccsprite and change the setDisplayFrame implementation but i thought somebody here probably did the same and already has a solution, so any suggestions on how to implement this? thanks!


Box2D Love2D (Lua) Assertion fail with polygon meshes When I try to create a triangle collider for my game it sometimes leads to an assertion fail. I use the physics engine that comes with love2d (Box2D). That's the error message that appears when the assertion fails love modules physics box2d Source Collision Shapes b2PolygonShape.cpp 85 b2Vec2 ComputeCentroid(const b2Vec2 , int32) Assertion area gt 1.19209289550781250000e 7F' failed. Here's an example of a triangle that doesn't cause the error (represented by a table with 3 points) 258,451 , 740,767 , 284,597 And this one leads to a crash 258,450 , 222,569 , 306,723 The bodies of both shapes lie at 0, 0 (upper left corner of the screen) Does anyone know a possible reason and or solution for the problem? Edit I'm not allowed to answer my question right now for some reason so I'll post the answer here before I've forgotten it In Box2D, the order of placement of vertices seems to play an important role, since I was able to avoid the crash with the "problematic" triangle in my example from my question just by placing the first vertex between the second and the third one. Maybe I'll repost the answer when I'm able to provide more information (and am also allowed to do so)


gamemaker getting a ball to bounce 90 degrees off of a 45 angle I am trying to get a circle to bounce off a 45 degree diamond shap using Gamemaker Studio. I would like the ball to bounce in straight lines so my directions would be 0, 90, 180, or 270 degrees, depending on which side of the diamond the collision takes place. Precise bouncing is giving me all sorts of results so I think I would have to do it in code. I tried saying if (direction 0 amp amp direction lt 90) direction 90 And doing this for all the angles, but this did not work. Has anyone encountered this before?


ways to make a physics engine Hey so i've been looking into real time physics engines, which led me to the crazyLaggoa multiphysics engine by thiaga costa, and brought up the question of What are some possible ways, ideas that have or have not already been done to make a real time physics engine? How about non real time? I know the Lagoa engine uses meshes and a crapload of particles... and then there's the rigid body way of going about things..... Also i'm only at 2d level in creating games right now so any 2d physics ideas would be great too!


How to throw b2body with various speed at fixed position? Above image is for ref to better representation. I have box2d object and i know start point amp end point position. Now i want to give any force or impulse such that b2body will first collide at end point BUT with different speed also should collide at that same end point. How should i achieve this?


How to calculate continuous motion with angular velocity in 2d I'm really new with physics. Maybe someone would be able to help me to solve the next problem I need to calculate position of an agent on the plane(2D) in next time step where time step is large(20 seconds) What I know about agent's motion Initial Position Direction(normalised vector) Velocity(linear function from time ) object always moves along it's direction Angular Velocity(linear function from time) Optional External force direction External force (linear function from time) Running discreet simulation with t 0 is not an option.


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?


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.


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.


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!


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.


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.


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.


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.


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?


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


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?


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?


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.


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?


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.


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?


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.


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?


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


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.


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.


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.


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.


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?


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?


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)


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?


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?


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.


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?


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.


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


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?


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.


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?


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.


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?


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 ?


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.


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.


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.


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?


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.


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


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?