How can I implement large moving "colossus" characters that also act as environmental objects? I'm curious how enormous characters that act both as entities and environments are implemented. I'm thinking of characters like in Shadow of the Colossus which move, but which the player can also move on. It seems these objects would be created as characters, rigged like any character would be with their various animations, but they would also need to be usual physical surfaces that we can walk on. Considering the way characters are handled compared to how static environment is handled physically in most game engines, this could prove problematic, and added to that is the problem of size. So, generalising over engine details (but assuming you have a generic physics character engine, e.g. Unity Unreal) what approach should be taken? Also, screenshot As you can see in this screenshot, the colossus is really big, and the player can walk on it and climb on some parts of it (hairs mostly) And a video of a boss fight here which really shows what this gameplay is all about


Typical Maximum steering angle of a real car I'm building a car sim in Unity3D. I'm trying to set the properties of the car to be as realistic as possible. I can't seem to get a straight answer on Google so I thought of asking here. What is the typical maximum steering angle of a normal passenger car ?


Moving object through nodes in Quadtree I'm working on my own quadtree for use in games for physics (collision detection to be exact) but am unable to move an object from one node to another node. What I'm doing is if some object is to be moved, I'm deleting it from its old position and adding a new object (with same property, such as width and height) to the new position. Is my approach correct or is there any other optimized process to do same? The problem I'm facing is that if I move an object from node 0 to node 3 (both node being children of, for ex., root node) the root node container(I'm using std vector) gets the object but it is not updated in the node 3's container. Any solution to my problem? Though would be happy to try some other method too. Thanks.


Orbital mechanics orbit as a function of time. Universal variable formulation? I am trying to model a two dimensional orbit for a two body Kepler problem but have gotten stuck when introducing the time variable. For a satellite with known semi major axis (a), eccentricity (e), and true anomaly (theta), I have r a (1 e 2) (1 e cos(theta)) How can I calculate theta as a function of time using the Wiki suggested Universal variable formulation method? I have no idea how to implement (am using Python but any algorithm advice much appreciated!) Alternatively, how do I calculate r as a function of time? Note All other orbital elements and masses are available. Also I am trying to come up with a general solution for elliptical, hyperbolic and parabolic orbits. Cheers!


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


Physics in carrom like game using cocos2d Box2D I am working on carrom like game using cocos2d Box2D. I set world gravity(0,0), want gravity in z axis. I set following values for coin and striker body Coin body (circle with radius 15 PTM RATIO) density 20.0f friction 0.4f restitution 0.6f Striker body (circle with radius 15 PTM RATIO) density 25.0f friction 0.6f restitution 0.3f Output is not smooth. When I apply ApplyLinearImpulse(force,position) the coin movement looks like floating in the air takes too much time to stop. What values for coin and striker make it look like real carrom?


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 ?


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


Why not derive velocity from position updates in games? Is there a reason why retrieving velocity of a 3d object in a game engine vs deriving it from position updates is preferable? I am currently polling position at every step and deriving current velocity, however, there is also a "get velocity" option. I already need position but I'm wondering if the velocity in the game engine is preferable for some reason like it has less latency than the derivative.


Making a parent system with euler angles (gimbal lock problem) I have a system where objects can be connected to each other as the parent rotates the child objects will rotate too and child objects themself can rotate too. The system is already working, however, I am doing it with rotation matrices. I want to dynamically simulate angular physics and for that, I would need the angular velocity for which I thought the direct and easiest way would be to get the difference of the euler angles. I am still a beginner with those rotation maths like matrices, quaternions etc. The problem is that the rotation of the children would be local and currently I am just adding the euler angle values (which works fine if I only rotate around one axis). So when I rotate a child on the x axis by 90 degrees and then rotate the parent on the y or z axis the system breaks (y and z should be swapped in this scenario with 90 degrees x rotation) As far as I have understood it the problem could be explained with quot gimbal lock quot . Is there a way to calculate the local euler angles? Or is there in general a better way to achieve what I am trying to do here? I have heard that quaternions also don't save 360 degrees, so that would be also a problem for angular velocity.


Oscillating an object left and right based on it's current orientation I'm currently implementing a fire animation in HTML5 Canvas using the phone's accelerometer. Regardless of the phones orientation, the triangles for the fire move upward. So you can spin your phone around to what ever degree you wish, and the triangles will move towards the sky. My issue is trying to implement an oscillation left and right for these triangles. Before I had the accelerometer hooked up, I just applied an oscillation to the x axis and everything worked fine. Now however because the triangles are moving in what ever direction up is, I need to somehow apply the oscillation to both axis depending on what the orientation of the phone is. Could anyone help me out? I'm using JS for this. Thanks.


Maximum range of projectile fired at given force and elevation I've gone over this again and again, and my result is obviously wrong when viewed in action. Here's the initial formula I converted (first one) http en.wikipedia.org wiki Range of a projectile and here's my C code float CalculateMaximumRange() float g Physics.gravity.y float y origin.position.y float v projectileSpeed float a 45 float vSin v Mathf.Sin(a) float vCos v Mathf.Cos(a) float sqrt Mathf.Sqrt(vSin vSin 2 g y) return Mathf.Abs((vCos g) (vSin sqrt)) Does anyone see what I did wrong?


How to make bird to fly using box2d I am new to Box2D, I have set gravity to 10. How to make an object fly in space even though the gravity is 10. What are the properties I need to set to make object fly? Is there any different approach?


Looking for a peer reviewed article that details the benefits of a physics simulation within interactive media I'm hoping this is the correct place to ask this question as it is video game related and can be seen as a key ingredient in modern game development. Does anyone know of a peer reviewed article that details the benefits of incorporating a physics simulation into interactive media (such as video games)? I can find books with a few remarks in their introduction (no more than a couple of sentences) but nothing substantial.


Physics based dynamic audio generation in games I wonder if it is possible to generate audio dynamically without any (!) audio assets, using pure mathematics physics and some input values like material properties and spatial distribution of content in scene space. What I have in mind is something like a scene, with concrete floor, wooden table and glass on it. Now let's assume force pushes the glass towards the edge of table and then the glass falls onto the floor and shatters. The near realistic glass destruction itself would be possible using voxels and good physics engine, but what about the sound the glass makes while shattering? I believe there is a way to generate that sound, because physics of sound is fairly known these days, but how computationaly costy that would be? Consumer hardware or supercomputers? Do any of you know some good resources videos of such an experiment?


Using Box2D for range detection? I have two entities. One has a sword, one has a bow and arrow. When the bow entity is 100 units away, he needs to begin attacking. Likewise, when the sword entity is 10 units away, he needs to begin attacking. My idea is to create an actual physical body for collision detection and a range body (or fixture?) for range detection. However, I don't want the range body to start pushing and affecting other entities. I simply want to detect when one entity's range body collides with another entity's physical body. Is this the right thing to do and how can I do this with Box2D?


Basic Box2D collision detection I don't understand how to listen for collisions in Cocos2D Box2D. Say I have two dynamic circle bodies. One is very small and the other is relatively large. When the small circle collides w the large circle I'd like to do something (play a sound for example). What's the best way to do this? I'm currently experimenting w the TestPoint method. Something like if(largeCircleBody gt GetFixtureList() gt TestPoint(smallCirclePoint)) collision happened... play sound etc


Game Physics Implementing Normal Reaction from ground correctly I am implementing a simple side scrolling platform game. I am using the following strategy while coding the physics Gravity constantly acts on the character. When the character is touching the floor, a normal reaction is exerted by the floor. I face the following problem If the character is initially at a height, he acquires velocity in the Y direction. Thus, when he hits the floor, he falls through even though normal force is being exerted. I could fix this by setting the Y velocity to 0, and placing him above the floor if he has collided with it. But this often leads to the character getting stuck in the floor or bouncing around it. Is there a better approach ?


How can I implement smooth digging effects in a tile based game? I'm trying to make a Dig Dug styled game where you will be digging into a material. This is going to be a tile based HTML5 game and I have decided to use the Phaser framework. One way to do the digging mechanic is to break the play area into tiles and remove tiles as the player sprite collides. But I would like to have a smooth digging animation physics, so it appears that the player character "carves" out the soil as it digs through. Any tips on how I should do this? Right now I have 15x15px tiles while the player is 45x45px, this sort of fakes the smooth digging I want. Is there a better way?


Is an inertia tensor in local space always diagonal? I'm looking at the implementation of a physics engine and I observe that the inertia tensor of a rigid body, in local space coordinates, is stored as a 3 dimensional vector, rather than a 3x3 matrix, and the description says quot A vector with the three values of the diagonal 3x3 matrix quot . A diagonal matrix is one with all zero off diagonal entries. What I don't understand is why the inertia tensor in local coordinates would be diagonal? Why couldn't it have non zero off diagonal entries?


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


Web workers for HTML5 game physics simulation? A bit related to this question. The idea is to guarantee the same physics behavior as much as possible. Would it be possible to run fixed time step physics on a web worker? The UI would update itself with different variable refresh rate. Has anyone tried such yet?


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


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


How to implement friction in a physics engine based on "Advanced Character Physics" I have implemented a physics engine based on the concepts in the classic text Advanced Character Physics by Thomas Jakobsen. Friction is only discussed very briefly in the article and Jakobsen himself notes how "other and better friction models than this could and should be implemented." Generally how could one implement a believable friction model on top of the concepts from the mentioned article? And how could the found friction be translated into rotation on a circle? I do not want this question to be about my specific implementation but about how to combine Jakobsens ideas with a great friction system more generally. But here is a live demo showing the current state of my engine which does not handle friction in any way http jsfiddle.net Z7ECB embedded result Below is a picture showing and example on how collision detection could work in an engine based in the paper. In the Verlet integration the current and previous position is always stored. Based on these a new position is calculated. In every frame I calculate the distance between the circles and the lines. If this distance is less than a circles radius a collision has occurred and the circle is projected perpendicular out of the offending line according to the size of the overlap (offset on the picture). Velocity is implicit due to Verlet integration so changing position also changes the velocity. What I need to do know is to somehow determine the amount of friction on the circle and move it backwards parallel to the line in order to reduce its speed.


Oblique launch within a game I'm creating a simple game in python that will follow the same logic of DDTank and Worms. The graph is formed by characters. The buildings that will be destroyed are formed by ' ', players are ' ' and the projectile I still did not think the character. For now I did the part that draws the buildings with a random height. But I was thinking the logic of launching projectiles. I learned in physics classes some formulas for oblique launch. So wanted to know if these formulas would fit in a computer program or I would have to invent another logic? Formulas vx v0 . cos ? x vx t v0y v0 sen ? y v0y t g t 2


Do you really have to sync Physics over the network? Let's say you want to create a 2D game where a character can shoot a bullet. You have the same code running on the Client and Server (JavaScript so it's exactly the same code). If the client and the server create the same bullet instance at the same tick X, with the same position, direction and velocity, is it safe to assume that the bullet will end on the same place on both the server and the client? Does the server need to send back the exact position at which the bullet collided, or can the client just predict that as it uses the same physics and same bullet initial data. Can the bullet hit the target on a different tick, or at a different position on the server from the client? My initial thought is that this shouldn't happen, but could this happen because of a different CPU architecture or a different JavaScript engine?


How would one generate a texture for cracks in different materials? I would want to have the ability to simulate different variables like brittleness, or other variables to get varied end results. I would mainly need to generate impact cracks, so it would need to react to different impact angles and speeds. I am using ActionScript3, but general theory answers will be helpful as well.


Collisions between sprites in SpriteKit I'm making a game in XCode using SpriteKit. The game has a player and different types of projectiles that he has to avoid. When the player collides with the projectiles, the score changes and the projectile disappears. However, when two projectiles collide, they kind of bounce away. I want to make that every time two projectiles collide, they act like nothing happened and they keep going in their original path. What should I do? Note This is not the whole code, it's just what matters. import SpriteKit struct Physics static let player UInt32 1 static let missileOne UInt32 2 static let missileTwo UInt32 3 class GameScene SKScene, SKPhysicsContactDelegate var player SKSpriteNode(imageNamed "p1.png") override func didMoveToView(view SKView) physicsWorld.contactDelegate self player.position CGPointMake(self.size.width 2, self.size.height 5) player.physicsBody SKPhysicsBody(rectangleOfSize player.size) player.physicsBody?.affectedByGravity false player.physicsBody?.dynamic false player.physicsBody?.categoryBitMask Physics.player player.physicsBody?.collisionBitMask Physics.missileOne player.physicsBody?.collisionBitMask Physics.missileTwo var missileOneTimer NSTimer.scheduledTimerWithTimeInterval(1, target self, selector Selector("SpawnMissileOne"), userInfo nil, repeats true) var missileTwoTimer NSTimer.scheduledTimerWithTimeInterval(1.2, target self, selector Selector("SpawnMissileTwo"), userInfo nil, repeats true) self.addChild(player) When contact happens func didBeginContact(contact SKPhysicsContact) var firstBody SKPhysicsBody contact.bodyA var secondBody SKPhysicsBody contact.bodyB if ((firstBody.categoryBitMask Physics.player) amp amp (secondBody.categoryBitMask Physics.missileOne)) CollisionWithMissileOne(firstBody.node as SKSpriteNode, missileOne secondBody.node as SKSpriteNode) else if ((firstBody.categoryBitMask Physics.player) amp amp (secondBody.categoryBitMask Physics.missileTwo)) CollisionWithMissileTwo(firstBody.node as SKSpriteNode, missileTwo secondBody.node as SKSpriteNode) else if ((firstBody.categoryBitMask Physics.missileOne) amp amp (secondBody.categoryBitMask Physics.missileTwo)) CollisionBetweenMissiles(firstBody.node as SKSpriteNode, missileTwo secondBody.node as SKSpriteNode) For Player and MissileOne func CollisionWithMissileOne(player SKSpriteNode, missileOne SKSpriteNode) missileOne.removeFromParent() For Player and MissileTwo func CollisionWithMissileOne(player SKSpriteNode, missileTwo SKSpriteNode) missileTwo.removeFromParent() For MissileOne and MissileTwo func CollisionBetweenMissiles(missileOne SKSpriteNode, missileTwo SKSpriteNode) ???WHAT SHOULD I CODE HERE???


Gravity and Jumping in Clickteam Fusion 2.5 So I'm currently building a bare bones functioning game that involves simple platforming. Quite literally a box moving left and right and jumping. I'm using Clickteam Fusion 2.5, and I know there's an option to assign platforming movement to an active object, but I honestly do not enjoy implementing that feature one bit. So instead I'm opting for simply adding or subtracting from the X and Y coordinates of the player object while the left and right arrow keys are held down for side scrolling movement. However, I have yet to figure out how to use this same method for jumping and gravity. I know being able to jump would be running an event that occurs after hitting a certain key, which takes in the current Y coordinate of the player and runs it through a parabolic formula. And then gravity would simply be constantly subtracting from (or I guess in Fusion's case, adding to) the current Y value of the player object while the frame is running. So the question simply is where and how do I implement these things in order to create jumping and gravity. I figure there's a correct syntax for a parabolic formula when creating an event after "jump" is pressed, but for the life of me I can't figure it out. As for gravity, I'm completely lost. I have managed to get down stopping movement when colliding when another object so that is not an issue. Thanks and appreciation in advance.


Do two balls of different mass bounce different heights? There are two balls and the only difference between them is the mass. Both are dropped from the same height on to the floor (static object with infinite mass), would both balls bounce up to the same height, or would the heavier ball bounce higher as it enters the collision with more momentum? From my own derivation it would appear that the calculation reduces down to a simple vector reflection about the contact normal, but it doesn't feel right. Can anyone verify this? EDIT To be clearer, I am looking for a code sample of how to resolve a ball collision against a plane using a collision impulse. Does the collision impulse rely on the ball's mass when colliding with an object of infinite mass?


How to make a character jump? I am currently making a game in C using Direct X 9.0. The game remake is Donkey Kong NES. I have nearly everything completed, but I am having problems with the physics of Mario's jump. I have variables declared for the Y and X co ordinations. I was wondering if there was a simple method of doing this. I have searched high and low for an answer but the answers I have found are either irrelevant or using a different programming language such as XNA. I currently have a bool variable set to check to see if W has been pressed then that will trigger any code to make him jump. I have been messing around such as. if (jump true) Playerypos vel Playerxpos vel Which didn't work that well. I have searched high and low for an answer and now I am desperate, if someone could point me in the right direction to a simple solution. That would be great. Much appreciated for any responses.


What is a good algorithm for generating a linear regression of positions in 3D space? (for getting the direction of a thrown object in VR) I'm trying to get throwing to feel right in my VR game. I don't plan on actually using physics to do this my idea is to accurately determine the lateral direction of the throw, then move the object in the intended direction (with a doctored Y value) at a speed dependent on other factors. The language of the code doesn't matter too much, but I'm using Godot, so something that wouldn't require me to import a bunch of different math libraries (by converting them to Godot's Python style GDScript) would be ideal. It doesn't need to be robust. To give you an idea of what I was thinking, my original plan was to save the position of the grabbing controller every frame while an object is being held, removing old positions if the controller is moving backwards, then averaging out the movement deltas over the last 10 or 15 frames or so before letting go (it should be consistent since Godot has a fixed timestep "update" function available) and normalizing the vector to get the direction the object should travel in. However, this blog post got me thinking that spending the time learning how to do the linear regression in a more robust way, then applying that to 3D VR, might be worthwhile. I just wonder if, since I don't need the actual linear or angular velocity, it might be overkill in terms of time spent on the feature.


How do I handle moving platforms in a platform game? I don't want to use box2d or anything, I just want simple moving platforms (up down, left right, diagonal and circular paths). My question is to handle the update order control hierarchy so that the player stays fixed to the platform solidly, without bouncing or wobbling?


Applying angular velocity distorts model I am calculating the orientation of a sphere through the following code wV new Vector3(0, pi 2, 0) w new Quaternion(wV, 0) o is the current Orientation o.Normalize() w 0.5f w o dt is the elapsed time since the last frame o w dt However it seems that over time the sphere tends to become distorted and then shrink back to its original size. Is this due to the simplicity of the integration or am I doing some simple mistake?


Dashing mechanic in top down projectile dodging game in pygame im making a simple third person top down game where you dodge projectiles than fly in from either side of the screen, its a simple high score game where the longer you avoid being hit, the better your score. i want to give the player the ability to dash in any movable direction by using a resource (lets call it a dashcoin) if the player collides with a certain target, they get one dashcoin, which can be expended to dash forward at increased speed for a brief moment. im also hoping to remove player control while they dash this is the entirety of the code right now. currently theres no projectiles to dodge, but im working on that. import pygame pygame.init() win pygame.display.set mode((630, 530)) pygame.display.set caption( quot Cube Dash quot ) x 250 y 250 width 30 height 30 vel 3 run True while run pygame.time.delay(10) for event in pygame.event.get() if event.type pygame.QUIT run False keys pygame.key.get pressed() if keys pygame.K LEFT and x gt 60 x vel if keys pygame.K RIGHT and x lt 550 x vel if keys pygame.K UP and y gt 10 y vel if keys pygame.K DOWN and y lt 490 y vel if keys pygame.K ESCAPE run False win.fill((0,0,0)) pygame.draw.rect(win, (255, 255, 255), (x, y, width, height)) pygame.display.update() pygame.quit() im completely new to pygame and got most of this from tutorials, so any help is appreciated


Gravity wells that go with finger I have a simple particle game, where all the particles are arranged in a grid. This game is for touch devices so to take advantage of it I am trying to have a multitouch gravity field thing going on. Basically I am trying to get it so that each finger is basically a well in an otherwise non existent gravity field. That way the particles are pulled towards a finger. My problem is I don't even know where to begin with these calculations, I have tried averaging a particles distance to each finger, its direction to each finger and nothing seems to work nicely! I have seen other games do this. What does the math for it look like?


Which Box2D like physics engine parameters need pixel conversion? The official guide does not have any useful details on the matter http www.box2d.org manual.html Position is an obvious one. What about velocity? Density? Anything else? Update the context is wrapping interfacing a physics engine to make it more usable. E.g. units of measure in the game editor should be consistent.


What is original Pong ball behaviour? I am building a Pong clone to learn interactive programming and I've stumbled in getting the ball movement and bouncing on the paddles right. If I play the original game I can't really understand how the "spin" and the paddle bounce works. I've been searching a bit on the internet and all I got was just more confusion. Can anybody explain me how the bounce is handled? If the paddle stands perfectly still and the ball, just moving on x, hits the paddle at the center I simply get x, that is clear. What happens if you hit the paddle on the sides? What changes if when the ball hits the paddle the paddle is also moving? I did an Arkanoid like implementation but it is far from the real Pong feeling.


3D Coulomb Friction Use Collision Impulse To Calculate Friction Force? I've been using this document to learn how to implement a very basic physics engine. The section on Coulomb Friction on page 55 56 (marked as pages 43 44) confuses me. It observes that the friction force can be calculated using the collision impulse (jr). This seems strange. Envision an object falling very quickly onto a plane with a slight incline. The object is rotating in the opposite direction it would if it were rolling down the incline. When the object makes contact, it will have a small velocity along the tangent, but a huge normal impulse (jr). This will result a very large change in velocity along the tangent (t hat) opposite to the direction of motion. This will push the object up along the surface (bad!) with a notable amount force. My implementation confirms this. Can someone explain to me how this all fits together? I'm very confused. P.S. I don't think trying to provide an example of my implementation here is relevant, either the effect I'm explaining cannot occur (in which case there is a bug, which I can find myself), or I'm misunderstanding the equations, in which case the implementation is inherently broken


Destructible Terrain like worms I have to develop a game with a dynamic destruction of the map, I searched the internet and even looked at some questions regarding this topic on this Website, but they did not help me much out. I made the map with tiled and used box2d to make collision between the game objects. As a game engine we have to use Libgdx, but I dont know how to start as I had never develeped a game before, can someone give me any tipps how I could start? with regards,


Using fixed timestep and interpolating states makes physics fall behind one frame. Does that affect responsiveness? The title says it all, but let me build more into the question I suppose everyone by now knows the Fix Your Timestep article, and its proposal to free your physics engine steps from your rendering steps. Which you can accomplish by accumulating time generated by the renderer and consuming it in fixed step sizes. The interesting part is that Glenn Fiedler tells you to interpolate the previous and the current frame, which lead me to the following question Doing such will make the rendering lag one frame behind the physics. Won't that affect my input responsiveness? Since I'll take one more frame to see the results of my actions. One may be inclined to say that one frame doesn't make that much of a difference, but then, these three articles of Mick West, one of the founders of Activision and former programmer of "Tony Hawk's Pro Skater" series says otherwise Pushing Buttons Measuring Responsiveness in Games Programming Responsiveness So again, the question Interpolating the previous and current frame, will make me lag one frame behind. Will that hurt my input responsiveness?


Looking for very simple implicit integration example I am trying to design a robust cloth system. I have no problem at all simulating things like that using forward integration such as euler, midpoint, runge kutta, verlet, etc. However, I just can't wrap my head around implicit methods. I don't understand how you formulate the equations in linear algebra terms. I'd really like to see a VERY simple tutorial, and an actual example of how to construct the equations, and then solve for a very simple system (for example, 3 particles connected by 3 springs). I looked into David Baraff's Large Steps in Cloth Simulation, and I can kind of follow it, but going from equations to code is a weak spot of mine. I can use a package like eigen to solve, but I'd also really like to see some code for something like conjugate gradient descent. I don't care about efficiency at the moment, I just want to be able to clearly understand what's going on. Thanks


Path following with Asteroids like movement. Time to complete path I'm currently learning about how to do this, but it's best to post the problem beforehand. (posting on Physics and GameDev, as you guys know your math) It's quite difficult to explain. This specific problem revolves around a problem of creating a guidance system for rocket powered craft. Think 'I want the ship from game "Asteroids" to follow a specific path and compute, how much time will the whole trip take beforehand" A craft has it's own properties like mass, linear and angular acceleration. It is only able to accelerate in its forwards direction. Also, quite a pain in the... it's maximum traverse velocity is limited. Hopefully the picture clears some things out The problem lays in the very first step. The program is initiated while the craft is already moving with random velocity and faces random direction. In order to move fully toward the target point, first the craft has to turn to face "U" vector. But while doing so, it still moves, so the vector "U" will change. From the picture you can see that the direction of turn can change, don't worry, it's not a problem. So, the problem. I tried using only vector math, but with no success as the variable I'm trying to compute relies on equations involving this variable. I'm too dumb to get only the variable I'm interested in on one side of equation. I think the solution would involve a function of distance from craft to object over time. Edit 1 For your interest. Here is the part where I get stuck. From the beginning. We have the craft on initial position "A", travelling with velocity "V1" and the target on initial position "B", with velocity "V2" (better include it just in case) From that we can compute the burn vector "U", that we need to align ourselves to in order to travel towards the target at the speed of "Vmax" The bigger the angle between craft's heading "Cf" and vector "U", the longer it will take the craft to turn. Which means, the craft will cover more distance while turning (uppermost picture). Which means the angle will change during turning etc. etc. On second picture, in red box. at the top we compute dot product, at the bottom we multiply magnitudes of vectors. As the Cf vector is of length 1 all the time, we can spare it. The primary thing I'm looking for is variable "t", currently I'm out of ideas.


Physics engine and squishing of stacked objects I have a general question that seems to apply to most physics Engines (Box2D, Unity, Matter.js, ). I'm trying to make a tower of rectangular objects that are stacked on the static mass infinity ground, and the more blocks I have, the more they "squish". I put together a test case in CodePen, which is reproduced here var canvas document.getElementById("canvas") var context canvas.getContext("2d") var width canvas.width var height canvas.height physics vars var phys Matter var bod Matter.Body var bodies Matter.Bodies var engine var render var world var optionsForBodies Florian restitution 1, var boxNumber 0 TEMP const keyState window.onkeydown function (event) keyState event.code true window.onkeyup function (event) delete keyState event.code TEMP Add bodies to matter function loadMatter() var floor phys.Bodies.rectangle(100, 225, 200, 50, isStatic true ) var blist floor for (var i 0 i lt 13 i ) for (var i 0 i lt 2 i ) var box bodies.rectangle(100, 200 i 20, 56.8, 20, optionsForBodies) blist.push(box) boxNumber 1 phys.World.add(world, blist) function drawMatter(name) var bodies phys.Composite.allBodies(world) for(var i 0 i lt bodies.length i ) if(!bodies i .render.visible) continue var verts bodies i .vertices if(verts.length lt 0) continue context.fillStyle " aaa" context.strokeStyle " 000" context.lineWidth 2 var ofsx 0, ofsy 0 context.beginPath() context.moveTo(verts 0 .x ofsx, verts 0 .y ofsy) for(var j 1 j lt verts.length j ) context.lineTo(verts j .x ofsx, verts j .y ofsy) context.lineTo(verts 0 .x ofsx, verts 0 .y ofsy) context.fill() context.stroke() function updateMatter(ms) phys.Engine.update(engine, ms) function clrCanvas() context.fillStyle " fff" context.fillRect(0, 0, width, height) var inter function init() initMatter() clrCanvas() requestAnimationFrame(step) function initMatter() engine Matter.Engine.create() world engine.world world.gravity.y 3.0 render Matter.Render.create( canvas canvas, engine engine, options width 400, height 300 ) loadMatter() var frameNo 0 function step() var SCALER keyState.KeyA ? 3 1 var SPEED 16 SCALER if (frameNo SCALER 0) updateMatter(SPEED) clrCanvas() drawMatter() requestAnimationFrame(step) init() lt script src "https cdnjs.cloudflare.com ajax libs matter js 0.11.0 matter.min.js" gt lt script gt lt body gt lt canvas id "canvas" width "400px" height "400px" gt lt canvas gt lt body gt To me what's happening is not obvious and I'd love an explanation in human words, since in real life if you stacked crates they would not squish inside each other, but it's a constant with EVERY physics engine, despite playing with restitution, slop, damping, density and many parameters. Ideally I'd like those crates to be dense enough to absorb a big part of the shock ( not bounce much) of each other and never penetrate each other. What concepts am I missing? In the codepen above, try to select the canvas and then press the 'A' key, which reduces the framerate (increasing the dt from 16ms to 50ms) which increases the forces computed for the objects at each iteration and therefore penetrating even more each other. Thanks!!


Calculate Jump Limits My question is in a similar vein to this question, I am creating a pre mapped pathfinding solution much akin to how Ash Blue was for my 2D platformer style game (in XNA). As part of the process, I have to be able to 'neighbor' nodes in the pathfinding algorithm. To be able to do this, I need a procedural manner to precalculate the maximum capabilities of motion from a given game object at a given location. I am having a difficult time with one specific aspect of this I cannot, for the life of me, figure out how to test whether or not a game object will be able to successfully jump to a given platform from where they are standing. I know there's a way to express this in some manner of equation, but I cannot find what the proper equation would be, it's probably in the vein of projectile physics, but the answer eludes me. If anybody can shed some insight into the matter, I would be very grateful.


How to create simple physics for a group of balloons colliding in the screen (2D) The game is 2D, how can I make simple physics for a group of balloons colliding in the screen. What I need is the balloons not to overlap and to bounce when they reach the limits of the screen or other balloons. Should I use something like box2d or is there a simple algorithm to do something like this?


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


Simulating elastic ball collisions quickly escalates to disaster I'm trying to learn HTML canvas and was working on a basic physical simulation, where a number of balls are drawn and set in motion, and the program simulates them colliding and bouncing off the walls and each other. Here's the simulation. Each ball is initially given a random position, direction, and a constant starting velocity. For simplicity, a ball's mass is simply equal to its radius. The velocity vectors are stored as (x,y) instead of polar coordinates to make the calculations simpler and the simulation faster, but this apparently has unintended consequences. In the simulation linked above, I'm starting with ten balls, and each ball has an initial velocity magnitude of 3, so the total initial "speed" of the system should be 30 ( 10 3). On each frame, I calculate the total speed of all the balls and read it out in a form field, and with uniform balls of size 10, the total speed seems to stay a few units under 30. The same is true of the min and max radius are decreased so all the balls are size 5, or increased to 20 the total speed stays relatively uniform. However, interesting things happen when the balls vary in size. If the minRadius is changed to 5 and maxRadius to 15, for example, you'll notice that the total speed of the system starts climbing over time. The bigger the difference, the faster the speed grows out of control. SO my first guess is that I screwed up the physics, but I can't figure out how. My other guess is that this is caused by accumulating floating point error, but it's interesting that it only grows upwards, and never towards zero. Also, it does seem to have a limit while it constantly fluctuates, it seems to be capped at some value related to the delta between the minimum and maximum ball size. My question is really to understand why this is happening? Did I just screw up something simple, or is something more sinister going on?


Server side physic simulations with hundreds of players I m currently working on a singleplayer physics orientated game where I would like the physics to be simulated server side. This because the game will have leadersboards, persistant player progression, etcetera and I want to prevent any type of cheating basically a pure client server architecture, the client is dumb and only displays what the server wants you to display. The problem however is that the game will most likely be played by hundreds (maybe thousands) of people at the same time. This concerns me, as it will most likely kill server processing power if I have to do and maintain hundreds of states at the same time. I would have no problems moving all of the physics simulations to the client side, but then I would really need a way to validate if the result of a client simulation is valid. However, I can't figure out how. I have thought about running the simulation server side once in a while to validate if the client is still playing fair, but I really want the server to have as less strain as possible. Physics will become about as complex as the GDC 2011 demo by Glenn Fiedler, maybe even simpler. However, a lot more always colliding rigid bodies will be in a single scene and they will all be visible at once. I have a hard time getting an answer to this particular case, as most resources on the web again, Glenn Fiedlers site being a great one speak about small scale networked physics (eg. a FPS with 30 players, like Halo). Any advice, websites, papers or the like on the subject will be very appreciated. A recap of the questions I would like an answer to How feasible is a client server model? Is my server processing power concern legit and grounded? Is it possible to reliably validate a physic simulation run by the client on the server? If so, how?


How to adjust my games speed to fps Hi so i am making a small sort of physics engine, but if your fps is really slow the physics will update slower and objects will move slower. How do i make the speed of objects greater if the fps is lower so that on a computer with 5 fps the object will land at the same time as on a 60 fps computer? (just with that slow framerate)


How to get plausible platformer physics with Farseer on MonoGame XNA? I am creating a 2D Vectorial (made of polygons, not tiles !) platformer using MonoGame and Farseer Physics Engine. Everything works perfectly, except the movement of the character which doesn't feels right for a platformer, because Farseer is a physics engine... I would like to have any advice to achieve a natural feeling like Mario . I didn't choose to make my own system because I'm simply not good enough to do something like this. I've seen some questions already about it, but none had useful answers (they said like 'You have to do a lot of tweaking', but how do I do that exactly ?) I could eventually use another engine that works for collision detection response and that gives me more control over the player entities, but i didn't find any yet. If you know any solution that's simple to use and that corresponds to what I need, then i'd love to hear it ) Thank you for any help. PS Also, I am soon going to try to create AIs for my game. How would I make them move with great control (like the player) ?


How do you apply relativistic physics to a 4x strategy game? I had the big idea of trying to create a hard science fiction 4X strategy game (with the obvious space setting), which is supposed to simulate a realistic way of creating interstellar societies while simulating real life physics as well. The problem is how do I apply Einstein's relativistic equations into the game? I will make a separate series of questions for other issues, such as applying Keplerian planetary movement and Newtonian combat physics. Do note the game is being made in C and in Unity. Be warned I am trying to simulate special relativity, not general relativity quite yet. That I can try in a different game.


Godot How do I get the id mask for a physics layer by name? I would like to figure out whether a collider is in a physics layer by the name (string) I set in project settings func physics process(delta) var collision move and collide(direction delta speed) if collision and (collision.collider.collision layer amp get collision layer("Walls")) ! 0 direction direction.bounce(Vector2.LEFT) more behaviors based on other layer tests Walls is the name of the physics layer and I am trying to find get collision layer. I am using Godot 3.2.1. self is a KinematicBody2D amp colliders are StaticBody2D's amp also KinematicBody2D's. I have figured out the collision id (as an int) but still think it would be cleaner to use layer names, preferably using a built in function.


Cocos2dx Physics Abort() When Changing Dynamic PhysicBody to Static? I just learned cocos2dx v3.3 integrated chipmunk physics engine. Here ,as you see, I create a simple circle with physic as auto sprite Sprite create("circle.png") auto body PhysicsBody createCircle(sprite gt getContentSize().width 2) body gt setContactTestBitmask( 1) active collisions event sprite gt setPhysicsBody(body) sprite gt setPosition(...) this gt addChild(sprite) When I toggle this circle static dynamic in normal situation everything work fine and when circle become static it stop in its position (as we expect gravity don't move it longer). here is a toggle code which works fine body gt setDynamic(false) scheduleOnce( (float dt) body gt setDynamic(true) ,3,"Back to Dynamic Mode Timer") PROBLEM BEGINS But I want when the circle collide with something else ( in my case screen edge with is not important part of scenario), it become static then. so I use below code auto contactListener EventListenerPhysicsContact create() contactListener gt onContactBegin (PhysicsContact amp contact) gt bool return true contactListener gt onContactPostSolve (PhysicsContact amp contact, const PhysicsContactPostSolve amp solve) contact.getShapeA() gt getBody() gt setDynamic(false) gt Cause Abort() ! eventDispatcher gt addEventListenerWithSceneGraphPriority(contactListener, this) But I just face a abort() message and game exit. The call stack ( God bless it) show that the error is comming from line 300 in CCPhysicsBody.cpp if ( world ! nullptr) cpSpaceRemoveBody( world gt info gt getSpace(), info gt getBody())


Find meeting point of 2 objects in 2D, knowing (constant) speed and slope I have a gun which fires a projectile that has to hit an enemy. The problem is that the gun has to be automatic, i.e. choose the angle in which it has to shoot, so that the projectile hits the enemy dead in the center. It's been a looooong time since school, and my physics skills are a bit rusty, but they're there. I've been thinking to somehow apply the v d t formula to find the time needed for the projectile or enemy to reach a certain point. But the problem is that I can't find a common point for both the projectile and enemy trajectories. Yes, I can find a certain point for the projectile, and another for the enemy, but I would need lots of tries to find one where the two points coincide, which is stupid. There has to be a way to link them together but I can't figure it out. I prepared some drawings and samples A simple version of my Flash game, dumbed down to the basics, just some shapes http axonnsd.org W P001 MathSandBox.swf click the mouse anywhere to fire a projectile. Or, here is an image which describes my problem So... who has any ideas about how to find x3 y3, thus leading me to find the angle in which the weapon has to tilt in order to fire a projectile to meet the enemy? EDIT I think it would be clearer if I also mention that I know the speed of both Enemy and Projectile and the Enemy travels on a straight vertical line.


Timestep schemes for physics simulations The operations used for stepping a physics simulation are most commonly Integrate velocity and position Collision detection and resolution Contact resolution (in advanced cases) A while ago I came across this paper from Stanford that proposed an alternative scheme, which is as follows Collision detection and resolution Integrate velocity Contact resolution Integrate position It's intriguing because it allows for robust solutions to the stacking problem. So it got me wondering... What, if any, alternative schemes are available, either simple or complex? What are their benefits, drawbacks, and performance considerations?


Get project's gravity value in Godot I need to get access project's gravity value which set in Project Settings Physics 3D Gravity, however I couldn't find any related information about this. How do I get project's gravity value in GDScript? In Unity, it can be done by simply Physics.gravity, but in Godot, couldn't find similar. Using Godot 3.1.1


How to prevent bullets from passing right through entities? (sorry for bad english) I'm making 2D arcade game. I write all of physics stuff myself. The problem involves bullet behaviour. Imagine bullet flying towards some entity. If the bullet's velocity is relatively high and the entity is small, the bullet passes right through the entity which is obviously not what it's meant to do. Here's the gif that shows why that happens (values are exaggerated to better show the process) As you can see bullet's velocity is simply bigger than the size of the entity. Then I came up with this Getting point of impact coordinates means I can check if the distance between the point of impact is smaller than the bullet's velocity. If the distance is smaller then bullet should collide with the entity at the point of impact. But I don't know how to calculate the coordinates of the point of impact. Pls help.


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.


Creating stable tentacle structures I am using verlet integration to simulate some tentacles. So far it works great and I am satisfied with how it looks in general. Here is how a tentacle is built The very stiff sticks are colored red, in addition I added angular constraints of 180 in order to keep everything together. But still, sometimes this happens When forces are too big at the peak, it flips around and gets stuck in a very ugly state. Of course I could increase the number of iterations for satisfying the constraints, but then the tentacles get too stiff and the performance suffers. What can I do about this? Some ideas add more points at the peak more constraints overall limit possible forces maybe rethink my tentacle design completely? detect flip over and undo it


Why is there no standard 3d file format that saves models as (collections of) primitives? I have been looking around for a file format that saves models as a collection of primitives (Boxes, Spheres, Cones, Cylinders, etc.). After some research, I came to the conclusion that pretty much every standard available file format saves models as a collection of vertices and indices (and some other stuff like UVs amp materials). Real world example Why would one need a file format that saves primitives? Well, in my case, I am trying to build a game where I will need to import the physics separately. Since physics are optimized per primitive type, I would deem it wise to not just import everything as a mesh collider but make use of these optimizations. For context, I am using Three.js with Ammo.js (Bullet) running server side. Standard So the question really is, why is there no standard for this? Why isn't there a standard like SVG but for 3d models? I will probably end up writing my own format implementation, so it's not like it's holding me back. It's just that I am a bit cautious, since I feel that there probably is a reason for no such standard to exist. Related links Here are some links I came across during research http wiki.laptop.org go Physics File Format http bulletphysics.org mediawiki 1.5.8 index.php Bullet binary serialization Edit Since comments aren't for thanking people, I'll just do that here. Thanks to all of you that answered and commented, very insightful! Much appreciated!


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?


Basic Box2D collision detection I don't understand how to listen for collisions in Cocos2D Box2D. Say I have two dynamic circle bodies. One is very small and the other is relatively large. When the small circle collides w the large circle I'd like to do something (play a sound for example). What's the best way to do this? I'm currently experimenting w the TestPoint method. Something like if(largeCircleBody gt GetFixtureList() gt TestPoint(smallCirclePoint)) collision happened... play sound etc


bullet character controller sliding down any slope gradient I've been experimenting with the btKinematicCharacterController. I've seen very old complaints that it has issues but I can't find anything recent stating that these issues remain (and nobody ever says what the issues were). The problem I'm seeing is that the character is sliding down slopes at absolutely ANY gradient. It will only stand still on level ground. If I have a ramp with a very gentle gradient it will slide slowly. I've found posts asking about this on the Bullet forums but haven't found any solutions. I've set the friction and rolling friction for both the ramp and character capsule to a very high value but it doesn't seem to impact the sliding. I'm sure there's something else I'm missing or is there something wrong with the controller's implementation of recoverFromPentrations (It seems to shift the object by the collision normal on the other surface which is necessary to avoid going through walls).


what is the difference between CCSprite and a PhysicsSprite? I am new to Cocos2D and I've realized that most of the codes written before the Cocos2d update used CCSprites. Recently I realized a lot of more recent codes after the update are using PhysicsSprite. What is the difference? What advantages does one have over the other, if any?


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


Does client side prediction sync with the server in the past? I've spent some time now messing around and just trying to learn dead reckoning and client side prediction for the fun of it. Most of what I do doesn't need it, so i've never had a need to go down the path. I get how to predict the client and i've got a completely deterministic setup with a lockstep of 60fps for the physics on client and server. Both client and server use the same movement code, and i'm using constant velocity to reduce complexity. I also understand how to interpolate for corrections. I also have the server and client ticking at nearly the same time (as close as one can really get it). The problem i'm having, that doesn't seem clear to me in anything I've read (i'll put links at the end to a few things), is what does the client message sync against on the server? So, for example, the client is at 0, 0, 0, with a heading of 0, 0, 1 at tick 0. At tick 5 the client presses the button to start moving forward at 40u s and sends the message to the server. We'll say that the trip to the server takes 50ms and 50ms back. So the server gets the message at tick 8 (roughly), and here is where I am slightly lost. The client sent the tick they pressed the button along with the position and new velocity. Does the server do A. Look back at tick 5 and say "you're good b c you were where you should be at that tick" B. Check against tick 8 and say "well you where at 0, 0, 0 at tick 8, so you didn't start moving until then". It would seem with B, which is what i'm currently doing, that the server is always sending back a correction. B also has a bad side affect that when I stop, I'm almost never where the server is and the interpolation of this feels impossible to get right. While with A, it would seem I have to redo all collisions for that object from tick 5 thru 8 on the server, but this sends less corrections and would give a smoother feel. I understand that A is used for lag compensation when firing a weapon or taking some action that would affect other entities, but is that also used for motion? Things I've read http gafferongames.com http www.gabrielgambetta.com fpm1.html Various articles out of books and other websites that seem to skip past this detail Thanks in advance for any help.


Solids as high viscocity Liquids A friend of mine and I were discussing different idea for allow materials in a world to be destroyed in a very piecemeal fashion and he proposed the idea of representing solids as very viscious fluids. My intuition is that this would be either A) very difficult, or B) very resource intensive, but I am unsure. Is such a model feasible for an RPG adventure rpg fps? edit clarification The idea is for collisions and objects breaking to be handled by this system. To basically allow any object handled this way to be destructable instead of having scripted destroyable objects.


Looking for very simple implicit integration example I am trying to design a robust cloth system. I have no problem at all simulating things like that using forward integration such as euler, midpoint, runge kutta, verlet, etc. However, I just can't wrap my head around implicit methods. I don't understand how you formulate the equations in linear algebra terms. I'd really like to see a VERY simple tutorial, and an actual example of how to construct the equations, and then solve for a very simple system (for example, 3 particles connected by 3 springs). I looked into David Baraff's Large Steps in Cloth Simulation, and I can kind of follow it, but going from equations to code is a weak spot of mine. I can use a package like eigen to solve, but I'd also really like to see some code for something like conjugate gradient descent. I don't care about efficiency at the moment, I just want to be able to clearly understand what's going on. Thanks


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.


Calculate the leaning angle I have an object moving around, let's say it's a cycle. In cycle dynamics, when the object takes a turn, it often leans into the direction of the turn. I would like to simulate this. I'm using the equation atan(v 2 r g), where v is the current velocity, r is the radius of the turning circle and g is the gravitational force. I get r with v 2 a, where a is the current acceleration. However it doesn't seem to work right. In some cases it leans to the right direction, in others, it leans to the opposite, meanwhile the leaning should always be inwards. I've determined the direction where the acceleration force pulls the object with sign(velocity.y acceleration.x acceleration.y velocity.x) and multiplied the leaning with the result, but it has no effect. What am I missing?


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?


Libgdx movement of scrolling background is not smooth even at 60fps I'm developing a game and I want to make a sliding background. The background is not scrolling smoothly. I logged the fps, but it was ok. This is my code, I don't know what I'm doing wrong, any ideas? public class MyGdxGame implements ApplicationListener private OrthographicCamera camera private SpriteBatch batch Texture back float offset 0f FPSLogger logger new FPSLogger() Override public void create() camera new OrthographicCamera(320, 480) camera.position.set(320 2, 480 2, 0) camera.update() batch new SpriteBatch() batch.setProjectionMatrix(camera.combined) back new Texture(Gdx.files.internal("back.png")) Override public void dispose() batch.dispose() Override public void render() logger.log() offset (400f Gdx.graphics.getDeltaTime()) offset offset 480f batch.begin() batch.draw(back, 0, offset) batch.draw(back, 0, offset 480) batch.end() Override public void resize(int width, int height) Override public void pause() Override public void resume() I uploaded the code to bring more information, I looked for on internet and a lot of people have the same problem, but I didn't find solution. I have almost finished the game, change the library will be a pity, any can help me? Thanks! This is the code https www.dropbox.com sh t26gt33wcex5izn AAD8 yBSOztZfHe4wzDPRjjQa


How should I make realistic electricity? I am currently designing electricity for my game. If you've ever played or seen Factorio, this is pretty much the exact way I want it to be. Okay, on to theory What I came up with is some sort of power source produces a certain amount of Watts per frame. Most power sources cannot store any energy, so at the end of the frame, it is all lost. Machines connected by wires to energy sources will perform a Dijkstra style flood fill from themselves through all connected wires, ignoring wires that have already been processed. The Watt cost will slightly increase for each wire it passes through (to simulate energy loss) and when it reaches a battery or power source, it will drain as much as it needs. If the source doesn't have enough, it continues to search for more power. If, by the end of the frame, it doesn't have enough Watts, it simply works slower or stops working entirely. After all machines have done this, all batteries will perform a similar flood fill, but ignoring other batteries, and will attempt to take ALL of the energy from sources (up to its storage capacity). Then, all power sources discard all energy. Is this how it actually works? I want to use numerical values, so just being connected to an energy source is not enough. Thanks.


Simulate wind affecting a boat using a 2D physics engine like Box2D or SpriteKit? I'm looking for a way to simulate the forces created by wind and how it affects a boat. In a nutshell if wind hits a boat (sailing yacht), the bow is aligning with the wind and if the wind is strong enough, the boat will then slowly start to move. I am not looking for a correct simulation of sails or alike. Just wind as it would affect a boat during maneuvers at slow speed. Here's what I have tried Make the boat just one body and apply a force this does not take into account the heavier stern versus the lighter bow. Make the stern a heavy body and the bow a lighter one and connect them with a fixed joint this will make the boat rotate if the same force is applied to both bodies but ignores the fact that once the boat is aligned with the wind, the force should be reduced. Create many (thousands) of very small objects with little mass and apply a force to them, simulating the wind "particles" and let them hit the boat this kills performance on slower devices. Maybe I am missing a very simple solution that would work good enough?


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


3D Planetary gravity so i am making a thing in javascript and i want to have planetary gravity in my "universe". But when i use an equation to calculate the acceleration by gravity i get one number. That is how fast the object accelerates in the direction of the other object, but how do i convert a speed in one direction to a speed in the X, Y and Z axis?


How to handle jumping up a slope in a runner game? In an 2D endless runner, what should happen when the player is running "too fast" up a slope and jumps? For example, in a "normal" case .O. . ..O . . O If he is moving to the right slowly enough, he will jump upwards and land on the flat part of the surface. However, if he is moving too fast, the jump will have no effect as his forward motion will bring him back in contact with the slope before he can get high enough to pass over it. When the speed is sufficiently high, there will effectively be no jump. .O O Are there any known ways to solve this issue? I know it's physically correct , but are there techniques that other games use to overcome this in a reasonable manner? As a last resort I'll have to just remove all slopes that are too slanted. If you constrain the player to never jumping backwards.


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?


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.


Implementing time step in main game loop So ive read both http gameprogrammingpatterns.com game loop.html and http gafferongames.com game physics fix your timestep and I kind of understand how I'm supposed to do it, but some parts are still blurry and I would like some guidance. By the way, I have programmed my game from scratch and i do not want to change to some framework or anything that has an built in main loop, i want to do this by myself. Anyway, this is what I have accomplished code wise, I will re produce my solution it in psudocode below. func createPlayer() oData Empty Object() oData.id oData.name oData.etc..... Player LoadSprite("filename", oData) Properties Player.oSprite.x Player.oSprite.y Player.oSprite.scale Player.oSprite.width Player.oSprite.height Methods (Self explanatory) Player.oSprite.width() Player.oSprite.height() Player.oSprite.centerX() Player.oSprite.centerY() return Player Startup oPlayer createPlayer() oWorld 1D array of objects which has identical properties and methods from createPlayer() Main game loop while(game) User inputs game userInputs(byref oPlayer) "Physics" jumps and world collission is done here. game Physics(byref oWorld, byref oPlayer) rendering, draws the world frame with all inputs and physics done beforehand game render(byref boWorld,byref oPlayer) This is how I "understand" what flow the loop should have t 0.0 dt 0.0 currentTime 0.0 accumulator 0.0 while(game) newTime Timer QueryPerformanceCounter() Im feeling like this need something more than just the QueryPeformenceCounter? frameTime newTime currentTime if (frameTime gt 0.25) frameTime 0.25 currentTime newTime game input() This is causing my game to get stuck here, i belive it has something to do with my type of timer while accumulator gt dt game physics(t, dt) how is the deltatime helping me in my physics? t dt accumulator dt alpha accumulator dt game render(alpha) I dont know what im supopsed to do with this. TLDR, what do i do with the t, dt in my physics? before i render?


Bullet Physics Applying Torques Effects not noticeable I am applying torques to a rag doll in order to make it move walk. For some reason, I am unable to view any effects when I use a call to rigidbody to apply torques even though these torques are pretty large i.e in the hundreds of Nm. When I start the simulation, the doll just falls and the torques don't seem to have any effect. When I apply torque impulses however, there is a huge effect and the rag doll blows up because the angular velocity component becomes large that my velocity damping factor multiplies it and the torque impulse becomes huge. I seem to notice effects of the torque though when I pause the simulation and then resume it after some time. Am I missing something when I am trying to applying torques? I know that when applying torque, it accumulates the torque value rather than updating the angular velocity directly. I'm applying torques at every internal tick callback. I'd be happy to supply necessary code. Thank you all.


LOVE Physics Breaking Joint Chains (LUA Box2D) Wasn't sure whether to post here or on SO so please move if needed. I've been having a look into the box2D physics API provided by LOVE to try and create a swinging flail or weighted rope but I'm having some trouble keeping the jointed elements close together. So far I've made a series of circular bodies and linked them together using revolute joints with the first element being static and the final element being slightly larger heavier to act as a weight. The code to generate each link is as follows for i 1, segments, 1 do link if (i 1) then link.body love.physics.newBody(world, xpos, ypos, "static") Starting link else link.body love.physics.newBody(world, xpos, ypos, "dynamic") end 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(chain,link) ypos ypos link distance Place next link further down, keeping x position end And the code to join each link for i 2, chain, 1 do x1,y1 chain i 1 .body getPosition() First link position x2,y2 chain i .body getPosition() Second link position chain i 1 .join love.physics.newRevoluteJoint(chain i 1 .body, chain i .body, x1, y1, x2, y2, false ) Join the two with a revolute joint end And this works quite well, producing a chain like this The next step is to move the chain, I'm currently moving the first static element and having it "drag" the rest of the links along with it using the following code position vo.add(position, velocity) Vector addition add velocity to current position to get new position chain 1 .body setPosition(position.x, position.y) Update the first link position This works fine for slow speeds (chain currently moves towards mouse cursor) but any rapid movement causes everything to fall apart. Is there anyway to easily keep the elements close together? I've tried adjusting the weights and world gravity but couldn't see any difference, I've also thought about applying a force to each element when the first one moves but that doesn't seem quite right. Thanks Solution (Thanks to NauticalMile) Change the previous position update position vo.add(position, velocity) Vector addition add velocity to current position to get new position chain 1 .body setPosition(position.x, position.y) Update the first link position To a velocity update and have Box2D handle the movement chain 1 .body setLinearVelocity(velocity.x, velocity.y)


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


How can I move a ball to a clicked location using physics forces? I have a ball as a sphere in my game and I'm viewing it from top down view. The ball is a rigid body. When I click somewhere on the screen, I want the ball to be moved towards that direction using physics forces. The ball needs to move only on the X and Y axes, the Z axis can be ignored. Here is what I tried, but gives me some weird results. The script is attached to the ball Use this for initialization void Start () rb gameObject.GetComponent lt Rigidbody gt () void Update () Vector3 v3 gameObject.transform.position Vector3 v3Mouse Input.mousePosition Vector2 pointA new Vector2(v3.x, v3.y) Vector2 pointB new Vector2(v3Mouse.x, v3Mouse.y) float Angle Vector2.Angle(pointA, pointB) float angleRad Angle (Mathf.PI 180) Debug.Log ("Angle " Angle) float dx Mathf.Cos (angleRad) 10 float dy Mathf.Sin (angleRad) 10 if (Input.GetMouseButtonDown (0)) rb.velocity new Vector3(dx, dy, 0) What should I do here? When I click on the top of the screen, the ball should move up toward the mouse, and in all the other directions. Any ideas?


Creating shattering effects without having to use actual physics? For certain effects like glass shattering and falling objects cracking to reveal their inner contents, are there any tricks or ways to implement these fracture physics without having to use actual physics simulation? Also, what are the trade offs if I don't use real physics simulations? Since the effects don't really require exact simulation, an actual physics simulation may be too expensive and wasteful.


how to ignore physics collision of some objects in box2d I know this sounds silly but I would like some objects to follow physics while others not to collide each other. I tried to achieve them by setting their position exclusively. But then it will ignore all physics. Is what I am trying to do even possible?


How do I properly use multithreading with Nvidia PhysX? I'm having a multithreading problem with Nvidia PhysX. the SDK requires that you call Simulate() (starts computing new physics positions within a new thread) and FetchResults() (waits 'till the physics computations are done). Inbetween Simulate() and FetchResults() you may not "compute new physics". It is proposed (in a sample) that we create a game loop as such Logic (you may calculate physics here and other stuff) Render Simulate() at start of Render call and FetchResults at end of Render() call However, this has given me various little errors that stack up since you actually render the scene that was computed in the previous iteration in the game loop. Does anyone have a solution to this?


Ideas for 2D Water Simulation I am looking for any input on simulating water in 2D, against a rather large (call it) blocked not blocked array (viewed from the side). I have come up with the following ideas Cell Automata Do a massively parralel simulation on the CPU, using cell automata. With rules as simple as If there is a cell open to the bottom move to it. Check the left and right cells, choose a random one out of the two and move to it. Pros Simple to implement. Meaningful deterministic in a multiplayer system. Cons Probably really slow. Not convincing. Fluid Dynamics on the GPU Perform a rough approximation of fluid dynamics on the GPU against a texture like the following R G B A vX vY NULL Density Pros Probably really fast. Could be quite convincing. A further pixel shader could render it directly. Cons Difficult to implement. Difficult to tweak. I can't allocate a single texture the size of my level. I could overlap the grid areas, but this would add further complexity. Particles Use particles to simulate the water. During rendering using additive blending and then apply a multiplication function to the alpha channel to give the water crisp edges. Pros Will probably look nice. Easy to implement. Easy to render. Meaningful in a multiplayer system, although would require quite a bit of bandwidth to transfer. Cons Inter particle effects will probably be slow (neighborhood lookup). Could lead to water 'leaking' through solid spaces (because the solid space is small, e.g. 1px). Could lead to strange holes in the water depending on the particle size. Both of the above could be mitigated by allowing particles to drift closer together than their real size, however would cause problems with the inter particle and particle landscape performance. Any further ideas? Note This is an approximation, I am not looking for physically correct water here just something that 'is good enough' (bonus points for quick and dirty). The game is multiplayer, so unfortunately the whole level needs to be simulated continuously.


What does maximum normalized frictional force mean in this tutorial? I tried following this tutorial https nccastaff.bournemouth.ac.uk jmacey MastersProjects MSc12 Srisuchat Thesis.pdf, but in page 19 I ran onto a problem I don't understand the step 4. It is also not explained before. Could somebody explain what is it and what values may be used?


How do I prevent a KActor from changing the orientation of its Z Axis? So I have an object that inherits from KActor that I would like to behave as a dynamic physics object, but I want its Z Axis to remain upright, but very stiffly. I've tried the bStayUpright that triggers the "Stay Upright Spring". The problem is, it's a spring, and the object in question oscillates into position when I want it to remain oriented properly without wobbling. In the image above, the yellow block has fallen onto the gray box, and it is currently pivoting about the contact point as it tries to right itself. Should I be tweaking the StayUprightMaxTorque and StayUprightTorqueFactor parameters, or should I be using a Constraint of some sort?


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


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


Need physics algorithm for modeling ceiling collapse in voxel based game I'm looking for algorithms on how to model the physics of cave ins collapses for a game idea I am working on. The game allows the player to extensively mine 3D voxel based asteroids, and I want areas that are insufficiently supported to collapse under their own weight. Making the problem even more challenging, gravity will be non uniform (the direction it pulls will depend on where a given voxel is in relation to the asteroid's center of mass), and the number of voxels in the asteroid will be too large to model them all individually (I am using a sparse voxel octree to model the asteroid). Hopefully, someone will be able to provide links to articles discussing suitable algorithms, or can provide ideas on how to solve the problem. If you need more details, please ask. Edit 1 It does not need to be very accurate, I'm looking for something that would be a reasonable approximation for a Minecraft or Dwarf Fortress style game. I am mostly interested in how to determine where sections should break off when blocks are added or removed, moving the bodies after they break isn't part of this issue. Edit 2 My initial idea was to calculate the force on each block then iteratively distribute the forces amongst neighbors. However, this would require an entry for each block, while only blocks on the surface have entries in the data structure. Modeling all blocks on the scale I want would likely be prohibitive I would like to have bodies of at least 10,000,000 voxels, of which 200,000 will be on the surface and need to be stored.


What is the Shannon rule law when talking about game physics? I've been reading some articles on game physics and came across subjects such as fixed timestep (article). Some of the articles I read mention the "Shannon rule" or "Shannon law" in relation to the length of the timestep. Example quote Your timestep should be at least 1 120 seconds or smaller because of the Shannon rule ... Here's an answer here on Gamedev that mentions it. Some quick google searches for "Shannon's law" doesn't seem to yield much result except for this wikipedia article but I'm not sure if that's what is being talked about here. So what is the Shannon rule Shannon law?


Is restitution the wrong value, to make bouncing objects? I have been experimenting with Bullet. Specifically I was modifying the Hello World tutorial, to make the ball bouncing. The first thing I noticed is, that I need to set both the restitution of the ball and the ground above 0 to make the ball bouncing. For a simple setup, with two objects, this seems fine. However, for larger simulations I fell like, restitution is the wrong way, to make bouncy objects. Here are my reasons Reason 1 Consider three objects ball, box and ground. ground is just some plane. box is a box, which is not supposed to be very bouncy, thus its restitution is near or equals zero. ball is supposed to be bouncy, so I give it a restitution of 0.5. If now the ball collides with the ground, it only actually bounces, if the ground also has a restitution higher than 0, so let's give it a restitution of 1. So our ball is bouncy as expected, when colliding with the ground. When it collides with box it won't bounce, because the box has a restitution of 0. If we give box a higher restitution, the ball will bounce from it. But now we have a different problem. If the box collides with the ground, it will bounce off, but it isn't supposed to. I see no way, with restitution only, to make this scenario work. Reason 2 Restitution describes the amount of energy, that remains as impulse after a collision. The rest of the energy goes into deforming the colliding bodies and other side effects. If we now look at a typical bouncy object, like a rubber ball, we see that they are easily deformable (compared to less bouncy objects). When the rubber ball collides with something, it takes up energy from the collision, by being deformed and then goes back into its original form, thus releasing the energy taken up during the collision and bouncing back off. The solution (?) Reason 2 suggests, that a bouncy ball (like a rubber ball) shouldn't have a restitution close to 1, but rather be elastic (thus being deformed and then going back to its original form), to model bouncy objects as expected. The way to model this in Bullet, would be a soft body and I think it would be the way to go, in such a scenario. The actual question The text above looks more like an answer than a question, so here's the question I'm trying to ask I'm really unsure, whether this is right. Are soft bodies really the better way for bouncy stuff or am I just mistaking the principle of restitution?


Javascript Jumping Physics I have asked questions for this project before, but the jumping physics are a bit messed up. I cannot jump unless I hold down the W key, and then it just teleports me upwards. Does anybody know how to fix this glitch? Here's the code var canvas document.getElementById("canvas") var ctx canvas.getContext("2d") var x 1 var y 0 var xPos 0 var yPos 0 function updateVariables() x x 0.9 y y 0.9 y y 0.5 xPos x yPos y function clear() ctx.clearRect(0,0,600,600) function Draw() collisionCheck() clear() ctx.fillRect(xPos,yPos,10,10) ctx.fillRect(0,canvas.offsetHeight 0.7,600,200) window.requestAnimationFrame(Draw) function collisionCheck() if (yPos gt canvas.offsetHeight 0.7 10) yPos canvas.offsetHeight 0.7 10 function right() x 2 function left() x 2 function jump() y 20 function detectKeys() document.onkeypress function (e) e e window.event console.log(e.key) if (e.key "d") right() if (e.key "a") left() if (e.key "w") jump() window.requestAnimationFrame(Draw) setInterval(updateVariables, 1) setInterval(detectKeys, 1) lt canvas id "canvas" width "500" height "140" gt lt canvas gt


How to simulate backspin or topspin in a box2d billiard game? I am designing a simple billiard game with box2d. I think I can easily simulate hitting left or right side of a ball. Since box2d is not 3D, however, I am not sure how to simulate hitting upper or lower part of ball with a cue. In case you are not familiar with the game. If the ball is hit on its upper part, it's still going forward after hitting another ball. But when cue hit on its lower part, it should backspin as soon as striking another ball. Is this simulation possible with box2d? If so, a hint or reference will be appreciated.


Find vector tangent to circle through a point C2 and P1 are known points. Radius of circle C2 is also constant and known. I am trying to find point T to eventually construct line p1 t, which is tangent to circle c2. I have made an attempt involving bisecting c2 p1 at M, and performing trigonometric operations to find measure of angle TMC2. Then, I found the difference in x and y coordinates from m.x and m.y using a polar form to cartesian (polar angle tmc2 and length of tm c2m 1 2 c2P). After this, I normalized vectors c2P and added the difference in x, normalized the vector perpendicular to c2p and added the difference in y. This approach seems very convoluted for such a simple task. Are there any basic vector operations to save time and processing power? Thank you


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


How to program friction in an air hockey game in Cocos2d x 3.11? I'm developing a simple air hockey game, and I have a question about friction of puck and puddles with the game scene. How can I do that? I'm using cocos2d x default physics engine, and the friction setting of physic bodies only applies when they collide. I've found an old air hockey example project, but it seems that it's ported to cocos2d x 3.x so it doesn't use built in physics engine.