_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
6 | 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? |
6 | 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. |
6 | 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 ????) |
6 | How to convert strict limit in position into gradual slow down? The player moves a spell object, the spell must stay withing a certain range of the player. The spell is moved using a physics system and it has mass and velocity. Currently when the spell goes out of range of the player it's being moved back into range, this has the effect stopping the spell abruptly at the edge. I want to smooth out this abrupt stop so that it gradually slows down. I tried to apply an easing function but because the time and distance change every frame I couldn't figure out the formula. Is there some sort of physics or easing formula I can use to gradually slow down the spell before it gets to the edge of its range, while at the same time guaranteeing that it never leaves the range? Additional Info The spells range is a circle. I only care about the center of the spell object. Movement forces are continually being applied to the spell. |
6 | Inertia in flight simulation using box2d I'm trying to simulate flight using box2d and libgdx. The main problem I am currently experiencing is with inertia since there is no air, the plane looks like it were drifting. I wasn't able how to turn off inertia. I have two ideas Imitate air resistance by applying force Imitate flight using linear velocity without using any box2d physics Are any of these two ways correct? Or maybe there is way to turn off inertia? |
6 | 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 |
6 | 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? |
6 | 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. |
6 | Relative Position Rotation calculation I have 2 objects each with a 3x3 Matrix (Orientation) and a Vector3 (Translation). Both are relative to world coordinates. How do I calculate the position and orientation of object B in relation to object A? I'm using the JVector, JMatrix that are a part of the Jitter3D physics library. (http code.google.com p jitterphysics ) Any help would be greatly appreciated! |
6 | 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! |
6 | Lunar lander why is my descent module crashing I've been reading this awesome simulation of the actual Apollo 17 descent http www.braeunig.us apollo LM descent.htm I've been trying to make my own simulation using Euler integration, with a time step of 100ms. The problem is my descent module is crashing during the first two minutes with a vertical speed of 220 m s. During the initial stage of the descent (braking), the lander is tilted 90 and almost all the thrust is spent in the horizontal component, with no force to counter gravity. In my simulation the vertical speed quickly builds up while the pitch is 80 90 , and then gravity does it job. Here's a trace t 0 s x 0 y 17234.6112 vx 1697.1264 m s vy 20.4216 m s ax 1.2995855485404475 m s2 ay 1.6121564579144938 m s2 pitch 90 throttle 0.1297 fuel 8874.2Kg t 10.015 s x 17062.974621379497 y 16948.14950433809 vx 1710.2669538608811 m s vy 36.64853435841286 m s ax 1.3247309786564347 m s2 ay 1.628484797082333 m s2 pitch 90 throttle 0.1297 fuel 8855.501190599978Kg t 20.019 s x 34239.89169813059 y 16498.912567960208 vx 1723.6514116543285 m s vy 53.026163503416676 m s ax 1.3509707026458686 m s2 ay 1.6456786784409965 m s2 pitch 90 throttle 0.1297 fuel 8836.82291908347Kg t 30.026 s x 51527.03405575163 y 15884.74450896862 vx 1725.5675762461628 m s vy 69.5834660661016 m s ax 0.9584923539027193 m s2 ay 1.663174744204344 m s2 pitch 90 throttle 1 fuel 8756.011226046036Kg t 40.041 s x 68759.3217349438 y 15103.315677459259 vx 1715.7571868391299 m s vy 86.32821281208818 m s ax 1.0003892381595199 m s2 ay 1.6806337716945954 m s2 pitch 90 throttle 1 fuel 8611.841531365935Kg t 50.502 s x 86651.75776002374 y 14107.047450672597 vx 1705.0564069549016 m s vy 104.00697912916615 m s ax 1.0452064683102156 m s2 ay 1.6991809596193168 m s2 pitch 90 throttle 1 fuel 8461.251498809865Kg t 134.865 s x 226365.92349700694 y 5.915270639694082 vx 1602.384872970266 m s vy 225.9485740506923 m s ax 1.382111636427434 m s2 ay 1.224439728661491 m s2 pitch 78 throttle 1 fuel 7246.814359289593Kg FINISHED at t 2.24775 minutes However, in the original simulation, vertical speed never exceeds 20 m s. I don't know how could this be possible, as there's no drag due to atmosphere. And I've coded initial acceleration and velocity values exactly as in this very same page. You can check the original trace here http www.braeunig.us apollo LM descent.pdf Here we can see the Moon's gravity is aprox. 1.5 m s which heavily influences ay in my simulation. However in the real descent trace it was kept to lower values ( 0.1) most of the time, even during the first minute when there was no vertical thrust due to the engine. I must be making very stupid mistakes but right now I can't see where. BTW this is how I update my vars in each step Calculate acceleration as a function of mass, velocity, thrust and gravity ax vx vx (y MOON MEAN RADIUS M) (thrust x mass) ay (vx vy (y MOON MEAN RADIUS M)) g (thrust y mass) This would be the acceleration for a flat moon. Don't work either. ax thrust x mass ay g (thrust y mass) Update velocity as a function of acceleration and time. vx vx ax dtSecs vy vy ay dtSecs Update position x x vx dtSecs y y vy dtSecs Any hint would be appreciated. Thanks in advance. |
6 | 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? |
6 | 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 |
6 | 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? |
6 | 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? |
6 | 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? |
6 | 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. ) |
6 | 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). |
6 | 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? |
6 | 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. |
6 | 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. |
6 | 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? |
6 | 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. |
6 | 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? |
6 | 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. |
6 | 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. |
6 | 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? |
6 | 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. |
6 | 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! |
6 | 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) |
6 | 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, |
6 | 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) ? |
6 | 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. |
6 | How do I get realistic sliding contact between objects in a voxel grid? I have a 3D grid of voxels in my game. Entities walk around with simple physics that represents them as an axis aligned bounding box with velocity, mass and acceleration. The way I'm doing collision resolution is fairly simple. Here's some pseudocode function ResolveCollisions() For each voxel that could intersect the bounding box... foreach (Voxel neighbor in VoxelGrid.GetVoxelsIntersecting(this.bounds)) Check a collision between the voxel and the bounding box if (neighbor.Collides(this.bounds)) ResolveCollision(neighbor, bounds) function ResolveCollision(Voxel neighbor, BoundingBox bounds) Compute the contact normal and penetration distance between the two boxes. Vector3 norm, float dist ComputeMinPenetration(neighbor, bounds) Snap the position so its no longer colliding this.position norm dist Reflect the velocity over the normal to perform an elastic collision. this.velocity this.Restitution Vector3.Reflect(this.velocity, norm) This works pretty well for instantaneous collisions and bouncing, but fails for sliding contact. If an entity is sliding across a flat plane of voxels, for instance, it will rapidly bounce, and will sometimes end up colliding with the sides of the voxels instead of the top. How do I get realistic sliding contact between the bounding box and a voxel grid, without bouncing or "toe stubbing?" |
6 | AI control for a ship with physics model I am looking for ideas how to implement following in 2D space. Unfortunately I don't know much about AI path finding autonomous control yet. Let's say this ship can move freely but it has mass and momentum. Also, external forces might affect it (explosions etc). The player can set a target for the ship at any time and it should reach that spot and stop. Without physics this would be simple, just point to the direction and go. But how to deal with existing momentum and then stopping on the spot? I don't want to modify ship's placement directly. edit Just to make clear, the physics related math of the ship itself is not the problem. |
6 | Implementing a motorized hinge joint I have a 2d physics engine, with three boxes "body", "left wing" and "right wing". The wing boxes are connected to the body using a hinge joint. The physics world has no gravity. I'm attempting to rotate the wings around their hinge connection, as if the joint is motorized but I'm not exactly sure how to achieve that. If I exert force with a downward vector on the center of the wings, the body itself flies down. This is undesirable. With an actual hinge motor, only the wings will rotate about the hinge, affecting the body only when they hit it. Which forces should be added to the wings, and at which origin points? I'm using Phaser.io, with P2.js physics, but the question is platform agnostic. |
6 | Spider physics to patrol on platform smoothly when changing direction I have a 3 tile wide platform. I want my spider to hang from the ceiling and patrol this platform left and right. I have dx property for velocity. I want a physics code that shows how to achieve this. I tried this but it is too harsh if (dx lt 0 amp amp !base.isSolid( 16, 1)) dx 1 else if (!base.isSolid(16, 1)) dx 1 What I want spider is to slow down on edges change direction and speed up. |
6 | How do I calculate the forces exerted by a taut wire wrapping 2D objects? Assume I have a physics primitive I am going to call a "wire", wrapped around a 2D environment (as described in this question). Here's an illustration of what that might look like In the example illustration The box is being pulled upwards (held up) by the wire, and the box is pulling the wire downwards. The object on the spring is being pushed downward by the wire, but is also pushing the wire upwards. While I haven't figured out how to implement it yet, assume the wire will slide freely across the points that it is wrapped around. In a 2D physics simulation (ie frame based) how do you calculate the forces (or impulses) to apply to the objects that are attached to or wrapped by a wire like this? As I alluded to in my first question, I imagine that if the only non static object "on" the wire was the mass at the end, then the force would be identical to a fixed length joint between the mass and the point before that on the wire. |
6 | Marble Wheel Game Physics Kinetic vs Static Friction? I've read a bit about the "normal force" modeling of friction here. I gather that it isn't a full picture, but a decent approximation, if it fits the needs of what you are trying to model. It mentions that there's a static friction and a kinetic friction where the static friction is the amount of force that needs to be overcome before an object will begin moving, and then the kinetic friction specifies how much force you need to apply to keep the object moving. For the case of a ball rolling or a wheel spinning, I know that a little bit of force will cause it to roll, while applying a lot of force will cause it to "slip" and lose contact friction with the ground and start spinning. In this case, is it the static friction that determines how much force you can apply to a wheel or a ball before it starts to slip, and then it's the kinetic friction that determines how it acts when it is slipping? |
6 | Lunar lander why is my descent module crashing I've been reading this awesome simulation of the actual Apollo 17 descent http www.braeunig.us apollo LM descent.htm I've been trying to make my own simulation using Euler integration, with a time step of 100ms. The problem is my descent module is crashing during the first two minutes with a vertical speed of 220 m s. During the initial stage of the descent (braking), the lander is tilted 90 and almost all the thrust is spent in the horizontal component, with no force to counter gravity. In my simulation the vertical speed quickly builds up while the pitch is 80 90 , and then gravity does it job. Here's a trace t 0 s x 0 y 17234.6112 vx 1697.1264 m s vy 20.4216 m s ax 1.2995855485404475 m s2 ay 1.6121564579144938 m s2 pitch 90 throttle 0.1297 fuel 8874.2Kg t 10.015 s x 17062.974621379497 y 16948.14950433809 vx 1710.2669538608811 m s vy 36.64853435841286 m s ax 1.3247309786564347 m s2 ay 1.628484797082333 m s2 pitch 90 throttle 0.1297 fuel 8855.501190599978Kg t 20.019 s x 34239.89169813059 y 16498.912567960208 vx 1723.6514116543285 m s vy 53.026163503416676 m s ax 1.3509707026458686 m s2 ay 1.6456786784409965 m s2 pitch 90 throttle 0.1297 fuel 8836.82291908347Kg t 30.026 s x 51527.03405575163 y 15884.74450896862 vx 1725.5675762461628 m s vy 69.5834660661016 m s ax 0.9584923539027193 m s2 ay 1.663174744204344 m s2 pitch 90 throttle 1 fuel 8756.011226046036Kg t 40.041 s x 68759.3217349438 y 15103.315677459259 vx 1715.7571868391299 m s vy 86.32821281208818 m s ax 1.0003892381595199 m s2 ay 1.6806337716945954 m s2 pitch 90 throttle 1 fuel 8611.841531365935Kg t 50.502 s x 86651.75776002374 y 14107.047450672597 vx 1705.0564069549016 m s vy 104.00697912916615 m s ax 1.0452064683102156 m s2 ay 1.6991809596193168 m s2 pitch 90 throttle 1 fuel 8461.251498809865Kg t 134.865 s x 226365.92349700694 y 5.915270639694082 vx 1602.384872970266 m s vy 225.9485740506923 m s ax 1.382111636427434 m s2 ay 1.224439728661491 m s2 pitch 78 throttle 1 fuel 7246.814359289593Kg FINISHED at t 2.24775 minutes However, in the original simulation, vertical speed never exceeds 20 m s. I don't know how could this be possible, as there's no drag due to atmosphere. And I've coded initial acceleration and velocity values exactly as in this very same page. You can check the original trace here http www.braeunig.us apollo LM descent.pdf Here we can see the Moon's gravity is aprox. 1.5 m s which heavily influences ay in my simulation. However in the real descent trace it was kept to lower values ( 0.1) most of the time, even during the first minute when there was no vertical thrust due to the engine. I must be making very stupid mistakes but right now I can't see where. BTW this is how I update my vars in each step Calculate acceleration as a function of mass, velocity, thrust and gravity ax vx vx (y MOON MEAN RADIUS M) (thrust x mass) ay (vx vy (y MOON MEAN RADIUS M)) g (thrust y mass) This would be the acceleration for a flat moon. Don't work either. ax thrust x mass ay g (thrust y mass) Update velocity as a function of acceleration and time. vx vx ax dtSecs vy vy ay dtSecs Update position x x vx dtSecs y y vy dtSecs Any hint would be appreciated. Thanks in advance. |
6 | How are these physics formulas translated to this code? So how exactly does something like v f v i a t translate to something like self.vel self.acc in code? or d v i t frac a t 2 2 translating to self.pos self.vel 0.5 self.acc there seems to be variables missing, and summations happening that aren't part of the formulas. |
6 | 3D Physics Engine Collision Response Solving Simultaneous Collisions via equation I have been implementing a basic physics engine for a small game project I'm working on. It has very specific requirements, so I decided to try and write my own physics engine to meet them. I found this paper, which seemed to be reasonably simple, and provide answers for everything I needed. https drive.google.com file d 0Bze6mKYvrpOKYjdkODVhMTAtM2Q4Zi00NzgyLWE2YzMtN2MwZmQ4NjA3OWMw view?ddrp 1 amp hl en So far I have successfully implemented collision detection (using my own custom algorithm designed to suit my particular requirements), as well as the collision response (See section 2.6.2.1 on page 41 of the paper). I have, however, become stuck on solving simultaneous collisions. The paper provides equations (see section 2.6.7.1 on page 51), but I am unable to understand or implement them. Can someone explain how these are supposed to be implemented? Here is my current understanding of what is presented, and why is must be wrong In terms of implementation, I'm not sure what they mean by "combined contact impulse," as they do not mention to term elsewhere and fail to explain what they are "combining" (Possibly the angular and linear impulse, but I'm not sure how those aught to be combined). I am also not sure how these formulas are supposed to work. It appears in the first equation just sum the the combined impulse (whatever that is), and use that to increase the velocity, but they only add it in 1 k (where k is the number of iteration) size chunks k times. This basically just seems to result in summing the velocities. This is not physically accurate since multiple collision against the same object will be summed resulting in unrealistically strong velocities. I'm even more confused by the next equation. It appears to add r cross n to the rotational velocity, with complete disregard for impulse magnitude. Doesn't make sense ether. The third equation has the same problem as the first. I feel like some kind of integration or transform needs to happen on each iteration that is not shown, but I am not sure what it should be. Please feel free to leave comments asking for clarification. I'm utterly confused, and I would not be surprised if my questions lack a little coherence. |
6 | What would be a good filter to create 'magnetic deformers' from a depth map? In my project, I am creating a system for deforming a highly detailed mesh (clothing) so that it 'fits' a convex mesh. To do this I use depth maps of the item and the 'hull' to determine at what point in world space the deviation occurs and the extent. Simply transforming all occluded vertices to the depths as defined by the 'hull' is fairly effective, and has good performance, but it suffers the problem of not preserving the features of the mesh and requires extensive culling to avoid false positives. I would like instead to generate from the depth deviation map a set of simple 'deformers' which will 'push' all vertices of the deformed mesh outwards (in world space). This way, all features of the mesh are preserved and there is no need to have complex heuristics to cull inappropriate vertices. I am not sure how to go about generating this deformer set however. I am imagining something like an algorithm that attempts to match a spherical surface to each patch of contiguous deviations within a certain range, but do not know where to start doing this. Can anyone suggest a suitable filter or algorithm for generating deformers? Or to put it another way 'compressing' a depth map? ( Push because its fitting to a convex 'bulgy' humanoid so transforms are likely to be 'spherical' from the POV of the surface.) Edit Here is an image diagram rightly suggested that illustrates what I am trying to achieve. Also, I should say since this question was posted I worked a lot more on this problem, and though I never solved how to the get the deformers I did eventually decide that depth maps for this were unsuitable as If the deformed mesh is not complete, it is possible to get texels in the map that are meant to be on the other side of the convex mesh (because they are not obscured by those closer to the camera on the correct side). The efficiency was not as high as I had hoped due to the fact 6 maps were needed per deformation. Not that these were unsolvable, but the other solution, which involved collision testing in kernels running on the GPU, resulted in higher quality results and was much simpler, even though it may not be as fast. I still think this questions problem is interesting though and would be interested in any answers as I am sure there are situations where it would be preferred. |
6 | How can I connect 2D skeletal animation to the physics engine? I'd like to use skeletal animations in my 2D game, and since I already use Box2D as the physics engine, I'd like to enable (but not enforce) ragdoll animations as well. I need some help in figuring out how the Animation and Physics entity components relate to each other. How should data be represented on disk? Should the actual model skeleton be different from the animation? Here's what I currently have in mind each texture has a corresponding Box2D body (forearm.jpg and forearm.body, for example). I also have a separate hero.model file that references the .body files, and several .anim files that reference the model and the textures. The reason I don't think I should reference the textures in the model directly, but reference them in the animation, is so I can have the character blink (for example) its head would be one body, but different sprites can be pasted over it at different keyframes as to make it blink. Should I actually move the limbs while animating? While the character is still alive (and ragdoll should be off), what should I do with the physical limbs? When I animate, should I just render the sprites with the correct transform, or should I actually move the physical limbs to their current position according to the animation? If yes, how can I get over the fact that Box2D doesn't handle moving bodies directly too well? How to enable more complex communication? Architecturally speaking, how should I implement communication between the Animation and Physics components so that interaction is kept to a minimum, but to also be able to do create more complex entities, like for example a wheel on a robot being rendered with the rotation of the physical wheel, while the rest of the robot is rendered according to the animation's keyframes. |
6 | 3D tilt angle for an arrow in archery game How can I calculate the angle of rotation tilt of an arrow in 3D? When I say angle I mean the angle the arrow takes when it flies through the projectile path. I am using logic given in the below link to calculate the location in the 3D space http babek.info libertybasicfiles lbnews nl130 proj3d.htm and also OpenGL for rendering |
6 | What is the logic beyond cube collisions? I am trying to simulate a colliding of two cubes , I actually tried and read a lot for many days but i did not get the idea beyond it,I know how to detect when they collide. Maybe my question is divided for many aspects, How to detect rotation and movement of these cubes after colliding , What is status of two cubes would be ? Sorry if was not clear or dumb, I would thankful if you could help |
6 | How do i calculate the velocity of a sprite after it leaves circular motion? I'm trying to make a game where the character can swing on a rope. I want to know how the velocity of player is calculated when it stops circular motion. Any help would be appreciated. |
6 | How can I simulate the gravity of a sphere instead of a plane? How can I simulate the gravity of a sphere instead of a plane? For a naval warfare game, I wish to implement a surface that simulates a curved plane with horizon. The plane is rendered with water physics, which needs, along with all physical objects, avatars and projectiles, to respond to gravity as a focal point rather than a distributed surface. |
6 | Can I use Havok Physics for free in my game? I found out that Microsoft purchased the Havok physics engine. Where can I get it for Windows Visual Studio 2015 Community? I tried to look around, but I could not find anything for the latest version. There are no download links at both the official website, nor on the Microsoft site. What do I need to do to use Havok in my own game? |
6 | Adding physics to a Blueprint actor in UE4 I am trying to create a dice in ue4 and be able to read off what value it gives. I've made a mesh in Blender and created a texture, imported them and created a blueprint actor and added the static mesh to it. When I start the game the dice just floats in the air and isn't affected by gravity. I have tried just using the static mesh and I can get that to be affected by gravity. However, I need to add scripts to the object so I can give it a random rotation and read its value, so I created a blueprint actor. I've looked online for a way to give this actor physics, nut nothing. Does anyone know how I can add physics to a blueprint actor? Also if anyone has any info on giving the actor a random rotation and reading the value of the dice that would be great. |
6 | Check gap in 3d environnement I am in a 3d environnement, when I jump, i'm calculating the hitPoint of the end jump. I want to know when I jump, if there is a GAP between my initial point, and the end point. But I don't want to set any trigger in the Level Design... My Initial Idea is to do Raycast each 5 6 steps, but I wonder if this is too much cost effective. MayBe it isn't ? |
6 | 2D object move evade obstacle Description Actor int x,y,width,height float speed, angle actor is an object that move around the map every frame, actor change position(x,y) according to it s speed amp angle Problem If Next frame actor A will collide with actor B Then A should turn to what angle to evade B? |
6 | How to handle player input with fixed rate variable fps time step? I've made a system which uses the ideas from "Fix your Time Step" in order update physics. I'm having trouble finding standard methods for dealing with this when user input affects player movement outside of a time step. If we want to integrate player movement within the "fixed time step, variable fps" system, I guess I would have to queue up player actions somehow, when accumulation hasn't yet completed. But then how do I integrate several different player actions within said timestep? IE lets say within timestep of N milliseconds, the player executes a move forward, move right and move backwards, where there is an infinite collidable wall in front. I could always calculate the last input, but in this case, it wouldn't be correct to do so. The player actually should be blocked by the wall, and then moving right and back would move them to the right, and back, to the right of where only processing the last input would lead. Similarly, if all movement was accounted for together, it might result in a player having an impossible vector for the final position, but if all moves were taken independently, there might have been a valid path (ie around a corner). If I process all inputs then the player made during the time step, it could conceivably be costly if they made a million tiny movements (collision check at each movement), though with exact physics (as far as a fixed time step simulation is concerned). Even if we thought the last bullet wasn't that bad, as soon as you add multiple players to the equation, it starts looking really bad, especially with a server. Are my only options to process all actions or only process a subset of them? |
6 | How does a custom physics engine connect to a tile graphics engine? I ve been looking into adding physics to my tile based side scroller game, and it seems like the best option might be to write my own engine to handle things like collisions and gravity due to the simplicity of what it is I need. I mostly understand the math that I need and some of the techniques to get the functionality I want (such as slopes), but the part I'm still missing is how the physics relates to the graphics, as well as how to actually implement that connection. All that I've seen is that physics and graphics are separate, but are updated together (the textures animations change according to the interactions from the physics engine). Aside from that, however, I have very little idea what I'm doing. My question is When it comes to a tile based game, how do you handle physics bodies and their creation? And on top of that, what would be an efficient way to connect the two engines to one another? |
6 | When should I use a fixed or variable time step? Should a game loop be based on fixed or variable time steps? Is one always superior, or does the right choice vary by game? Variable time step Physics updates are passed a "time elapsed since last update" argument and are hence framerate dependent. This may mean doing calculations as position distancePerSecond timeElapsed. Pros smooth, easier to to code Cons non deterministic, unpredictable at very small or large steps deWiTTERS example while( game is running ) prev frame tick curr frame tick curr frame tick GetTickCount() update( curr frame tick prev frame tick ) render() Fixed time step Updates might not even accept a "time elapsed", as they assume each update is for a fixed time period. Calculations may be done as position distancePerUpdate. The example includes an interpolation during render. Pros predictable, deterministic (easier to network sync?), clearer calculation code Cons not synced to monitor v sync (causes jittery graphics unless you interpolate), limited max frame rate (unless you interpolate), hard to work within frameworks that assume variable time steps (like Pyglet or Flixel) deWiTTERS example while( game is running ) while( GetTickCount() gt next game tick ) update() next game tick SKIP TICKS interpolation float( GetTickCount() SKIP TICKS next game tick ) float( SKIP TICKS ) render( interpolation ) Some resources Gaffer on games Fix your timestep! deWitter's game loop article Quake 3's FPS affects jump physics allegedly a reason Doom 3 is frame locked to 60fps? Flixel requires a variable timestep (I think this is determined by Flash) whereas Flashpunk allows both types. Box2D's manual Simulating the World of Box2D suggests it uses constant time steps. |
6 | How to handle physics of moving platforms in a platformer? So after a few hours of searching on the internet, I have yet to find a pleasing answer on how to handle moving platforms in a 2d platform game. So I decided to make a simple prototype where you interact with 2 different platforms, one that moves vertically and one horizontally. I would love some help to dissect and see what isn't working, and how to fix them. I have submitted the .fla file .as file below, accompanied with a link to the playable .swf. The goal is to make the Hero interact with the platforms as if they were solid objects that he can stand on, pushed alongside with, jump on under etc etc. The problems with my prototype are these When you stand on the horizontally moving platform, without moving (not touching any keys), the Hero moves along with platform, but with a slight delay causing hero to slide back a little. When you stand on the horizontally moving platform, and jump, you move along with the platform midair (some games prefer having it like this, but it doesn't feel natural and is not wanted here). Which might be caused by the Hero retaining the velocity on the X axis from the platform. When you jump up to the bottom side on the vertically moving platform, whilst the platform is moving downwards, you sink inside it for a brief second. Hero penetrates through as if the collision was non existent for a moment. When you jump on vertically moving platform, the veloctiy on Y axis is retained, so when you walk off the platform, you fall down at a higher speed. With the speed of the retained velocity, gravity that is added (this is mostly because I cant figure out a way to reset velocity on Y axis to 0 when you land on the platform, without the player freezing midair). I'm a novice programmer so I am sure there are BETTER ways to do this, and I would love to hear them all. Any ideas on how to improve the code or other methods in which you can implement moving platforms into a Tilebased game are welcome. In the end, I am trying to find a solid way to handle moving platforms in 2d platformers. Playable SWF http dl.dropbox.com u 28271061 PlatformerhowtoFLA.html (Move with arrow keys, Jump with X key, Run with Z key) Sourcecode AS file http dl.dropbox.com u 28271061 Platformerhowto.as SourcefileFLA http dl.dropbox.com u 28271061 PlatformerhowtoFLA.fla If you prefer just to read the code through Pastie online http pastie.org 2266764 |
6 | Test if Jump can reach target I have an object that can jump. When it jumps, its Y velocity becomes 600 (pixels second). For up to .2 seconds, it can ignore gravity. After .2 seconds, it begins to accelerate downward at 2100 (pixels second). Independently from its Y velocity, the object can move on the X axis up to 220 (pixels second) or 220 (pixels second). How do I calculate whether or not, with a given starting x y coordinates it can jump to a target x y coordinate? Also, how do I calculate the necessary X velocity to reach its target in the proper amount of time so that it doesn't overshoot or undershoot? |
6 | Calculating spaceship course There is an idea for (soft) sf strategy game following me for a long time but I need to get a grasp of some math before moving further with it. Lets assume there is a spaceship traveling (in space) with some velocity and its engines can generate some acceleration with maximum acceleration much smaller in magnitude than obtainable velocity. Now given the planned use of engine (acceleration in time) I think ti is fairly straightforward to calculate movement of the ship. But the problem I need to solve is reverse given starting position, velocity and desired destination I need to find a plan of engine usage (acceleration over time) that will guide the ship to the destination in minimal time. There may be some complications like The ship can only accelerate in one direction and turning (changing direction) takes time There are some large bodies with gravitational pull that affects ship course The destination point is moving in time for example it is relative to planet or moon orbiting larger body The timing is important for example the ship is flying in fleet and need to arrive on target at roughly same time as her companions Now I do not expect to get ready to use solution but my question is where I could look for clues? What I should study? What similar problems or related algorithms can help? As this is for a game the solution may be simplified and even involve some "cheating" that would not work in real life. |
6 | Is this a correct backward Euler implementation? I want to simulate a mechanic object like this init acceleration a init velocity v init position x loop get delta time dt v v a dt x x v dt I use the velocity (which is the derivative of position) at the end of each time step to approximate the new position. So this should be exactly what the backward euler method does. Do I have an error in reasoning? |
6 | In a Sonic esque platformer, how to tell if the chracter is upside down or not? In a Sonic esque platform game, how do you know if the player's character is currently upside down? Let's say the character is running to the left At a certain point the character will begin to supposedly run on the ceiling. How do I keep track of this since the chracter is touching both the ceiling and the floor of the tunnel?know I need some way to know where the character's feet are positioned, keep track of it and allow this to change when the character is moving fast across curved surfaces. |
6 | How to avoid entities flying far away when tabbing out and then tabbing back in? I'm developing a game which uses a standard Entity Component System. Every frame, the PhysicsSystem runs, which, among other things, updates the position of entities based on their velocity. Something like this execute(delta number, elapsed number) for (let entity of this.scene.query(CT.Transform, CT.Physics)) let transform entity.get(CT.Transform) let physics entity.get(CT.Physics) let movementIncrement physics.direction.multiply(delta physics.friction physics.speed) physics.velocity physics.velocity.multiply(1 delta physics.friction).add(movementIncrement) transform.pos transform.pos.add(physics.velocity.multiply(delta)) This works fine, except there's an issue. When the user switches to another tab, waits some time (let's say 5 seconds), and then tabs back in, sometimes the entities instantly fly away so far that they fly off the map and out of bounds. I'm not sure why this would happen, as it never happens during normal gameplay. Something to do with the tab becoming inactive for a time, and then active, seems to cause this issue. I suppose a possible solution is to quot pause quot the game if the tab loses focus, but I rather the game keep running in the background unless the user manually pauses by hitting escape. Does anyone know why this is happening? The rest of the game continues functioning normally, it's just the entity positions fly away for some reason. |
6 | Box2D Asteroids Like Spaceship Physics I'm new to Box2D (JavaScript) (and the world of physics mathematics) so I'm having a hard time working out the methods I need to use to make a spaceship act like it does in the classic arcade game Asteroids. I've tried varying methods and nothing works quite right (as I obviously don't understand what I'm doing). For example, in Asteroids you can rotate the ship but it turns at a constant rate and won't continue to spin after you let go of the key, unlike the rest of the ship's physics. So I tried SetPositionAndAngle(position, angle 0.1) as an example to make the ship turn without having it rotate after key up, however when I then press the up key to make the ship go forward, it turns left as well as going forwards (via ApplyForce). Can anybody give some tips on how I should be dealing with Asteroids type spaceship physics? |
6 | How do I implement friction in a billiards game? I'm having trouble implementing friction in a billiards game. Currently, the ball only slows on collision with the edges, but I also want some friction with the background. How can I implement friction? (I'm using PhysicsJS.) |
6 | Where to start for implementing vehicle physics? A little background for myself. I am relatively experienced with 3rd part physics engines such as Havok, Box2D, Bullet and have successfully integrated them in custom engine(s). I have also made a simple physics engine by following a few known books. Now I am interested in diving into vehicle physics. There are a couple of books that skim over the topic but do not go over in enough detail for me to grasp anything useful. So I would like to know of good books resources that are not too heavy (by that I mean a book that is pure vehicles and made for engineers rather than game developers) that help me get started on vehicle physics. Here get started at least guide me through creating a simple vehicle in 3D with modern features found in most games (suspension transmission etc.) Note I searched for a similar question but did not find one, but if one exists, please post the link and feel free to close the question. |
6 | CGVectorMake to move SKNode at a certain speed towards the middle of screen? I am trying to launch my ball sprite towards the middle of the screen at the same speed every time I launch it. let vel CGFloat 1000 dx size.width 2 ball.position.x dy vel size.height 2 ball.position.y ball.physicsBody?.velocity CGVectorMake(dx, dy) This works in that it does launch the ball towards the center of the screen but at differing speeds depending on where the ball starts from. |
6 | Numerical differentiation to calculate size of circular buffer I'm using Allegro 5 to create a software generated "motion blur" effect for my 2D sprites. I basically just have a boost circular buffer of some length which holds "snapshots" of the sprite going back in time. Each render cycle a new "snapshot" of the main sprite is pushed onto the front of the buffer, and the last is popped off the back. The "snapshots" are then rendered with alpha values scaled by how old far back in the buffer they are. To save on CPU power I'd like to have the circular buffer dynamically resized so that the length of the trail is proportional to the object's velocity, i.e. don't store and push back lots of snapshots for trail sprites that won't be needed anyway because the object is moving too slowly. The inputs I have to the data structure that holds the main sprite and its associated effect buffer are just the dx and dy values of how much its position vector changed since the last update cycle of the game logic. So I'm looking for a suggestion for an algorithm that can use that to increment decrement some kind of unsigned counter that can be used to resize the buffer proportional to velocity. |
6 | Detecting overlap with Phaser P2 physics In a 2D platformer, I'd like to implement a ladder. I have collision working between the player and ground tiles. Now I would like to be able to detect when the player walks through a ladder tile (which can be one of three tile indices). When the player is overlapping a ladder and up is being pressed, the climbing state would be set. Ideally, I'd like to get a callback when this happens. It seems that the overlap method from Arcade physics is not available in P2. What is there instead to implement overlap detection? |
6 | Physics for movement in a topdown 2d game? I'm implementing player movement for a simple topdown game, how would I handle more "advanced" concepts in physics to make my player movement feel more natural? Right now I have something like this void update(double delta) dx dy 0 if (left) dx 1 if (right) dx 1 if (up) dy 1 if (down) dy 1 if (dx ! 0 dy ! 0) x dx delta y dy delta How would I go about implementing things like friction, acceleration, drag, and so on? |
6 | Best physics engine for OpenGL ES (different implementations)? Can you recommend a good physics engine which is easily portable between WebGL and other OpenGL ES implementations like in Android and iPhone? I don't want a game engine. Only the physics part. |
6 | LOVE Physics Joint Stretching After asking a similar question yesterday I've come across another problem with using joints in box2D LOVE and trying to create a weighted chain. Everything is set up as follows, I've tried to remove most of the fluff Each link is created as a body shape pair then joined together and added to a links table. for i 1, segments, 1 do link link.body love.physics.newBody(world, xpos, ypos, "dynamic") if (i segments) then link.shape love.physics.newCircleShape(endlink radius) Ending link else link.shape love.physics.newCircleShape(link radius) end link.fixture love.physics.newFixture(link.body, link.shape) Fix bodies to shapes table.insert(links,link) ypos ypos link distance end Links are joined together using rope joints to allow for some springy ness for i 2, links, 1 do x1,y1 links i 1 .body getPosition() x2,y2 links i .body getPosition() links i 1 .join love.physics.newRopeJoint(links i 1 .body, links i .body, x1, y1, x2, y2, link distance, true ) end The player controls the first element of the chain and holds the table of links, its created as follows local body love.physics.newBody(world, 300, 100, "kinematic") local shape love.physics.newCircleShape(3) local fixture love.physics.newFixture(body, shape) local chain chain.new(world) Joined to the chain x1,y1 body getPosition() x2,y2 links 1 .body getPosition() join love.physics.newRevoluteJoint(body, links 1 .body, x1, y1, x2, y2, true ) The player tracks the mouse cursor, determines a velocity and moves towards it by setting the linear velocity of the first chain element body setLinearVelocity(velocity.x, velocity.y) And this very nearly works, you can pull the chain around quite nicely using the mouse (directing the top pink element), however if you keep spinning the chain it begins to stretch and pull away from the first element Any ideas on how to solve this? I've tried using different joints and parameters, adding a reinforcing joint from the first link to the last, adjusting body weights and altering the update iterations but can't seem to find anything effective. Many thanks. |
6 | 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! |
6 | How does one avoid the "staircase effect" in pixel art motion? I am rendering sprites at exact pixel coordinates to avoid the blurring effect caused by antialiasing (the sprites are pixel art and would look awful if filtered). However, since the movement of the objects involves variable velocity, gravity, and physical interactions, the trajectory is computed with subpixel precision. At large enough screenspace velocities (v t larger than 2 or 3 pixels) this works very well. However, when velocity is small, a noticeable staircase effect can appear, especially along diagonal lines. This is no longer a problem at very slow screenspace velocities (v lt lt 1 pixel per second) so I am only looking for a solution for intermediate velocity values. On the left is the plotted trajectory for a large velocity, obtained by simple rounding of the object coordinates. In the middle you can see what happens when velocity becomes smaller, and the staircase effect I am talking about. On the right, the locus of the trajectory I would like to get. I am interested in algorithm ideas to filter the trajectory in order to minimise the aliasing, while retaining the original behaviour at large and small velocities. I have access to t, instant position and velocity, as well as an arbitrary number of previous values, but since it is a realtime simulation, I do not know about future values (though if necessary, an estimation could be extrapolated under certain assumptions). Note that because of the physics simulation, sudden direction changes can also happen. |
6 | Speed limit for Newtonian spaceships? I am working on a game based around Newtonian physics. Therefore there is no drag and therefore a ship will keep accelerating indefinitely if there is no counter force acting on it. This is being built within Unreal Engine and it is entirely based on physics thrusters (i.e. "Add Force at Location"). For gameplay purposes I'd like to implement a "speed limit". Consider a simple seek steering behaviour. Ship A is pursuing Ship B. Ship A reaches the "speed limit" at time t0. Ship B changes direction at time t1. If I calculate the new direction at t1, and then "cap" the speed at time t1 1 frame, Ship A will continue on its original direction, because accelerating towards another direction would make its total linear velocity greater than the speed limit. If instead of calculating the "global" instantaneous velocity I only calculate the projection of the velocity vector along its forward axis, then it works. However, there are some fringe cases. For example if the new direction is almost orthogonal to the velocity vector, then that means that its projection on the forward axis will be very small in magnitude. The ship will thus reach speeds well above the limit, only to have a "hard brake" when the velocity projection reaches the limit on its forward axis. Which other methods could I use to limit speed? I thought about removing a software based limit altogether and just make sure that the ship is braking whenever it is close to the limit. While more realistic, I'm afraid it might look less interesting. |
6 | Client side prediction in 2D rigid body physics I'm currently working on 2D rigid body physics multiplayer game using Matter.js for physics (both the client and server side) and Phaser3 for rendering. Both the server and the client run the simulation and the server is authoritative. The whole game consists of multiplayer players (who can collide with each other) and objects (boxes, balls, etc). For now, I'm working on the client side prediction and while I understand the main concept, I just can't get it right. Every game tick I gather the client inputs, store them locally, timestamp them and send to the server, while at the same time I start moving the player forward (by applying force). When the server receives the inputs, it processes them (by applying the same forces to the player). The server then sends the current state (coordinates, velocity, rotation, last processed input timestamp, etc) to all players at 20hz. This is the part where it gets tricky. What I currently do, is I force the player to the coordinates sent from the server and apply the same velocity (both X and Y). After that, I remove all locally stored inputs which are older than the last processed input and apply them instantly in a single frame, by doing multiple physics steps. With low latency (20 30ms) it works out quite well, with some jittering when rapidly changing the player direction or when I'm colliding with other players objects, but with higher latencies 70 110ms, the prediction goes completely off. I can see the player constantly being pulled back and forth and the whole game becomes unplayable. I can't wrap my head around, what exactly am I doing wrong? Is client side prediction even the correct way of handling this sort of thing in a rigid body physics based game? Also, I turned off state updating from the server and noticed that the position in the server and locally sometimes goes completely off, for example when I'm jumping, running and quickly changing direction. I believe that means that the physics engine is not deterministic? |
6 | Fixed timestep game loop, why interpolation This is a very standard way of doing a fixed timestep game loop, where you just accumulate time from the previous frame and consume it in discrete steps with the physics engine while ( accumulator gt dt ) previousState currentState integrate( currentState, t, dt ) t dt accumulator dt A lot of articles suggest that with the residual lag we should do an interpolation between the previous update and the current one, BUT it does not make any sense to me! If you have residual lag it means that you still have some time to catch and you should EXTRAPOLATE the current state. Why would you ever do an interpolation with the previous state? |
6 | Run a physics simulation on both client and server? I'm implementing a multiplayer asteroids clone to learn about client server network architecture in games. I have spent time reading GafferOnGames and Valve's publications on their client server tech. I am having trouble with two concepts. Currently I have an authoritative game server simulating physics with box2d and sending out the state of the world to clients about 20 times per second. Each client keeps track of the last few snapshots it received and lerps between two states to smooth out the movement of sprites. However it's not that smooth. It can be smooth for a while, then jerky a bit, then back to smooth, etc. I have tried both TCP and UDP, both are about the same. Any idea what my problem might be? (Note I implemented this for single player first, and the sprite movement is perfectly smooth at 60fps when updating the physics world only 20 times per second). In order to solve the first problem I thought maybe the client should run a box2d simulation as well and just update the positions of its sprites to match the server snapshots when they don't match. I thought this might be smoother since my single player implementation is smooth. Is this a good idea? Even if it won't fix the above problem, is it necessary for client side prediction? For example, if a player attempts to move their ship, how will they know if they hit an asteroid, wall, or enemy ship without a physics simulation? It seems like their ship would appear to pass through the object it should collide with before they receive a snapshot from the server that says they hit the object. Thanks! |
6 | Simple 3D particle gravity in javascript? I'm trying to do some simple gravity handling in my 3D environment (I'm using three.js). I've got some code, but it doesn't work. I'm hoping it's just a silly bug somewhere. Note This is a cross question from stack overflow since I've got no responses function handleGravity() for(var j 0 j lt spheres.length j ) for(var i 0 i lt spheres.length i ) var r1 new Array( spheres j .position.x, spheres j .position.y, spheres j .position.z) var r2 new Array( spheres i .position.x, spheres i .position.y, spheres i .position.z) var r12 new Array(r2 0 r1 0 , r2 1 r1 1 , r2 2 r1 2 ) var r12UnitVector new Array( r12 0 Math.abs(r12 0 ), r12 1 Math.abs(r12 1 ),r12 2 Math.abs(r12 2 ) ) var m1 masses j var m2 masses i var r12Squared r12 0 r12 0 r12 1 r12 1 r12 2 r12 2 var a12 new Array( (gravConst m2 r12Squared) r12UnitVector 0 , (gravConst m2 r12Squared) r12UnitVector 1 , (gravConst m2 r12Squared) r12UnitVector 2 ) velocities j 0 a12 0 timePassed velocities j 1 a12 1 timePassed velocities j 2 a12 2 timePassed If you can see anything wrong with it, or give me any tips on using JavaScript to simulate many particles in a 3D environment most efficiently (I'm very new to physics simulation), that would be awesome! |
6 | Channelling an explosion along a narrow passage I am simulating explosions in a 2D maze game. If an explosion occurs in an open area, it covers a circular region (this is the easy bit.) However if an explosion occurs in a narrow passage (i.e narrower than the blast range) then it should be "compressed", so that it goes further and also it should go around corners. Ultimately, unless it is completely boxed in, then it should cover a constant number of pixels, spreading in whatever direction is necessary to reach this total area. I have tried using a shortest path algorithm to pick the nearest N pixels to the origin avoiding walls, but the effect is exaggerated the blast travels around corners too easily, making U turns even when there is a clear path in another direction. I don't know whether this is realistic or not but it is counter intuitive to players who assume that they can hide around a corner and the blast will take the path of least resistance in a different direction. Is there a well known (and fast) algorithm for this? |
6 | Implementation of a quaternion based hinge constraint I'm trying to implement a hinge joint between two rigid bodies based on Lagnange multipliers, s.t. constraint functions to be constraints on quaternions, which describe bodies orientation, itself. It's more natural than describe constraints in terms of some vectors rigidly connected with bodies as it is just implicit quaternions. Plus quaternions should handle the problem of bistability of "vectorial constraints". It is essential to write the correct constraint functions. It seems that I found the correct constraints but something goes wrong (later). Tell me, please, if I do something wrong or miss something. Let us concentrate just on unlimited hinge rotation of two rigid bodies about some common axis. So we need to get rid of two degrees of freedom. Let q rAconj qAconj qB rB, where qA and qB are usual orientation quaternions (s.t. if a vector V has a coordinates column V' in a frame of a body B (lets name this frame B') then (qB (0, V') qBconj).im is its coordinates column in a world frame (lets call this frame W)), rB is a quaternion which carry out rotation from frame where the axis, bodies rotate about, direction vector has coordinates (0, 0, 1) (lets call this frame B'') to frame B', rA defined by analogy. The hinge constraint would not be violated iff vectorial part of q is collinear with Z axis. I.e. the (coordinate) constraints are just q.x 0, q.y 0. Then differentiating this equations, minding Leibniz rule, unitarity of quaternions and dq dt 0.5 q (0, w) identity we get qdot 0.5 rAconj (qAconj qB (0, wB) (0, wA) qAconj qB) rB and the velocity constraints qdot.x 0, qdot.y 0. Velocities are "decoupled" so to get Jacobian is a matter of simple quaternion multiplication. For convenience while experimenting I just write short functions getC, getCdot by which Jacobian is calculated. I'm quite sure in that part of code 'cause I've tested with "not quaternion version" of getCdot and it works fine. Everything works fine if one of the bodies has an infinite inertia (kinematic body) or (if both bodies are dynamic) if angular velocities are orthogonal or collinear to rotation axis. If angular velocities are in general case simulation blows up. Can you get a tip why is this happening? This is not because of quadratic term (Coriolis', gyroscopic, ...) in the Euler equations I ignore this term for now for the sake of stability. |
6 | Box2d topdown racing game killing "residual" forces I'm making top down race game in GM S with Box2D, the car is controled in unusual way player sets direction and engine's speed, and the car uses them turns to the desired direction and reaches speed. But the question is about the "residual" speed after the turn. Here is what I mean I make rotation by applying torque and move with applying force. I don't have tyres, it's just one plain object. So how can I get rid of this momentum? I'm working in GM S, but I'd like to hear any solution, I can adapt it easily. Movement code var ad angle difference(phy rotation, desiredDir) physics apply torque((angleTorque) sign(ad)) rotate the car dx lengthdir x(spd, phy rotation) dy lengthdir y(spd, phy rotation) physics apply force(phy position x, phy position y, dx, dy) move the car |
6 | How to make the Angry Birds "shot arch" dotted line? I am making a game that includes 2D projectile flight paths like that of Angry Birds. Angry Birds employs the notion that a previous shot is shown with a dotted line "arch" showing the player where that last shot went. I think recording that data is simple enough once a shot is fired, but in my game, I want to show it preemptively, ie before the shot. How would I go about calculating this dotted line? The other caveat is I have wind in my game. How can you determine a projectile preemptively when wind will affect it too? This seems like a pretty tough problem. My wind right now just applies a constant force every step of animation in the direction of the wind flow. I'm using Box2D and AndEngine if it matters. |
6 | Physics not synchronizing correctly over the network when using Bullet I'm trying to implement a client server physics system using Bullet however I'm having problems getting things to sync up. I've implemented a custom motion state which reads and writes the transform from my game objects and it works locally but I've tried two different approaches for networked games Dynamic objects on the client that are also on the server (eg not random debris and other unimportant stuff) are made kinematic. This works correctly but the objects don't move very smoothly Objects are dynamic on both but after each message from the server that the object has moved I set the linear and angular velocity to the values from the server and call btRigidBody proceedToTransform with the transform on the server. I also call btCollisionObject activate(true) to force the object to update. My intent with method 2 was to basically do method 1 but hijacking Bullet to do a poor man's prediction instead of doing my own to smooth out method 1, but this doesn't seem to work (for reasons that are not 100 clear to me even stepping through Bullet) and the objects sometimes end up in different places. Am I heading in the right direction? Bullet seems to have it's own interpolation code built in. Can that help me make method 1 work better? Or is my method 2 code not working because I am accidentally stomping that? EDIT Another problem with method 1 I just noticed is that the collision response will be way off for collisions against non synchronized objects. Kinetic bodies kind of shoot stuff to infinity sometimes since they can't be knocked back. |
6 | What in the BOTW game engine makes physics behave wildly when certain actions are triggered during bullet time? What in the BOTW game engine makes physics behave wildly when certain actions are triggered during bullet time? https www.youtube.com watch?v dXKsTrwZ6XY Also, what can you do to prevent it? Is this problem unavoidable when you include bullet time? |
6 | Time complexity of solving constraints in physics engine Erin Catto mentioned in a talk that solving constraints precisely requires cubic time and quadratic space. What algorithm is he talking about when he mentions cubic time? pdf of slides with following quote We can model and program our constraints perfectly. Good enough to drive a robot arm on an assembly line or launch a satellite into space. Unfortunately for games, we do not have enough cycles to solve constraints accurately. Solving constraints precisely requires cubic time and quadratic space. For games we make due with linear time and space, so we are constantly wrestling with our solvers. The better you understand constraint solvers, the better chance you ll have of creating robust simulations in your game. |
6 | How do I program a fan in a platformer game? Fan physics I have a platformer game and want to have fans in it that blow in a given direction and if the player presses the jump button they can go even further. How do I do this? side note I am working with godot engine EDIT My character moves on the two axes using two variables, both multiplied by speed move dir and y velo. gravity affects y velo and the arrow keys affect move dir |
6 | Wall collision response results in jittery physics I have the following game loop while true HandleInput() Update() PhysicsEngine.HandleCollisions() PhysicsEngine.Integrate() Render() For now, HandleCollisions is simply negating the velocity vector of the player. The problem is that if I hold the button to walk forward this results in a jittery screen flashing between the render of the forward walk and the backward walk. How can I smooth it out so that it feels like the player has stopped even if I am still pressing the button ? From what I have found on the internet, Unity's Rigidbody.MovePosition solves this problem, but I was not able to find its implementation online. One thing that I thought about, but am not sure if it is the solution is the following. Find distance of penetration in the HandleCollisions function In the same function move object this much Change velocity to (0,0,0) The problem here is that from my understanding the Integration step should be the one doing the movement and I should only be changing velocity. If that is correct, then I have no idea how to solve it. edit removed architecture tag |
6 | Numerical stability in continuous physics simulation Pretty much all of the game development I have been involved with runs afoul of simulating a physical world in discrete time steps. This is of course very simple, but hardly elegant (not to mention mathematically inaccurate). It also has severe disadvantages when large values are involved (either very large speeds, or very large time intervals). I'm trying to make a continuous physics simulation, just for learning, which goes like this time get time() while true do new time get time() update world(new time time) render() time new time end And update world() is a continuous physical simulation. Meaning that for example, for an accelerated object, instead of doing object.x object.x object.vx timestep object.vx object.vx object.ax timestep timestep is fixed I'm doing something like object.x object.x object.vx deltatime object.ax ((deltatime 2) 2) object.vx object.vx object.ax deltatime However, I'm having a hard time with the numerical stability of my solutions, especially for very large time intervals (think of simulating a physical world for hundreds of thousands of virtual years). Depending on the framerate, I get wildly different solutions. How can I improve the numerical stability of my continuous physical simulations? |
6 | Calculate gears rotation for a realtime simulation I'm trying to do a game with real time simulations of gears. There is a big Gear with inside a smaller gear. I managed to draw gears with different diameters but equal size teeth, but if i try to move the smaller one inside the bigger one the movement is odd. See the animated gif The biggest gear is in center C1 and the small in the center C2. I calculate C2 position in this way C2.x C1.x C1 RADIUS C2 RADIUS) cos(t) C2.y C1.y C1 RADIUS C2 RADIUS) sin(t) for t that goes from 0 to TWO PI in n steps. I apply as rotation the angle t, but maybe it is wrong and i have to calculate another rotation for get a perfect joint. EDIT I am using radians for rotations and I think this is OK. My main problem is that I want to achieve a perfect joint between teeth like this example. My teeth are overlapping in some odd way. EDIT a working example can be found here http www.openprocessing.org sketch 83665 |
6 | My pool balls often jump around when there are two or more balls colliding touching I'm working through the book 'Introduction to Game Physics with Box2D' and I've created a little pool game with the example code. Despite the name, there is NO box 2D used in this particular exercise. The example in the book can be seen in this video by the author which only consists of the cue ball and 8 ball. This all works well. I've written my own version from scratch (using SDL instead of DirectX), using the code in the book as a guide. When I limit it to two balls, everything works great. When there are more than two balls, things are sometimes problematic in a way I can't predict. Breaking can be fine on one run, or it can cause the balls to 'jump' and flicker as they move presumably looking for empty space. Generally, problems occur when there are more than two balls in a collision. I've read around and it seems that I need to perform more 'iterations' to get closer to the correct result, but the code that I'd learned will work the same regardless of the number of times it is performed it sets the positions of any overlapping balls so that they are barely touching. I've tried changing it so it 'pushes' the balls slightly in the direction of the collision normal, with no success. Here's the relevant code bool BallManager ballBounce(Ball amp ball1, Ball amp ball2) float r static cast lt float gt (ball1.diameter ball2.diameter ) 0.5f Calculate direction of relative velocity. Vector2 v ball2.velocity ball1.velocity Vector2 vhat v.normalized() Calculate relative displacement along normal to collision tangent. Vector2 c ball2.position ball1.position Vector2 n c.normalized() Relative distance along normal to tangent. float cdotvhat dot(c, vhat) Balls don't collide, exit early. float discriminant cdotvhat cdotvhat c.lengthSquared() r r if (discriminant lt 0.0f) return false The distance we want to move ball2 back by. float dist2 cdotvhat sqrt(discriminant) float relativeVelocity 0.0f if (ball2.velocity .length() gt 0.0f) relativeVelocity ball1.velocity .length() ball2.velocity .length() The distance we want to move ball1 back by. float dist1 dist2 relativeVelocity Move balls in reverse direction of velocity to point of impact. Vector2 v1hat ball1.velocity .normalized() Vector2 v2hat ball2.velocity .normalized() ball1.position dist1 v1hat ball2.position dist2 v2hat Adjust ball velocities after reflection. Vector2 vDiff ball1.velocity ball2.velocity vDiff dot(vDiff, n) n ball1.velocity vDiff ball2.velocity vDiff Finally, move balls again to where they should have bounced to. v1hat ball1.velocity .normalized() v2hat ball2.velocity .normalized() ball1.position dist1 v1hat ball2.position dist2 v2hat return true At the moment I'm mainly looking for a pointer in the right direction or suggestions since I'm new to physics programming. |
6 | Problem with impulses in my physics engine I'm currently developing a small 3D impulse based physic engine for a CS project. It uses GJK for collision detection and is kind of stable at the moment. Nevertheless, I'm not satisfied with my collision response as rigid bodies appear to gain more and more momentum with each bounce, although only under some configurations. I use Newton s Law of Restitution (pictured immediately below) for instantaneous collisions with no friction. I checked this formula again and again, and I also checked if the magnitude of the contact normal is 1, and all seems fine. The direction of the bounce and the induced rotation are convincing but the impulse is just sometimes too strong. I think my problem may lie within the impulse application part in my mind, the impulse is the force necessary to separate two touching points of two bodies plus a certain magnitude depending on the coefficient of restitution (0.7 in my tests). I compute an impulse for each detected contact point and apply it at the contact position. For example if a cube falls right to the floor, there will be 4 impulses, each one at a vertex of the bottom face of the cube. For each of the four contacts, I do something like this J computeImpulse(contact) A.applyImpulse(J, contact.pos) B.applyImpulse( J, contact.pos) I'm a bit confused. Is this the correct approach, or should I apply half of the impulse to each body? Or, should I rather apply a fraction of the impulse depending of the mass of the bodies? Or, is the problem just somewhere else (e.g., in the formula)? I don't know if someone has an easy answer for me, as it's a rather specific problem, but thank you for your help. ) |
6 | Are you supposed to be looping through all PhysicsObjects at every step in a physics engine? I am currently making a small 2D game and I am trying to implement some basic 2D physics. I currently have a list of around 100 PhysicsObjects which I loop through every frame in order to update and apply forces to that object based on user input. The basic code is as follows accumulator 0 dt 0.01 while running for each object in PhysicsObjects update object accumulator time between last frame and current frame while accumulator gt dt for each object in PhysicsObjects resolve forces to get new position of object based on dt accumulator dt for each object in PhysicsObjects render the object I was going to resolve the forces and calculate the new position in the update method of each object, but I was told the dt was necessary in order to make the movement and physics independent of frame rate, which is why it is in a separate loop. I also can't update the objects in the physics engine loop as the update method needs to occur every frame. This already seems incredibly inefficient, and I haven't even started to test for collisions or anything else more in the physics engine. Is there a better way to structure this where I don't need to loop through every object again in order to calculate their new position? |
6 | How long does the collision take? I want to simulate a simple force acceleration (rather than impulse velocity) physical world made up entirely of disks and I'm having an irritating problem with my physics. When two disks collide, I can calculate the changes in velocities quite easily using conservation of momentum and conservation of energy. Since this is going to be a force based simulation, I need to calculate the forces to apply. I thought I'd use the momentum impulse equality m v F t Sounds simple, except I don't know what to do with time( t). So I guess the question boils down to this how long does the collision take? Or rather, do the two objects stick together for a period of time ( t)? |
6 | SpriteKit How to jump to specific position? I'm would like to achieve something like Object A will jump to position A in parabolic way. For example I am able to make the object jump but i do not know how to calculate to make the object jump to the precise location. |
6 | Tracking Object Position Firing on a Trajectory How can I calculate the position of an object after "firing" it from a fixed point? I am to create a small game most likely with canvas (pure HTML, JS based) or Adobe Flash in which the player fires objects at other obstacles in order to clear them. |
6 | Bullet objects falling through I have problem with bullet collisions. You can see problem on this video (around 0 18) http goo.gl DiVP8l Objects are "embeded" inside vertical bars that is not correct they should be bouncing like at the beggining of the video. I am using sphere and box as bullet bodies. I have also enabled CCD, that improves stability a little, but problem is still there. Pulsing bars are controlled with this code dist distance I need the bar to change its position in a single frame float g (2 dist) (times.dTime) dTime 1 60 bars i gt GetBulletBody() gt setLinearVelocity(btVector3(0, 0, 0)) bars i gt GetBulletBody() gt setGravity(btVector3(0, speedUpFactor g, 0)) I have constant update rate of physics and world, set to be 1 60 s. |
6 | When should I use a physics engine? Since I found out Box2D, I'm using it for kind of any game like application I try to write, from very small prototypes or small programs to test something, to actual projects. Thanks to it it's so terribly easy to handle anything from collisions, to the actual physics. Sometimes, though, I have some doubts about it if I only have to handle circles or AABB, and don't need advanced physics tools (joints or stuff like that), I think that a physics engine could add a sort of big, unneeded overhead. To reassume my question would you use Box2D (or other physics engines) in a game where physics is really simple (like Super Mario, let's say)? And, if not, why? |
6 | Physics engine recommendation which can simulate pool game correctly? I'm making a pool game like game. This game requires correct (or very accurate) reflective bounces. I tried Box2D and Bullet Physics, but they both have this problem. If there is a wall on top of this image, red line is expected course of a real ball in a pool game. But the engines often shows green line course. Especially, This happens after a slowly moving ball hits the wall. Sometimes a rapidly moving ball get slower suddenly. I'm finding a physics engine which can simulate pool game accurately as much as possible without these problems. Can I get some recommendations? Now I'm digging Newton Game Dynamics, but I am not sure the engine will show what I want. I'm considering the PhysX engine as a next trial, and have to make my own if nothing works. But it's obvious it'll take very long time, so I wish I won't do that. I'll be very appreciated if you save my time. And of course, solution with Box2D Bullet Physics are also welcomed. I am working with C C Objective C on iOS. I attach my configuration with Box2D. Walls static box shape linear angular damping 0.1 restitution 1.0 friction 100 density 10 bullet false fixed rotation false inertial scale 1.0 Balls dynamic sphere shape linear angular damping 0.1 restitution 1.0 friction 100 density 20 bullet true fixed rotation false inertial scale 1.0 |
6 | 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. |
6 | What are the properties of "position, velocity, acceleration, rotation" collectively named? They say naming things is one of the hardest problems in computer programming. They were right. Given the pseudocode below, what is a more appropriate name for this collection of properties? "Course", "Route", "Heading", "Orientation" all don't capture it. class NewtonianStuff lt Needs a better name vec3 position, velocity, acceleration lt What is this group called quat rotation class SpaceShip NewtonianStuff xxxxxx lt What do you call that Perhaps that collection is too abstract. What is the formal name for this collection of properties? vec3 position, velocity, acceleration The best I can come up with is "PositionAndDerivatives", which doesn't really flow. |
6 | Powder games how do they work? I recently found these two gems http powdertoy.co.uk http dan ball.jp en javagame dust My question is How are the physics with so many elements efficiently handled? Am I just severely underestimating modern computing power or is it possible to 'just' have a two dimensional array, each cell of which describes what is placed at the according position and simulate each cell in every step. Or are there more complex things being done like summarising large areas of the same kind into a single data set and separating said set as needed? Are there any open source games like this I could look at? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.