AS3 Flash Develop Radial Gravity (character on planet simulation) I am trying to create a program where a character shape will be constantly drawn towards the centre of a planet shape. I have taken on previous advice into using physics equations to generate the desired effect yet I think I am missing some and therefore it does not work (I am only using v 2 u 2 2as). Am I over complicating things? All I need is for the player object to be constantly drawn towards the centre of the planet object there will be no need for other planet objects to come into play and affect the player's gravity. edit To clarify, my question should have been "where did I go wrong?". I have now since solved the problem with the answers posted below, which were present because I wasn't going about trying to achieve what I wanted the right way. I didn't calculate the actual direction to move in as expected, and so the character could not move in the expected direction. Here is my Main.as package import flash.display.InteractiveObject import flash.display.Sprite import flash.events.Event import Math import flash.display.Bitmap import flash.display.DisplayObject import flash.events.KeyboardEvent import flash.text.TextField import flash.text.TextFormat import flash.utils. ... author Me public class Main extends Sprite public var planet1 Planet public var character1 Character public var initialXVelocity Number 0 public var initialYVelocity Number 0 public var finalXVelocity Number public var finalYVelocity Number public const gravitationalAcceleration Number 3 public var xDistance Number public var yDistance Number public function Main() if (stage) init() else addEventListener(Event.ADDED TO STAGE, init) private function init(e Event null) void removeEventListener(Event.ADDED TO STAGE, init) entry point planet1 new Planet character1 new Character place entites in position to test note planet 1 is 100 100 pixels, character 1 is 10 10 pixels planet1.x 350 planet1.y 250 character1.y 100 295 character1.x 396 395 addChild(planet1) addChild(character1) Make sure character has gravity applied constantly setInterval(playerMove, 1000) public function playerMove() void Calculate the distance between the character and the planet in terms of x and y coordinate xDistance (character1.x 5) (planet1.x 50) yDistance (character1.y 5) (planet1.y 50) Make sure this distance is a positive value if (xDistance lt 0) xDistance xDistance if (yDistance lt 0) yDistance yDistance Calculate velocity using physics equation v 2 (u 2) 2as finalXVelocity Math.sqrt((initialXVelocity initialXVelocity) (2 gravitationalAcceleration) xDistance) finalYVelocity Math.sqrt((initialYVelocity initialYVelocity) (2 gravitationalAcceleration) yDistance) trace(initialXVelocity) trace(gravitationalAcceleration) trace(xDistance) trace(finalXVelocity) trace(initialYVelocity) trace(gravitationalAcceleration) trace(yDistance) trace(finalYVelocity) Make sure the character is moving towards the centre of the planet at all times by reversing the appropriate velocity once it passes the axis of the centre of the planet if (planet1.x lt character1.x) finalXVelocity finalXVelocity if (planet1.y lt character1.y) finalYVelocity finalYVelocity Update the current velocity before new velocity is calculated initialXVelocity finalXVelocity initialYVelocity finalYVelocity Send the character into the correct direction character1.x finalXVelocity character1.y finalYVelocity


Using Minimum Translation Vector in SAT algorithm I am working on a simple rigid body physics engine ,I've already implemented SAT algorithm for collision detection and everything works fine, Now i get to step to use MTV to calculate the distance which objects might move to, In my case the two objects are cubes ,Actually i am a little confused about the distance and how to use it Here is the two cubes Both of them are on the same y axis and z axis, Only differs in x axis I am calculating MTV and i get samllest which refers to the smallest axis, So it looks like (x,y,z). overlapDistance which refers to the smallest overlap distance as a double variable. I know that overlapDistance is the distance that one of two cubes should move till no collision But how to use it , How cubes should respond to this distance ? Sorry if i am not clear, but for summary i know the smallest overlap distance but i don't know how to get use of it


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?


Friction due to gravity in an impulse based physics engine In my physics engine, I'm using impulses to solve collisions. I'm basing all calculations on these equations impulse desired velocity change mass impulse force time friction force lt normal force coefficient If an object moves along flat ground (infinite mass), after integration it'll be moving slowly "into" the ground due to gravity. This means that the impulse needed to react to that (given the restitution equals 0) will be the velocity in the direction of the contact normal, multiplied by mass. The issue here is that gravity is a constant acceleration, which means that the object, no matter the mass, will always "dip" by the same amount given a constant frame rate. So the mass is never a factor in this situation, outside of the impulse calculation, which is just a flat velocity change. Now, I can use impulse to calculate the force that was needed to react to the collision, this force can then be used in the friction equation as such friction impulse time lt normal impulse coefficient time Since time is always greater than 0, I can just multiply both sides by it, and then I can use the impulse equation, as such planar velocity change mass lt velocity change along normal mass coefficient And again, I can just remove mass from the equation, which leaves me with planar velocity change mass lt velocity change along normal mass coefficient This is the desired velocity change along the contact surface due to friction. The issue is, obviously, that none of this depends on mass, which means that no matter how heavy or light an object is, it'll always continue sliding along the surface by the same amount given a constant initial velocity. What am I missing? It really looks like there's a logical mistake here. Should the dynamic friction depend on the mass in the first place? Moving a heavy object requires higher force, so static friction should be modeled properly, since it just flat out removes velocity, though it'd be nice to hear if this has merit or just "looks good".


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?


Why do people like realistic' physics and graphics in games? If games are all about fun, then why do people tend to like realistic physics and graphics are good for games? Can you cite your source?


Change sprite angle on sloping ground I have a problem here with GameMaker built in physics environment.My player is designed to be on a skateboard. I want my player to rotate its sprite, according to the kind of fixture(up or down slopes) he is moving on.I've tried everything i could and everything i could find, but it didn't help me much, because the object is rotating in a very strange way.I enabled some flags to see the mask. Also, I've been studying vector algebra and i know it the angle between vector x speed and vector y speed should be the direction. Please help. Here's what i have so far 1 object which is the player Information about object obj Player Sprite sprite7 Solid false Visible true Depth 0 Persistent false Parent obj Static Parent Children Mask Physics Start Awake true Is Kinematic false Is Sensor false Density 0.5 Restitution 0.1 Group 0 Linear Damping 0 Angular Damping 0 Friction 0.2 Shape Polygon Points (76, 52) (76, 60) (0, 56) (0, 52) Create Event execute code Initialize the tires var half sprite width 2 var halfy sprite height 2 var tire instance create(x half 12,y halfy,obj Wheel) physics joint revolute create(id,tire,tire.x,tire.y,0,0,0,0,0,0,false) var tire instance create(x half 12,y halfy,obj Wheel) physics joint revolute create(id,tire,tire.x,tire.y,0,0,0,0,0,0,false) Step Event execute code Code facing point direction(0, 0, phy speed x, phy speed y) phy fixed rotation true phy rotation facing Move him if(keyboard check(vk space)) physics apply impulse(x,y,0, 100) if mouse check button(mb left) phy position x mouse x phy position y mouse y Information about object obj Wheel Sprite spr Wheel Solid false Visible true Depth 0 Persistent false Parent obj Static Parent Children Mask Physics Start Awake true Is Kinematic false Is Sensor false Density 0.05 Restitution 0.1 Group 0 Linear Damping 0.1 Angular Damping 0.1 Friction 30 Shape Circle Points (8, 8) (8, 8) Create Event execute code Keyboard Event for Key execute code physics apply torque( 100) Keyboard Event for Key execute code physics apply torque(100) And here is the result http i.stack.imgur.com sn1qh.gif


How to account for speed of the vehicle when shooting shells from it? I'm developing a simple 3D ship game using libgdx and bullet. When a user taps the mouse I create a new shell object and send it in the direction of the mouse click. However, if the user has tapped the mouse in the direction where the ship is currently moving, the ship catches up to the shells very quickly and can sometimes even get hit by them simply because the speed of shells and the ship are quite comparable. I think I need to account for ship speed when generating the initial impulse for the shells, and I tried doing that (see "new line added"), but I cannot figure out if what I'm doing is the proper way and if yes, how to calculate the correct coefficient. public void createShell(Vector3 origin, Vector3 direction, Vector3 platformVelocity, float velocity) long shellId System.currentTimeMillis() hack ShellState state getState().createShellState(shellId, origin.x, origin.y, origin.z) ShellEntity entity EntityFactory.getInstance().createShellEntity(shellId, state) add(entity) entity.getBody().applyCentralImpulse(platformVelocity.mul(velocity 0.02f)) new line added, to compensate for the moving platform, no idea how to calculate proper coefficient entity.getBody().applyCentralImpulse(direction.nor().mul(velocity)) private final Vector3 v3 new Vector3() public void shootGun(Vector3 direction) Vector3 shipVelocity world.getShipEntities().get(id).getBody().getLinearVelocity() world.getState().getShipStates().get(id).transform.getTranslation(v3) current location of our ship v3.add(direction.nor().mul(10.0f)) hack this is to avoid shell immediately impacting the ship that it got shot out from world.createShell(v3, direction, shipVelocity, 500) Edit I switched to v3.set(direction) v3.nor().mul(velocity) if (platformVelocity ! null) v3.add(platformVelocity) entity.getBody().setLinearVelocity(v3) And it seems to work (so adding the velocities and setting them on the body). However, I'm not sure what the drawbacks are and why the tutorial application used impulses instead of setting velocities. I also think that while this is physically correct it leads to strange results (gun range is two times further when shooting forward than when shooting sideways). The root cause is because really the shells are indeed too slow, but I like them slow as otherwise the gameplay is too fast paced, and they travel too far. I think I need some compromise between physics realistic and ignore platform velocity.


Are you supposed to be looping through all PhysicsObjects at every step in a physics engine? I am currently making a small 2D game and I am trying to implement some basic 2D physics. I currently have a list of around 100 PhysicsObjects which I loop through every frame in order to update and apply forces to that object based on user input. The basic code is as follows accumulator 0 dt 0.01 while running for each object in PhysicsObjects update object accumulator time between last frame and current frame while accumulator gt dt for each object in PhysicsObjects resolve forces to get new position of object based on dt accumulator dt for each object in PhysicsObjects render the object I was going to resolve the forces and calculate the new position in the update method of each object, but I was told the dt was necessary in order to make the movement and physics independent of frame rate, which is why it is in a separate loop. I also can't update the objects in the physics engine loop as the update method needs to occur every frame. This already seems incredibly inefficient, and I haven't even started to test for collisions or anything else more in the physics engine. Is there a better way to structure this where I don't need to loop through every object again in order to calculate their new position?


Can I use physics in Isometric map based games? I am trying to use physics in my game which is an isometric map based strategy game that the player deals with a city full of buildings, roads and people in it. I am writing the game with Swift and SpriteKit technology. (the following picture shows a snapshot of my game) MY GAME I like to use Spritekit's physics library so I would be able to simulate car accidents and preventing them to go throw the buildings and other kind of stuff that physics could provide. I am familiar with Physics and I have enough experience with Bullet and I can write a 3D game using OpenGL ES and physics, but I haven't really used physics in 2D isometric map games. I have also wrote a 2d physic game that was really 2d (an endless runner) which was actually a sample of a book but as you can see in the following picture the gravity vector is the Y axis and every thing is pretty easy. Here is the gravity vector that is used to create the game at the following picture. self.physicsWorld.gravity CGVectorMake(0, 9.8) Someone Elses Game, Book Sample Book Name iOS 7 Game Development Author Dmitry Volevodz You may find the book Here However, in an isometric map game you can't just set and assign the Y axis as a gravity vector. since the method which sets the gravity vector accepts two arguments it is a big hope that I can use physics in my isometric map games. For example something like this I Say!!! As I am still using a cartesian coordinate system (perpendicular axis) X and Y axis make a 90 degree angle and if I need to project the gravity quantity over the X and Y axis it would be gCos(45),gSin(45) I haven't tested it yet. self.physicsWorld.gravity CGVectorMake( 9.8 0.707, 9.8 0.707) May you please help me on setting the gravity vector and how should I define the moving objects like cars and humans and the static ones like buildings any other tips on modelling physics in isometric map are also welcome and appreciated. The main question is is it really possible to use physics in an isometric map based games?


Bullet Physics Scaling rotational part of 6DoF Spring Damper I am currently trying to scale up my setup (consisting of two rigid bodies connected by a btGeneric6DofSpring2Constraint) to fall within the suggested dimensions for a concise simulation. In order to do so, I followed to the provided Wiki http www.bulletphysics.org mediawiki 1.5.8 index.php?title Scaling The World. I scaled all the linear properties and concerning the resulting forces, everything turned out physically consistent. Note that I did not scale up the liner and angular stiffness and damping values. However I encountered significant deviations concerning the spring related torques resulting due to a angular spring offset. I guess that this issue arises due to the fact that the torques should be scaled ( scale 2) as well. However I do not see a way of scaling the internal torque representation of the btGeneric6DofSpring2Constraint. Should i simply scale up the angular spring stiffness and spring damping by a factor ( scale 2) or is there a better more elegant way to retrieve physically consistent results (forces, torques, motion) when trying to scale a world containing the btGeneric6DofSpring2Constraint? EDIT I was able to boil it down to the following The rotational stiffness and damping vales are chosen independent from the scale. The stiffness itself does not alter the behavior of the system. The deviations are caused entirely by the damping part. An experiment with altering the scale and non existent damping showed results independent from the scaling factor, just as desired (K stiff 20.0, K damp 0.0) . However when repeating the same experiment with no stiffness and a positive damping factor, significant differences arise when scaling up. (K stiff 0.0, K damp 9.0) The image denotes the system responses for different scales. I found the corresponding code snippet in btScalar fs ks error dt btScalar fd kd (vel) (rotational ? 1 1) dt btScalar f (fs fd) info gt m constraintError srow (vel f (rotational ? 1 1)) btScalar minf f lt fd ? f fd btScalar maxf f lt fd ? fd f printf(" .3lf n",f) if(!rotational) info gt m lowerLimit srow minf gt 0 ? 0 minf info gt m upperLimit srow maxf lt 0 ? 0 maxf else info gt m lowerLimit srow maxf gt 0 ? 0 maxf info gt m upperLimit srow minf lt 0 ? 0 minf info gt cfm srow cfm srow info gt rowskip count Interestingly, the scaling works just fine if the if clause is commented out. Any sugestions why this happens?


Aircraft trajectory prediction I have an aircraft that is controlled by player and i need to predict it's position at needed time. It's not a problem if the plane is just moving straight but most of the time aircraft is maneuring. So i came up with an aproximation that aircraft movement can be described as a helix. So i have a point A and linear velocity V 1 that aircraft had at a time of t 1. Point B and linear velocity V 2 that aircraft had at a time of t 2. In that approximation we may assume that V 1 equals V 2 so it will be a perfect helix. And i need to find a point C in that aircraft will be at a time of t 3.


Inertia in flight simulation using box2d I'm trying to simulate flight using box2d and libgdx. The main problem I am currently experiencing is with inertia since there is no air, the plane looks like it were drifting. I wasn't able how to turn off inertia. I have two ideas Imitate air resistance by applying force Imitate flight using linear velocity without using any box2d physics Are any of these two ways correct? Or maybe there is way to turn off inertia?


Friction using delta time returns inconsistent result Slowing down a character using the following formula returns different results depending on the frame rate this.y this.yVel delta this.yVel Math.pow(0.99, delta) Is there a better way to decelerate a player using delta time to allow for consistent movement across several framerates?


Why do physics engine use impulses to solve collisions? Usually, in most physics engines that are out there, the way that collisions are solved is by applying some impulse to both colliding bodies. While I understand that impulses are just force that is already integrated into time, and will result into velocity added at the end of the frame, why not simply project both bodies out of collision and removing their velocity component that is going towards the collision? I'm not really sure, but it really looks like classic platformers only stopped the character instead of adding impulse to it. Is this right? And if yes, why the added complexity of using impulses in modern engines?


Calculate gears rotation for a realtime simulation I'm trying to do a game with real time simulations of gears. There is a big Gear with inside a smaller gear. I managed to draw gears with different diameters but equal size teeth, but if i try to move the smaller one inside the bigger one the movement is odd. See the animated gif The biggest gear is in center C1 and the small in the center C2. I calculate C2 position in this way C2.x C1.x C1 RADIUS C2 RADIUS) cos(t) C2.y C1.y C1 RADIUS C2 RADIUS) sin(t) for t that goes from 0 to TWO PI in n steps. I apply as rotation the angle t, but maybe it is wrong and i have to calculate another rotation for get a perfect joint. EDIT I am using radians for rotations and I think this is OK. My main problem is that I want to achieve a perfect joint between teeth like this example. My teeth are overlapping in some odd way. EDIT a working example can be found here http www.openprocessing.org sketch 83665


Is there any reasons to make sprites and bodies line up? So in LibGDX the Sprite objects position is where it's 0,0 mark is in the word. In Box2D a a bodies position is in it's center. So to line these up when you update the sprites position with the bodies position you would adjust it by half the width and height. But it seems to me theres no reason to worry about that. Because the relative position is always going to be the same, and that it'll just waste calculations lining it up. Is there any reason I should do it?


Radiometric quantities and time in rendering Often in papers people use various radiometric quantities, mostly radiant flux, radiant intensity, radiance and irradiance. It seems to me that all of these quantities are dependent on time. For example, radiant flux is defined as the amount of radiant energy per span of time (emitted by a light source). The other quantities contain radiant flux in some measure so they seem to depend on time as well. Yet when reading papers, people don't go into time at all. For example, some papers say "the radiant flux diffusely reflected by this area of the surface is x" and then they go on to explain that x is just light colored intensity surface color or something (depending on the illumination model used, of course), not factoring in any kind of time at all. Is this because the time frames observed are assumed to be 1 second? Is the time factored out somewhere (perhaps when defining the light intensity, which may be defined as radiant flux)? What am I misunderstanding here?


Lunar lander why is my descent module crashing I've been reading this awesome simulation of the actual Apollo 17 descent http www.braeunig.us apollo LM descent.htm I've been trying to make my own simulation using Euler integration, with a time step of 100ms. The problem is my descent module is crashing during the first two minutes with a vertical speed of 220 m s. During the initial stage of the descent (braking), the lander is tilted 90 and almost all the thrust is spent in the horizontal component, with no force to counter gravity. In my simulation the vertical speed quickly builds up while the pitch is 80 90 , and then gravity does it job. Here's a trace t 0 s x 0 y 17234.6112 vx 1697.1264 m s vy 20.4216 m s ax 1.2995855485404475 m s2 ay 1.6121564579144938 m s2 pitch 90 throttle 0.1297 fuel 8874.2Kg t 10.015 s x 17062.974621379497 y 16948.14950433809 vx 1710.2669538608811 m s vy 36.64853435841286 m s ax 1.3247309786564347 m s2 ay 1.628484797082333 m s2 pitch 90 throttle 0.1297 fuel 8855.501190599978Kg t 20.019 s x 34239.89169813059 y 16498.912567960208 vx 1723.6514116543285 m s vy 53.026163503416676 m s ax 1.3509707026458686 m s2 ay 1.6456786784409965 m s2 pitch 90 throttle 0.1297 fuel 8836.82291908347Kg t 30.026 s x 51527.03405575163 y 15884.74450896862 vx 1725.5675762461628 m s vy 69.5834660661016 m s ax 0.9584923539027193 m s2 ay 1.663174744204344 m s2 pitch 90 throttle 1 fuel 8756.011226046036Kg t 40.041 s x 68759.3217349438 y 15103.315677459259 vx 1715.7571868391299 m s vy 86.32821281208818 m s ax 1.0003892381595199 m s2 ay 1.6806337716945954 m s2 pitch 90 throttle 1 fuel 8611.841531365935Kg t 50.502 s x 86651.75776002374 y 14107.047450672597 vx 1705.0564069549016 m s vy 104.00697912916615 m s ax 1.0452064683102156 m s2 ay 1.6991809596193168 m s2 pitch 90 throttle 1 fuel 8461.251498809865Kg t 134.865 s x 226365.92349700694 y 5.915270639694082 vx 1602.384872970266 m s vy 225.9485740506923 m s ax 1.382111636427434 m s2 ay 1.224439728661491 m s2 pitch 78 throttle 1 fuel 7246.814359289593Kg FINISHED at t 2.24775 minutes However, in the original simulation, vertical speed never exceeds 20 m s. I don't know how could this be possible, as there's no drag due to atmosphere. And I've coded initial acceleration and velocity values exactly as in this very same page. You can check the original trace here http www.braeunig.us apollo LM descent.pdf Here we can see the Moon's gravity is aprox. 1.5 m s which heavily influences ay in my simulation. However in the real descent trace it was kept to lower values ( 0.1) most of the time, even during the first minute when there was no vertical thrust due to the engine. I must be making very stupid mistakes but right now I can't see where. BTW this is how I update my vars in each step Calculate acceleration as a function of mass, velocity, thrust and gravity ax vx vx (y MOON MEAN RADIUS M) (thrust x mass) ay (vx vy (y MOON MEAN RADIUS M)) g (thrust y mass) This would be the acceleration for a flat moon. Don't work either. ax thrust x mass ay g (thrust y mass) Update velocity as a function of acceleration and time. vx vx ax dtSecs vy vy ay dtSecs Update position x x vx dtSecs y y vy dtSecs Any hint would be appreciated. Thanks in advance.


Leapfrog integration vs Euler integrator I am looking at various integration methods for my n body simulation and I'm slightly confused about actual implementation of leapfrog integration. According to the wikipedia page leapfrog method is defined like this When I imagine how to code it, i come up with something like this while true dt time since last frame for every object object.position object.velocity dt for every object acceleration object.calculate acceleration() object.velocity acceleration dt render() But this is Euler integration, right? So moving the initial velocity back by one half step makes a first order method into a second order method? But for me a small change of initial velocity is not important, it will be set as a random value anyway... Why I won't just use velocity verlet This is for a game where tens of thousands particles fly around affected by forces roughly resembling gravity. I'd like to keep amount of data stored in every partile as low as possible to improve cache locality, which is why I don't want to use a method that requires storing acceleration (and recalculating it would be too slow).


Orbits Combine the Pros of RK4, Symplectic Euler, and Verlet Velocity Integrator Recently, I've implemented and compared a number of basic integrators for my physics engine. The 3 that gave me the best results are RK4, Symplectic Euler, and Verlet Velocity, but I think I need something a little more advanced. I've done many Google and StackExchange searches but haven't found what I'm looking for. I'm looking for something that combines the strengths of those integrators without their weaknesses. I'm only concerned about orbital mechanics. Drag and other similar forces will not be put through the integrator because it's not important that I get perfect answers for those other forces, but (near) perfect answers are very important for my orbital mechanics. Computationally expensive algorithms (within reason) are not as much of a concern as accuracy is. My thoughts and primary concerns are as follows RK4 Pros Very accurate. RK4 Cons Loses energy over the long term. This sim needs to be able to run for a VERY long time, so experiencing this kind of "orbital decay" is quite undesirable. Symplectic Euler and Verlet Velocity Pros Symplectic Don't lose energy. Symplectic Euler and Verlet Velocity Cons Much less accurate. Highly eccentric orbits make this apparent very quickly...even with a simple massless satellite orbiting a massive object scenario, the satellite's orbit "rotates" around the parent object over longer periods of time. This is extremely undesirable behavior. For my purposes, I cannot resort to orbits "on rails". TLDR I am looking for an algorithm that gives me the accuracy of RK4 without the slow decay. Computational expense is not a major concern. Thanks in advance for the help! Update 1 I found a similar question here https stackoverflow.com questions 3680136 help with symplectic integrators There might be good answers in the accepted answer, but after several hours of study, I have only determined that they are very difficult to understand. I will keep studying the accepted answer's linked paper and source code and post an answer if I get results. However, I suspect that while the algorithm is not much more complicated than RK4, the symbology and style of the linked explanations source code are making it very difficult for anyone without a heavy math physics background to understand. Unfortunately, as a comment noted, the OP accepted that answer, but never came back and gave a clearer explanation himself. I'll leave this question open and keep studying myself. Hopefully, together we can come up with a clearer answer for future searchers!


Calculating collision of polygons Say I have a multitude of 2D polygons floating about on a plane. These polygons can have any side count and aren't necessarily regular. Assuming I know absolutely everything about the polygons (area, collision point, location, velocity, rotation, angular velocity... etc) how to I calculate what happens to two polygons after collision? I.e. what will their resultant velocities and angular velocities be after collision? If not an exact solution, what resources could help me learn how to accomplish this?


Implementing a motorized hinge joint I have a 2d physics engine, with three boxes "body", "left wing" and "right wing". The wing boxes are connected to the body using a hinge joint. The physics world has no gravity. I'm attempting to rotate the wings around their hinge connection, as if the joint is motorized but I'm not exactly sure how to achieve that. If I exert force with a downward vector on the center of the wings, the body itself flies down. This is undesirable. With an actual hinge motor, only the wings will rotate about the hinge, affecting the body only when they hit it. Which forces should be added to the wings, and at which origin points? I'm using Phaser.io, with P2.js physics, but the question is platform agnostic.


What is a simple deformer in which vertices deform linearly with control points? In my project I want to deform a complex mesh, using a simpler 'proxy' mesh. In effect, each vertex of the proxy collision mesh will be a control point bone, which should deform the vertices of the main mesh attached to it depending on weight, but where the weight is not dependant on the absolute distance from the control point but rather distance relative to the other affecting control points. The point of this is to preserve complex three dimensional features of the main mesh while using physics implementations which expect something far simpler, low resolution, single surface, etc. Therefore, the vertices must deform linearly with their respective weighted control points (i.e. no falloff fields or all the mesh features will end up collapsed) as if each vertex was linked to a point on the plane created by the attached control points and deformed with it. I have tried implementing the weight computation algorithm in this paper (page 4) but it is not working as expected and I am wondering if it is really the best way to do what I want. What is the simplest way to 'skin' an arbitrary mesh, to another arbitrary mesh? By skin I mean I need an algorithm to determine the best control points for a vertex, and their weights.


Box2d Body to follow mouse movement I am trying a box2d body to rotate following the mouse. Here's an image to clarify what I mean. The red and blue circles are current point of the mouse and the body (of corresponding color) moving rotating to follow it. Basically the rectangle should rotate with its one end pointed towards where the mouse pointer is. Here's my code so far, World world Body body, bullet Box2DDebugRenderer debugRenderer OrthographicCamera camera Override public void create() world new World(new Vector2(0, 0f), true) debugRenderer new Box2DDebugRenderer() float w Gdx.graphics.getWidth() float h Gdx.graphics.getHeight() BodyDef bodyDef new BodyDef() bodyDef.type BodyDef.BodyType.DynamicBody bodyDef.position.set(10, 10) body world.createBody(bodyDef) PolygonShape shape new PolygonShape() shape.setAsBox(2, 5) FixtureDef fixtureDef new FixtureDef() fixtureDef.shape shape fixtureDef.density 1f Fixture fixture body.createFixture(fixtureDef) shape.dispose() Gdx.input.setInputProcessor(this) camera new OrthographicCamera(200, 100 (h w)) camera.position.set(camera.viewportWidth 2f, camera.viewportHeight 2f, 0) camera.update() Override public void render() Gdx.gl.glClearColor(1, 1, 1, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) world.step(Gdx.graphics.getDeltaTime(), 6, 2) camera.update() debugRenderer.render(world, camera.combined) Override public boolean mouseMoved(int screenX, int screenY) int mouseX screenX int mouseY Gdx.graphics.getHeight() screenY float rotateAngle MathUtils.radiansToDegrees MathUtils.atan2((float) mouseY (float) body.getPosition().y, (float) mouseX (float) body.getPosition().x) body.setTransform(body.getPosition(), rotateAngle 57.2957795f) return true And here's a gif of how it appears now. as you can see the body gets skewed and also doesn't rotate properly. What am I missing?


What are the advantages of having a real time based physics? Possible Duplicate Fixed time step vs Variable time step Now just let me clarify what I mean by "real time based physics", which I will call RTBP from now on. Well, basically, it implies taking, you guessed it, actual time into calculations. For example timePassed time lastTime positionx vx timePassed positiony vy timePassed lastTime time This would be a simple RTBP model. What's the alternative? I call it "step based physics" (SBP from now on), which would just be this positionx vx v in SBP is obviously smaller than in RTBP positiony vy I currently use SBP, but I see that many people actually include time in their calculations. Why is that? I of course limit the update time to 1000 60ms. Once the update interval is limited, both models would behave the same. The only difference is when the FPS drops. I believe that here is where PBS excels over RTBP. In PBS the game would, yes, run slower, but would always produce the same results! In RTBP, the position might increase so much that an object actually passes through a wall! Anyway, there must be something that I'm missing.


Box2d topdown racing game killing "residual" forces I'm making top down race game in GM S with Box2D, the car is controled in unusual way player sets direction and engine's speed, and the car uses them turns to the desired direction and reaches speed. But the question is about the "residual" speed after the turn. Here is what I mean I make rotation by applying torque and move with applying force. I don't have tyres, it's just one plain object. So how can I get rid of this momentum? I'm working in GM S, but I'd like to hear any solution, I can adapt it easily. Movement code var ad angle difference(phy rotation, desiredDir) physics apply torque((angleTorque) sign(ad)) rotate the car dx lengthdir x(spd, phy rotation) dy lengthdir y(spd, phy rotation) physics apply force(phy position x, phy position y, dx, dy) move the car


How do you convert angle with velocity to x velocity and y velocity? This question can be simplified to If you lean a pencil of a certain length at a certain angle what is the x and y position of the tip? So, basically, I am making a game that plots a balls path through the air as it travels. I want the user to enter an angle and velocity to launch a ball at and get the program to convert that to an x and y velocity so that it can work out how to plot the balls movement across the screen. The x velocity doesn't change through the simulation but the y velocity will decrease constantly until the ball touches the ground again. This is why I referenced to a pencil because it relates to turtle graphics calculations.


How to convert strict limit in position into gradual slow down? The player moves a spell object, the spell must stay withing a certain range of the player. The spell is moved using a physics system and it has mass and velocity. Currently when the spell goes out of range of the player it's being moved back into range, this has the effect stopping the spell abruptly at the edge. I want to smooth out this abrupt stop so that it gradually slows down. I tried to apply an easing function but because the time and distance change every frame I couldn't figure out the formula. Is there some sort of physics or easing formula I can use to gradually slow down the spell before it gets to the edge of its range, while at the same time guaranteeing that it never leaves the range? Additional Info The spells range is a circle. I only care about the center of the spell object. Movement forces are continually being applied to the spell.


Objects are stumbling in place continuously. How to fix that? I have a nasty problem with my physics engine. Objects sometimes just jump in place, or roll left and right. Main game loop works in that manner Every living object is updated (it changes velocity, the logic is different for each object) Engine computes collisions using objects' positions and velocities and resolves them. Imagine that we have a grenade positioned at one pixel above ground, with zero speed, and the gravity is 1 px tick 2. Normal bounce coefficient is 0.5, so an object will bounce with half speed. According to the algorithm Object's controller adds gravity to its velocity, so now v 1. Engine moves object to y 0, no collisions happen. Velocity is changed to 2 by the controller. Engine tries to move the object, the collision happens immediately, v is set to 1, and object moves to y 1. Velocity is changed to 0 by the controller. The object remains in place. Initial conditions has reproduced. The object will bounce forever with a period of 3 ticks. These situations vary, but they all are caused by discrete nature of the engine described above. This bug was in every version of my game. Objects may vary in shape and size, and the terrain is destructible Worms like. I use my own engine that uses swept collision detection customized to work with small and fast objects, never letting them go through impassable object unless they were spawned inside, and the only acceptable option for me is to modify it. One thing that I have in mind that I can detect if object had very low speed for some time, make it "immobile" and call different controller functions depending on "immobile" flag. It's an ugly solution though, because the complexity of my logic will increase. Also, when a round object stands on two points and we remove one, it will not fall. So this approach is wrong at all I guess. What is the right approach to fix that?


Verlet collision with impulse preservation I came across this article, recently, that presented a technique for impulse preservation with position based verlet integration. What was interesting was that the integration steps are seemingly done differently from typical position based verlet schemes, as well as the ordering of the integration step and collision resolutions. Specifically, the typical verlet position integrator is newPosition 2 position oldPosition acceleration timeStepSquared oldPosition position position newPosition DoConstraints() Where the article has position acceleration timeStepSquared DoConstraints() newPosition position 2 oldPosition oldPosition position position newPosition Which ignoring constraints for a moment works out to be newPosition 2 position oldPosition 2 acceleration timeStepSquared oldPosition position acceleration timeStepSquared position newPosition Which is different in a term of acceleration timeStepSquared. I haven't quite convinced myself that those terms cancel out through the iteration, as the prior acceleration timeStepSquared term may not be the same as the current one. Could someone explain the reasoning for this, and if indeed it makes sense?


What to do after detecting OBB OBB intersection I'm using this code to detect intersections between two OBBs. The problem is that i don't know what to do after detecting it. I tried using a simple algorithm if (collision detected) move character back to its position on previous frame But this is not what i need, because the character is rotating and moving to certain points (usually to mouse click position). When it's close to an object with OBB and it rotates to a point, its OBB updates (the position of all OBBs corners is recalculated) and most of the time the updated OBB intersects with an object that is near, so the charecter gets stuck at its position. How can i deal with the rotation problem or what other methods can you offer for stoping character when its OBB itersects with another?


How to get the physics just right in a physics driven game I'm working on a physics driven game using a java port of Bullet (JBullet). In our game we have a ball that can have collisions with the other objects, including the objects that define the boundaries of the playing area. Since we consider collisions between the ball and other objects as a very important aspect of the gameplay we wish to handle those collisions in our own code. This allows us to get non realistic but very controllable behavior for the ball. The other gameobjects also collide with each other, but JBullet handles those collisions well and we have no issues there. The problem is that we have great difficulty triggering the custom behavior in the correct way. In our first set up called our custom collision handling code every time JBullet reported a collision for the ball. This caused undesired behavior as a single hit could trigger multiple reported collisions. Which caused the ball to be sort of glued to the wall. Our "fix" for this was to have the ball keep a timer and to ignore subsequent collisions occurring within let say 0.1 second of another. However, this caused ball to bounce through walls in some cases, probably because the first reported collision isn't the one we expect, and the ball wall collision occurring shortly after is sadly ignored. So that brings me to my question. How does one sort this out without resorting to all sort of "fixes" that only make the problem more complicated and less predictable? Would for instance placing the ball at the last known position before the collision and handling the collision from there work? But what if another object has moved to that position in the mean time. Or maybe calculate future collisions with the ball for non moving objects and enforcing them if they are missed by the physics? Any feedback thoughts revelations would be greatly appreciated!


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?


How can I synchronize ocean waves over the network? I've been performing a little bit of research in my spare time on ways to increase the interactivity of environments in a networked game or simulation. One of my areas of research is fluid dynamics and whether it would be possible to synchronize it over the network. I believe the short answer to that is Yes of course you can. But there will obviously be trade offs as there are with any network synchronization problem. I was recently playing Battlefield 4 and a number of their maps have playable ocean areas with fully functional waves large enough to obscure entire boats during gameplay. It seems to work quite well as well. My assumption here is that the ocean simulation is completely offline and each client performs synchronization with the server during initialization. This would allow all clients to run the exact same ocean simulation that appears to be dynamic but is in fact the same offline simulation every time. Interaction with the ocean simulation appears to be only superficial with local splash wave depression. I assume that is entirely local to the client and not synchronized. My question here is Would the above be an appropriate way to synchronize fluid simulation over a networked game? If not, what would you suggest?


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.


How do I figure out if a point is infront or behind my vehicle? I need to figure out whether a point is infront or behind my vehicle. I have the vector of it's position, forward direction. So far I have tried finding the vector perpendicular to its forward direction and then calculating what side of the line it is positioned on. This works fine at first. But then I realised it is only calculating around the origin. bool Car isInfront(ngl Vec2 pos) http stackoverflow.com questions 1243614 how do i calculate the normal vector of a line segment if we define dx x2 x1 and dy y2 y1, then the normals are ( dy, dx) and (dy, dx). create vector per to the direction of travel. ngl Vec2 fwdVec m carPhysics gt getForwardVec2() ngl Vec2 pos m carPhysics gt getPosVec2() ngl Vec2 dir pos fwdVec float dx dir.m x pos.m x float dy dir.m y pos.m y ngl Vec2 v1( dy, dx) ngl Vec2 v2(dy, dx) ngl Vec2 perp (v1) (v2) int turn getLeftOrRight( pos, perp) if(turn LEFT) return true else return false int Car getLeftOrRight(ngl Vec2 dir, ngl Vec2 fwd) http gamedev.stackexchange.com questions 34536 calculating angle between two vectors to steer towards a target cross product float val ( dir.m x fwd.m y) ( dir.m y fwd.m x) if(val gt 0) return LEFT else return RIGHT


Implementing proportional navigation in 3D Good afternoon guys, a N ' V is the formula for the commanded acceleration required to hit the target, where N is the proportionality constant, ' is the change in line of sight and V is the closing velocity. Data I natively have x,y,z position of both missile and target vx,vy,vz velocity vector of both missile and target x,y,z vector which points from missile to target and opposite This is set by me but still maximum speed of missile. Data I can get with some calculations Vertical angle between missile and target (and opposite) Horizontal angle between missile and target (and the other way around). That's the reference system of the game ' or the derivative with respect to time of the Line of Sight it's a concept I really didn't understand... its unit should be, in theory, Hz or (s 1) since m s 2 ' m s ' 1 s V should be pretty easy to calculate V v(missile) v(target) OR Vx (v(missile) v(target)) cos (x0y) Vy (v(missile) v(target)) sin (y0z) Vz (v(missile) v(target)) cos (y0z) N well it's a scalar number, usually 3. The computed acceleration will then be passed to a RK4 integrator which will move the interceptor towards its target. To steer the missile, I will simply change its velocity vector at every update (every 1 60th of a second) and its orientation accordingly. For example if the missile has a velocity of 0,100,0 , he's going 100 m s due y axis. If at the next frame it should slightly turn right, then he'll be going to have a velocity of 10,99,0 and so on. That's the only thing left to finish off my little thesis and unfortunately I'm stuck here. In the meantime, thank you very much! Here's a video I made, but it doesn't still actually use the Proportional Navigation law it checks if the missile is "aligned" to its target and eventually correct its route. That's my actual code pastebin That's what i've come up with but sadly doesn't work as expected params " n"," missile"," target" private " a" vm velocity missile rm getPosASLVisual missile vt velocity target rt getPosASLVisual target vr vt vectorDiff vm r rt vectorDiff rm omega ( r vectorCrossProduct vr) vectorMultiply (1 ( r vectorDotProduct r)) a ( vr vectorCrossProduct omega) vectorMultiply n a Similar questions Finding the components of Proportional Navigation in 2D


Change sprite angle on sloping ground I have a problem here with GameMaker built in physics environment.My player is designed to be on a skateboard. I want my player to rotate its sprite, according to the kind of fixture(up or down slopes) he is moving on.I've tried everything i could and everything i could find, but it didn't help me much, because the object is rotating in a very strange way.I enabled some flags to see the mask. Also, I've been studying vector algebra and i know it the angle between vector x speed and vector y speed should be the direction. Please help. Here's what i have so far 1 object which is the player Information about object obj Player Sprite sprite7 Solid false Visible true Depth 0 Persistent false Parent obj Static Parent Children Mask Physics Start Awake true Is Kinematic false Is Sensor false Density 0.5 Restitution 0.1 Group 0 Linear Damping 0 Angular Damping 0 Friction 0.2 Shape Polygon Points (76, 52) (76, 60) (0, 56) (0, 52) Create Event execute code Initialize the tires var half sprite width 2 var halfy sprite height 2 var tire instance create(x half 12,y halfy,obj Wheel) physics joint revolute create(id,tire,tire.x,tire.y,0,0,0,0,0,0,false) var tire instance create(x half 12,y halfy,obj Wheel) physics joint revolute create(id,tire,tire.x,tire.y,0,0,0,0,0,0,false) Step Event execute code Code facing point direction(0, 0, phy speed x, phy speed y) phy fixed rotation true phy rotation facing Move him if(keyboard check(vk space)) physics apply impulse(x,y,0, 100) if mouse check button(mb left) phy position x mouse x phy position y mouse y Information about object obj Wheel Sprite spr Wheel Solid false Visible true Depth 0 Persistent false Parent obj Static Parent Children Mask Physics Start Awake true Is Kinematic false Is Sensor false Density 0.05 Restitution 0.1 Group 0 Linear Damping 0.1 Angular Damping 0.1 Friction 30 Shape Circle Points (8, 8) (8, 8) Create Event execute code Keyboard Event for Key execute code physics apply torque( 100) Keyboard Event for Key execute code physics apply torque(100) And here is the result http i.stack.imgur.com sn1qh.gif


How do fluid dynamics work? How would I go about implementing fluid dynamics in a game, such as can be seen in this video?


How to implement stress strain mechanics in voxel terrain? I am in the process of developing a Minecraft like world where the terrain is divided into voxels. However, I would also like for unstable configurations of landscapes to collapse predictably. For example, an overhang that is too heavy would fracture and break off at 'high stress' voxels, as would a pillar formation with an asymmetrically eroded base. I was thinking about adding a 'stress vector' field to each voxel in the terrain, and doing the following (pseudocode) foreach voxel in terrain foreach neighbor in voxel.neighbor voxels() if magnitude(voxel.stress neighbor.stress) gt stressThreshold detach voxels(voxel, neighbor) But the problem is that I don't know how I would go about calculating these individual stresses. Is there some kind of FEA based algorithm specialized for voxel discretizations that I can use to calculate the stresses on a per voxel basis? Or am I approaching this all wrong and there's some other way to do this?


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)


Is there a benefit to applying forces to my camera? I have implemented a camera system and a rudimentary physics system. I now have a decision to make regarding steering the camera Option 1 Update the camera movement directly. eg. position (0, 0, 0) Key 'W' gt position (0, 0, 1) Option 2 Apply a force to the camera and let my physic's integration sort it out. eg. position (0, 0, 0) Key 'W' force (0, 0, 0.2) gt ...? How should I implement camera movement?


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


Box2d Body to follow mouse movement I am trying a box2d body to rotate following the mouse. Here's an image to clarify what I mean. The red and blue circles are current point of the mouse and the body (of corresponding color) moving rotating to follow it. Basically the rectangle should rotate with its one end pointed towards where the mouse pointer is. Here's my code so far, World world Body body, bullet Box2DDebugRenderer debugRenderer OrthographicCamera camera Override public void create() world new World(new Vector2(0, 0f), true) debugRenderer new Box2DDebugRenderer() float w Gdx.graphics.getWidth() float h Gdx.graphics.getHeight() BodyDef bodyDef new BodyDef() bodyDef.type BodyDef.BodyType.DynamicBody bodyDef.position.set(10, 10) body world.createBody(bodyDef) PolygonShape shape new PolygonShape() shape.setAsBox(2, 5) FixtureDef fixtureDef new FixtureDef() fixtureDef.shape shape fixtureDef.density 1f Fixture fixture body.createFixture(fixtureDef) shape.dispose() Gdx.input.setInputProcessor(this) camera new OrthographicCamera(200, 100 (h w)) camera.position.set(camera.viewportWidth 2f, camera.viewportHeight 2f, 0) camera.update() Override public void render() Gdx.gl.glClearColor(1, 1, 1, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) world.step(Gdx.graphics.getDeltaTime(), 6, 2) camera.update() debugRenderer.render(world, camera.combined) Override public boolean mouseMoved(int screenX, int screenY) int mouseX screenX int mouseY Gdx.graphics.getHeight() screenY float rotateAngle MathUtils.radiansToDegrees MathUtils.atan2((float) mouseY (float) body.getPosition().y, (float) mouseX (float) body.getPosition().x) body.setTransform(body.getPosition(), rotateAngle 57.2957795f) return true And here's a gif of how it appears now. as you can see the body gets skewed and also doesn't rotate properly. What am I missing?


Calculating the resulting velocity after a reflection I am trying to do a simple reflection of a point entity off of an arbitrary surface that contains it. It doesn't have to be physically correct but essentially the goal is to do the following if (isOutsideOfContainer()) placeOnNearestEdgeOfContainer() float2 container getContainerNormal() float2 newVelocity f(velocity, container) So essentially I am placing the out of bounds point on an edge of the container, getting the normal of the edge at that point on the container, and using that to calculate the new velocity vector. How exactly do I do this? I am doing this so that particles can "bounce" off of the edge of the screen as computationally cheaply as possible. Sometimes the screen will be a boring rectangle but other times it might be an iPhone X, or have half of its corners rounded. No matter what the screen I want to properly simulate its bounce.


How can I control a game 2d car mechanic from acceleration speed to just 1 value? So I have a car in a 2d game that runs on acceleration and speed, two values that have a max. The acceleration is small, under the value of 1 and it rises by an incrementation. The speed is large number like 100 and it rises by incrementing the current acceleration. They are both incremented relative to the fps but that's not important. What I am trying is to have a formula with having only one value (with a max) instead of two as I am trying to simplify the UI for the player. Alternatively, I was thining of having a value (lets call it speed) that gets incremented by something, without a max, but is limited by, lets say road friction (like multipling it with 0.99). Such a thing would be felt lower when the car is slow but eventually the friction would act as a max limit, the car oscilating to near max values. I know too little of physics and car stuff to figure this out on my own so I am reaching out for help. Thanks!


Perlin noise example the same on CPU as GPU? I am looking for an example site with a Perlin Noise implementation in both CPU and GPU, that generates somewhat the same results in those two places. I see many CPU implementations of Perlin Noise, but they don't match up with the GPU implementations that I found. The reason I need this is for physics. The map is generated with Perlin Noise on the GPU in 2D, but this also means that to do physics, I must have a CPU version of the algorithm that generates the same results.


Frame rate independent friction on movement in 2d game I have been trying to implement a simple physics system for a 2D space game I am making. I have it pretty much working, but I have encountered an issue with the way I apply friction. I have tried several different ways of solving it, with different guides found online, but my math skills are lacking and it's difficult for me to translate the solutions to fit my problem. I made a unit test that shows my problem Simulate a low FPS. Accelerate body1 with 100 pixels second, for a deltaTime of 1 (A single frame that took 1 second) body1.accelerate(100, 1) Performe the physics with the dame deltaTime. body1.doPhysics(1) Simulate a higher fps. Accelerate body2 10 times, with 100 pixels second for a deltaTime of 0.1 (A single frame that took 1 10'th of a second. for(int j 0 j lt 10 j ) body2.accelerate(100, 0.1) body2.doPhysics(0.1) Debug.Log("Straight movement result " body1.getPosition() " " body2.getPosition()) Which gives the result "Straight movement result 0.0, 50.0 0.0, 39.31200662855 " My acceleration does not seam to be a problem. I have a unit test like the other one, to test the acceleration, and it shows no problems. public void accelerate(double acceleration, double deltaTime) Vector2f accel new Vector2f(0, (float)(acceleration)) If power is negative, we want to go backwards. if(acceleration lt 0) accel.setTheta(angle 90 180) else accel.setTheta(angle 90) velocity.x (accel.x deltaTime) velocity.y (accel.y deltaTime) In the doPhysics method, is where I calculate the friction. If I remove the friction calculations, the two values printed from the unit test are equal. private static final float friction 1.0f 0.96f private void doPhysics(double deltaTime) Save the velocity before applying friction. Vector2d velBefore new Vector2d(velocity) Then apply friction, with deltaTime. velocity.x (velocity.x friction) deltaTime velocity.y (velocity.y friction) deltaTime And then calculate the average of the friction before and after friction and factor in deltaTime double realVelX ((velBefore.x velocity.x) 0.5) deltaTime double realVelY ((velBefore.y velocity.y) 0.5) deltaTime Add the calculated velocity. position.x realVelX position.y realVelY I hope someone can see what I am doing wrong. I would really like my physics to be frame rate independent and simple enough for me to understand.


How are real world car characteristics translated to in game? I am just entering the world of game development, starting with the racing genre of games. Let me clarify that this question is not about car modelling or external detailing it is about the way a car drives, handles, and the way it feels (how heavy or torque y it is, or how fast and nimble it is, the way it moves in place when you hit the brakes, etc.) in game. I am looking to understand the process game developers take to translate real world car characteristics and physics into in game cars. I am not talking specifically about simulation games I'm including even arcade games where driving a muscle car feels very different from driving a tuner, or a sports car, or super and hyper cars. Questions such as the following arise (1) Do developers have get their hands on a car physically in order to be able to map it into an in game car? When they drive it around, what metrics are they looking to capture so their in game car can feel as true to the real one? (2) What if they can't get a physical car, or if the car is a concept with no drivability? What metrics, data and telemetry should the car manufacturer supply in order for the car to be represented in game? (3) Within cars of the same kind, such as muscle cars, how do developers ensure that a Ford Mustang, a Dodge Challenger, a Chevrolet Camaro, all feel sufficiently distinct from each other in game? How do they ensure a Porsche 911 Turbo, a 911 GT3, a 911 GT2 all feel different, just as the real cars do?


Cocos2dx Chipmunk Fully elastic collision between moving bodies I'm using Cocos2dx and the built in Chipmunk physics engine, and currently I've got my PhysicsBodys' materials set up with Density 0 Restitution 1 Friction 0 in order to get fully elastic collision, and keep moving bodies moving at a constant speed. This works great if they collide against a static element, like a wall, not so much if they collide with other moving objects. I'm moving these bodies by applying an initial force Vec2 velocity moveDirection.getNormalized() moveSpeed myPhysicsBody gt getVelocity() Vec2 newForce myPhysicsBody gt getMass() velocity deltaTime myPhysicsBody gt applyForce(newForce) So I'm guessing that even though their materials would result in fully elastic collisions, the moving objects both carry an impact force, this modifies the resulting force into one with different magnitude? All these moving bodies have the same mass. Currently I'm manually catching the impact start and manually generating the resulting force in the right directing, and using the object's speed to apply it with the same previous magnitude, effectively overriding Chipmunk's collision resolution. Is this the best way to do this, or can I configure my bodies in a way that allows Chipmunk collision resolution to achieve the same effect? I'm a bit rusty on my physics.. heh..


Strange behavior of RigidBody with gravity and impulse applied I'm doing some experiments trying to figure out how physics works in Unity. I created a cube mesh with a BoxCollider and a RigidBody. The cuve is laying on a mesh plane with a BoxCollider. I'm trying to update the object position applying a force on its RigidBody. Inside script FixedUpdate function I'm doing the following public void FixedUpdate() if (leftButtonPressed()) this.rigidbody.AddForce( this.transform.forward this.forceStrength, ForceMode.Impulse) Despite the object is aligned with the world axis and the force is applied along Z axis, it performs a quite big rotation movement around its y axis. Since I didn't modify the center of mass and the BoxCollider position and dimension, all values should be fine. Removing gravity and letting the object flying without touching the plane, the problem doesn't show. So I suppose it's related to the friction between objects, but I can't understand exactly which is the problem. Why this? What's my mistake? How can I fix this, or what's the right way to do such a moving an object on a plane through a force impulse?


Rotation of a 3D ball on a plane This used to be on the physics stack exchange but I was told to put it here I'm making a game (with physics) and I have a 3D ball rolling down a flat plane. It moves perfectly fine, but the rotation is messed up. It seems way too fast, and the axis seems to be all wrong. Here's the code that runs every tick (20 times per second). (normal is the normal to the plane, acceleration is gravity vector projected onto the plane, in m tick2, and velocity is the velocity in m tick.) vec3 rotationAxis normalize(cross(normal, acceleration)) quat newRotation rotate(oldRotation, length(velocity) sphereRadius, rotationAxis) rotate by v r radians about the rotationAxis I'm not sure why this doesn't work, since according to angular mechanics, v r and v t r (and t 1 since velocity is in meters tick). Am I doing something wrong? Why is the rotation so much faster than it should be? And is my axis of rotation correct? Rephrased in a more physics way, is this correct in 3D hat x frac hat N times vec a hat N times vec a Delta theta textrm about hat x frac v r Delta t And if it is correct, then what s wrong with my code?


Infinite ball bouncing problem (Unity) I am trying to develop a basic Breakout game using this tutorial using Unity 5. But the ball starts to bouncing infinitely very easily. I cannot understand why this happenes. In my physics knowledge starting an infinite bounce is very hard, and even impossible. To return the ball to same position after bouncing we must send the ball with zero degrees with the vertical axis. To send the ball with zero degrees with vertical axis we must receive the ball with zero degrees with the vertical axis. To receive the ball with zero degrees with the vertical axis we must send the ball with zero degrees, and so on. We can send a ball with zero degrees only in initial ball throw. In all the other cases there must be an angle which is not equal to zero. Am I wrong? I mean the ball does not change its rotation. Ball moves between two plates which are parallel to each other infinitely (for example between paddle and upper wall) I added physics material to ball, paddle and the walls. This material has following settings Dynamic friction 0 Static friction 0 Bounceness 1 Settings of the ball Mass 0.5 Drag 0 Angular Drag 0 Is Kinematic true (I changed to false just before firing) Use Gravity false Settings of the paddle Mass 0.5 Drag 0 Angular Drag 0 Is Kinematic true Use Gravity false


Soft body, where to start learning? I want to ask you about some resources to learn simulating soft bodies, do you know some good knowledge sources? I asking because I want to make car crash simulator, I've made something but it didn't work well.


2D Motocross physics I'm looking into making a 2D motocross bike game with plausible physics. It should look like this For a first try, I've created only the player (a motocross driver) and the map (consisting of only straight lines no curves, to keep it simple). How should collisions between the motocross bike and the track affect the bike's position and velocity? The bike should rotate if only one of the wheels touches the ground and speed up if the back wheel touches the ground. Pretty standard bike game stuff. How do I achieve this behaviour?


Why is my player still moving down when I set its gravity to 0? I'm writing Lode Runner like platformer game. I'm trying to solve player sprite slowly moving down when on ladder by setting player.body.gravity.y 0. I have arcade physics gravity y set to 900 in game config. But game gravity settings seems to override player.body.gravity settings. I even log player.body.gravity.y to console. It shows 0 when player is on ladder. But it still slowly moving down.


Collision shape and Model problem I used BEPUphysics for my XNA 4.0 game , the problem is that I load my model.fbx from into the game then add it to the space of physics engine , but when I change the scaling matrix of my Model then collision did not work , if I keep model scale the same then my model response to collision and every thing look good ! some says to me that your collision shape (it's often box ) that bound your model have to be changed also if the Model changed ? is this true ? (If yes !!! what is this ????)


How to convert strict limit in position into gradual slow down? The player moves a spell object, the spell must stay withing a certain range of the player. The spell is moved using a physics system and it has mass and velocity. Currently when the spell goes out of range of the player it's being moved back into range, this has the effect stopping the spell abruptly at the edge. I want to smooth out this abrupt stop so that it gradually slows down. I tried to apply an easing function but because the time and distance change every frame I couldn't figure out the formula. Is there some sort of physics or easing formula I can use to gradually slow down the spell before it gets to the edge of its range, while at the same time guaranteeing that it never leaves the range? Additional Info The spells range is a circle. I only care about the center of the spell object. Movement forces are continually being applied to the spell.


Inertia in flight simulation using box2d I'm trying to simulate flight using box2d and libgdx. The main problem I am currently experiencing is with inertia since there is no air, the plane looks like it were drifting. I wasn't able how to turn off inertia. I have two ideas Imitate air resistance by applying force Imitate flight using linear velocity without using any box2d physics Are any of these two ways correct? Or maybe there is way to turn off inertia?


Simplified aerodynamics for 3D airplane I'm looking how to implement simple movement for an airplane in 3D in godot, i couldn't find any tutorial or any hints on how to do this, mostly theoric information on a more real flight movement. Any ideas on how to implement this? I'm not looking for realistic physics, just a more arcade type of movement


Phaser 3 How to make 2 object merging after collision (Like Claw Machine) I'm new in Phaser 3. I use Matter.js for physics. I want to create something like Claw Machine I have a claw (top) and prize (bottom) The claw will take a prize from bottom When claw hit the prize, i want the prize drag by claw. Right now i use Matter.js for prize Arcade for claw I confuse how to do it. Any idea?


Can this script be edited to create a "shotgun" type spread when firing? Top down shooter I have this code and I'd like to add a shotgun to the game by slightly modifying the code. I've looked online for any example but everything I find is for FPS not a TDS. void Shoot () timer 0f gunAudio.Play () gunLight.enabled true gunParticles.Stop () gunParticles.Play () gunLine.enabled true gunLine.SetPosition (0, transform.position) shootRay.origin transform.position shootRay.direction transform.forward if (Physics.Raycast (shootRay, out shootHit, range, shootableMask)) EnemyHealth enemyHealth shootHit.collider.GetComponent lt EnemyHealth gt () if(enemyHealth ! null) enemyHealth.TakeDamage (damagePerShot, shootHit.point) gunLine.SetPosition (1, shootHit.point) else gunLine.SetPosition (1, shootRay.origin shootRay.direction range) I have a basic understanding of most of this code. I don't quite understand how shootRay.direction understands transform.forward means always the front of player. As DMGregory stated adding a variable of some sort that runs through a for loop firing multiple different angles (or simply different coordinates if making angle rays is over my head) is the route I first thought of but I cannot find a way to implement it. I'm having issues with understanding how to manipulate ray coordinates because they cannot be changed by floats which is the extent of my current knowledge of problem solving.


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!


Smoothly move between bodies I'm not sure if the title is correct (please comment if it is not). I have a sprite (rectangle body), and I'm applying force on it to make it move from left to right and then go backward. The platform consists of a few rectangle blocks of same size, lined up, with no distance between them . What they form is a perfectly straight line. The platform can be flat or sloped. What I want The sprite moves smoothly forward and backward on the platform. What actually happens The sprite is sometimes clogged at the point it moves from one block to another, even there is no space between blocks at all. Also sometimes at that point a collision is registered. I have tried to search and found something called "internal corners", but have no clue how to fix this problem. Is there a way to get around? Thanks!


Lunar lander why is my descent module crashing I've been reading this awesome simulation of the actual Apollo 17 descent http www.braeunig.us apollo LM descent.htm I've been trying to make my own simulation using Euler integration, with a time step of 100ms. The problem is my descent module is crashing during the first two minutes with a vertical speed of 220 m s. During the initial stage of the descent (braking), the lander is tilted 90 and almost all the thrust is spent in the horizontal component, with no force to counter gravity. In my simulation the vertical speed quickly builds up while the pitch is 80 90 , and then gravity does it job. Here's a trace t 0 s x 0 y 17234.6112 vx 1697.1264 m s vy 20.4216 m s ax 1.2995855485404475 m s2 ay 1.6121564579144938 m s2 pitch 90 throttle 0.1297 fuel 8874.2Kg t 10.015 s x 17062.974621379497 y 16948.14950433809 vx 1710.2669538608811 m s vy 36.64853435841286 m s ax 1.3247309786564347 m s2 ay 1.628484797082333 m s2 pitch 90 throttle 0.1297 fuel 8855.501190599978Kg t 20.019 s x 34239.89169813059 y 16498.912567960208 vx 1723.6514116543285 m s vy 53.026163503416676 m s ax 1.3509707026458686 m s2 ay 1.6456786784409965 m s2 pitch 90 throttle 0.1297 fuel 8836.82291908347Kg t 30.026 s x 51527.03405575163 y 15884.74450896862 vx 1725.5675762461628 m s vy 69.5834660661016 m s ax 0.9584923539027193 m s2 ay 1.663174744204344 m s2 pitch 90 throttle 1 fuel 8756.011226046036Kg t 40.041 s x 68759.3217349438 y 15103.315677459259 vx 1715.7571868391299 m s vy 86.32821281208818 m s ax 1.0003892381595199 m s2 ay 1.6806337716945954 m s2 pitch 90 throttle 1 fuel 8611.841531365935Kg t 50.502 s x 86651.75776002374 y 14107.047450672597 vx 1705.0564069549016 m s vy 104.00697912916615 m s ax 1.0452064683102156 m s2 ay 1.6991809596193168 m s2 pitch 90 throttle 1 fuel 8461.251498809865Kg t 134.865 s x 226365.92349700694 y 5.915270639694082 vx 1602.384872970266 m s vy 225.9485740506923 m s ax 1.382111636427434 m s2 ay 1.224439728661491 m s2 pitch 78 throttle 1 fuel 7246.814359289593Kg FINISHED at t 2.24775 minutes However, in the original simulation, vertical speed never exceeds 20 m s. I don't know how could this be possible, as there's no drag due to atmosphere. And I've coded initial acceleration and velocity values exactly as in this very same page. You can check the original trace here http www.braeunig.us apollo LM descent.pdf Here we can see the Moon's gravity is aprox. 1.5 m s which heavily influences ay in my simulation. However in the real descent trace it was kept to lower values ( 0.1) most of the time, even during the first minute when there was no vertical thrust due to the engine. I must be making very stupid mistakes but right now I can't see where. BTW this is how I update my vars in each step Calculate acceleration as a function of mass, velocity, thrust and gravity ax vx vx (y MOON MEAN RADIUS M) (thrust x mass) ay (vx vy (y MOON MEAN RADIUS M)) g (thrust y mass) This would be the acceleration for a flat moon. Don't work either. ax thrust x mass ay g (thrust y mass) Update velocity as a function of acceleration and time. vx vx ax dtSecs vy vy ay dtSecs Update position x x vx dtSecs y y vy dtSecs Any hint would be appreciated. Thanks in advance.


How to get the point of collision in Separating Axis Theorem? I'm interested in the relatively precise point (not line) of collision for calculating angular velocity on impact for use in a impulse calculation. At first I thought, perhaps naively, that I could use the closest point along the shortest overlapping axis, but closest to what exactly?


Steer a flock towards a target? Like in pikmin? Can a flock be steered towards a target ? I've seen that flocking behavior has the alignement behavior, but can it be directed and steered toward a goal ? http www.youtube.com watch?feature player detailpage amp v BKJyv4uqsWI t 305


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?


Is it a good plan to use 2D physics for a 3D racing game? I am working on a 3D racing game using SDL and OpenGL. I thought it would be easier to use a 2D physics engine, since I really don't need the 3rd dimension. There will be no flying cars or jumps, they will just be stuck to the floor, so I would use 2D colliders and that things to simulate collisions in a plane but render the actual game from a 3D perspective. So the real question is is it possible, is it a dumb idea, what else can I do?


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?


Are there games with player programmable vehicle control behaviour? My question Are there any (space flying driving) games where the player can customize the mapping between player controls and the input to the vehicle actuators engines programmatically? (Yes or no.) Player input gt Control system Vehicle input gt Vehicle model gt Vehicle motion Feedback (optionally) Basically games where the control system in the diagram above is replaceable by custom code. Edit Just found out that Star Citizen plans to implement this to some extent. But my question is if there are any such games today? (Yes or no.) Why I'm asking I'm curious to see what would happen if a game only imposed physical models of vehicles and let players choose how to adjust controls. I've been thinking about this on and off for some time, but never found it implemented. For example, in spaceflight games the default could be a mode where say the roll is automatically stabilized, players could then modify this code to instead take full control over the thrusters, or just tune the aggressiveness of the stabilization down a notch. Since all ships have the same capabilities, this would allow a kind of individual modding posing no fairness problems in multiplayer. I imagine some hardcore players would really like this, and it could be cool if players started sharing trading settings to tune their ships. Maybe even making it possible to trade control systems as in game items. If sufficient signals where exposed through an external interface, it would even be possible to write complete autopilots in your language of choice. I would love to teach automatic control using a game. )


3D Sandbox game Detecting when a block is no longer attached to the ground I've been playing "Ace of Spades" recently, mostly because my son likes that. They have a feature that my son calls "gravity", but I don't know the official name. Anyway, the effect of "gravity" is that if you have a tower, and you remove the last block at the bottom, the game engine detects that the rest of the tower is not connected to the game world ground anymore, and makes the tower fall apart. My question is how do you quickly detect that a part of the game world is not connected anymore (and which part)? While "Ace of Spades" levels are fixed size, an algorithm that also works for "infinite worlds" would be preferred. If that kind of problem has a specific name, I'd like to know that as well, since it helps when looking for possible implementations ... I think this is somehow similar to how a garbage collector works when there is no "path" from the ground to a block, then it is disconnected (garbage).


Understanding Unity3d physics where is the force applied? I'm trying to understand which is the right way to apply forces to a RigidBody. I noticed that there are AddForce and AddRelativeForce methods, one applied in world space coordinate system meanwhile the other in the local space. The thing that I do not understand is the following usually in physics library (es. Bullet) we can specify the force vector and also the force application point. How can I do this in Unity? Is it possible to apply a force vector in a specific point relative to the given RigidBody coordinate system? Where does AddForce apply the force?


Calculating initial velocities given trajectory parabola I'm working on a volleyball game but my maths physics knowledge isn't quite up to par. I need some help with the following problem The player can hit the ball from anywhere on the left of the court into one of three points on the right P x x x The ball travels in a parabola defined by the three points, all of which are known The players X coord and height (Xp, Yp) The point just above the top of the net (0, Yn) (assume the left of the court is negative along the x axis) The point where the ball impacts the ground on the other side of the net (Xi, 0) I need to calculate the initial X Y velocities when the player hits the ball so that the ball, affected only by gravity, follows that parabola. EDIT Alternatively, the velocity magnitude and angle from which the X Y component velocities can be calculated. I'm able to find the function of the parabola using pen and paper but since this involves "saving" equations with unknown variables I have no idea how to translate that to code (how could you have variable a 2b for example if b is undefined?). I'm not even sure if finding the function is necessary for this problem. Any help? EDIT I just came to the realisation that if I can calculate the flight time then I can divide the distance traveled each frame along the x axis and just plug that into the parabolic function to get the ball's y coordinate. I guess that's my next avenue of research.


Is it possible to correctly catch up a particle system simulation based on long delta time between many frames? I have a particle system with a physics simulation integrator based on delta time (elapsed time between frames) which is implemented on the GPU in a compute shader. I also have a frustum culling system implemented on the GPU. The frustum culling gives me the possibility to cull away draw calls and the dispatch calls for the particle simulation. The culling of draw calls works well, I also don't have a problem with culling the particle simulation when the camera is looking away. My problem happens when I want to catch up the particle system simulation when the camera looks back at the particle system after looking away for a while. What I do is accumulate the time passed while looking away, then I resume the simulation using all that accumulated time. The problem with this approach is that if the simulation is anything but a simple constant velocity change in one direction, the simulation just doesn't look the same as if the simulation was playing one frame delta at a time. From what I have read this is a common issue with using time elapsed between frames to simulate physics. What I wonder is if there's a different approach that can actually allow me to correctly play back many seconds of simulation (let's say 20 seconds) the same as if it was played one frame delta at a time?


Calculating distance by force I am trying to predict a ball(sphere) movement. The formula of force which I know is Force Mass Accelaration What I want is how can I get distance or displacement by giving particular force? I want to consider drag, angular drag and friction also included in the equation. Or if it can be vice versa, calculating force needed by providing distance. The equation I could find doesn't include drag and friction, thus they are not as accurate as I needed. Any help in generating the exact formula would be appreciated.


Box2D Citrus Engine Proper Pong Paddles I am creating a pong clone for my first Citrus Engine project using Box2D. I've tried two types of paddles, both do not fully work. 1) Paddle is a dynamic body with a restitution of 1.0 and friction of 0.0. Problem The bouncing ball will move the paddle when it collides. 2) Paddle is a kinematic body type. Problem The paddle will not detect collision with the walls of the game screen. Question How can I create a paddle object that will not be affected by the collision of the ball while colliding normally with the game walls?


Inertial quantities in 3D physics I'm writing a little 3D physics engine and everything is peachy except that to have constraints behave correctly, I'm having to artificially scale up the inertia tensors. Worse the amount that I have to do so seems to vary from constraint to constraint. I'm implementing constraints according to Erin Catto's sequential impulses paper. It does make sense to me that it's trickier to get things to behave well rotationally via discrete time impulses, but not sure what sort of approach to take to improve performance that isn't so hand wavy e.g. would satisfying the constraints at the acceleration level in addition help? Open to any advice, even if it's that there's potentially something fundamentally wrong with my implementation or that I'm being too prissy about not wanting hacky solutions, etc.


Why is the drag force multiplied by the inverse normalised velocity vector? In pure physics texbooks, I'm seeing this formula to calculate fluid drag force It is clearly stated that it should be opposite to the velocity. Now to me that means, in pseudocode fd get drag(v) using the above formula if v lt 0 fd fd That is, if the velocity is negative the drag should be positive, so we invert the returned value. However, in game code, game physics books and tutorials, I see people doing drag v drag.normalise() fd get drag(v) fd drag That is, we multiply the drag force by the (inverted) velocity unit vector. This to me is logic in regard to the sign, but also it scales down the drag force by a factor between 0 and 1. Which one is correct, and why? PS to be noted, normalisation involves square root, multiplications and divisions, so it's more expensive than a conditional check and subtraction.


Should a transform class store a matrix or seperate position rotation scale values? I'm creating a transform class to make storing the transform of individual objects in a scene easier, but I'm unsure on how to do it. I could create one like this class Transform public ... private Matrix4f matrix Easy to concatenate Easy to perform operations on (since the matrix functions already exist) Can store certain information such as the camera projection Difficult to get the individual values such as the position of the object Performing operations in the wrong order can lead to unexpected results (rotate translate rotate results in a very different transform than rotate rotate translate) Lots of memory usage (64 bytes of data for a single precision transform) Or like this class Transform public ... private Vector3f position Quaternionf rotation Vector3f scale Very easy to extract individual values Very easy to change individual values Because the position, rotation, and scale are independent from one another, there is no "correct" order for rotate translate scale Smaller, being only 40 bytes for single precision Cannot store anything beyond position rotation scale Performing operations which require information stores in more than one value (such as strafing, which changes the position but depends on the rotation) are much more difficult to implement I'm not entirely sure how most game engines deal with this. Which implementation should I go with?


How can I calculate force and acceleration? I have problem of calculating the movement of the object. At the moment, I have a vectors calculated from the center of the screen minus the position of the object. direction vector centerScreen positionObject To calculate the new position of the object position(new) position(t) directionVector delta The delta is the time frame rate. Does anyone know how can I modify the above formula to calculate forces and acceleration? I want to have an object pulling other objects towards it.


Simulating Physics dt vs formula I was just wondering, when simulating physics is it usually a good idea to get the time delta from the last frame and apply the relevant motion equations? Something like void simulate(float dt) vel (force m) dt In this case wouldn't there be an accumulated error over time due to precision? For example when trying to simulate a circular motion? Or would it be better to get the entire elapsed time from the beginning, and then apply the motion void simulate(float elapsedTime) vel vel0 (force m) elapsedTime And since this doesn't depend on the previous simulate() steps, it's less likely to cause precision errors? Thanks!


Inconsistent jump height I am doing some physics for a platformer game in MonoGame. The jump height changes based on FPS even though I'm using delta time. When the FPS decreases and gravity is added before movement, the jump height is shorter than usual. How do I keep a consistent jump height at all frame rates? Here's the pseudo code executed each frame velocity.Y gravity dt Move(velocity dt)


How can I make the player slide when he does a 180 degree turn? I'm making a roller skating game and I would like to player to skid or stop moving skating when they try to move in the opposite direction of their current one. But I'm not sure how to go about this. I tried computing the the dot product of the input of the current frame and the last and if the product was less than or equal 0 that must mean the player did a 180 and the player's velocity was stopped. But it did not work, the product was always greater than 0,


Formula Racing Physics in curves (under steer, over steer) I have a working physics code for a let's say WipeOut style vehicle well, closest approximation . Some time next year I would like to do a formula game but am struggling to get to tweak my code to behave anywhere near the way the formula (say, like in F1 GP game that ran on 100 MHz Pentiums) behaves in curves. Visually, think 3D engine and a 3D track (with hills valleys but still a track (not a generic heightmap)). Since the target HW is below 100 MHz and code is written in ASM, we can't use any off the shelf physics engines, but it must be written from scratch (initial prototyping will be done in C for max productivity and understanding of limitations of the physics component). Now, I don't have any issue with the following (already working) non linear acceleration (e.g. each gear range has different constants behavior) hill based acceleration decceleration (how steep hill is) car gets lighter over time (less gas in the tank), affecting acceleration each parameter can have an additional modifier (linear, non linear) applied to it over the time My greatest issue is I can't seem to get the thing to over steer under steer in curves. I want to allow the player to choose several different levels of physics from Arcade, through gradually more realistic features, to a full blown (as far as manageable by me) physics (like in F1GP game). So far, I have these racing physics modes implemented Arcade racing (kinda like in Lotus Outrun) gear specific non linear acceleration (each formula has different characteristics) hill based speed up down (steepness) speed based drag in curves (how quickly car reacts to turning) tire temperature gradually rising (affecting all physics ranges, modifiers and constants) Through trial amp error I found a way how to get the car to turn faster slower based on current speed. It works pretty well, but it won't realistically skid the car away from the track (like F1GP does). Also, nowhere in the code, I actually use any vectors. It's all just constants, valid ranges, and type of applied modifier (none speed up down, linear non linear) that we use on the desired variable, as that's the fastest possible way on given platform (all these values fit into available CPU's registers, unlike vectors that have to be read from slow RAM). So, how does one actually get the car to under steer over steer in curves ? What's the actual physics here ? Rigid Body ? I believe it should be perfectly possible to emulate this feature via 2D vectors (car direction speed) ?


Impact of increasing physics simulation rate I am working one Mini Golf game development using Scenekit (iOS). To fix one of the problem with Scenekit, I have to increase the physics simulation rate by 4 times. Questions What is the impact on the CPU requirements? What are the common advantages and disadvantages of changing the physics simulation rate? What are the expected problems issues with such increase in the physics simulation rate? I would appreciate any suggestion on this topic. Thank you.