Can I "Pre rotate" VBOs while loading them in LWJGL? It is possible to flip VBOs horizontally and vertically by swapping around destination coordinates. Is it possible to rotate an image by any angle, such as 45 degrees, using different destination coordinates when loading up a VBO? I realise that rotating present VBOs can easily be done using a matrix uniform in your vertex shader, but I'm asking about pre loaded (VBOs) rotations the VBO that you load being permanently rotated by X degrees. I am not looking for code but a conceptual method (or an explanation of why this isn't possible).


How to expand the limit of screen mouse access for FPS side rotation I started coding in Godot and i have a working FPS controller but the problem is that when i move my mouse sideways , it cannot move my sight beyinid that side of my screen , in other words the movement of my charecter is limited by the size of my screen , how to prevent this Rotation code func input(event) if event is InputEventMouseMotion head.rotate y(deg2rad(event.relative.x mouseSensitivity)) camera.rotate x(deg2rad(event.relative.y mouseSensitivity))


3D 3 axes rotation into 3D 2 axes rotation Hello everyone and thanks in advance to anyone who'll help me through this ! I am currently working on the Kinect V2 (for XBox One) to interact with an avatar. I'd like to use the rotation quaternion that the SDK 2.0 give for each joint of the Skeleton. My avatar (virtual avatar of NAO robot) communicates through nautical angles, yaw, ptich and roll. There's no problem to convert quaternions into nautical angles, but here's my problem Let's take the shoulder as an example of joint Where the Kinect express the rotation of my shoulder as a 3 axes rotation, I need to convert it into a 2 axes rotation. So for my shoulder I have a Yaw, Pitch, Roll from the Kinect, which I want to convert into a Pitch, Roll for NAO's avatar At the beginning, I didn't see the problem I just ignored the Yaw angle. But I rapidly noticed that the movement was not the same than in the Kinect (and it makes sense). Can someone help me ? How can I convert a 3D 3 axes rotation into a 3D 2 axes rotation ?


from normal to rotation matrix (i'm on OPENGL) i have a mesh O (object) and a mesh T (terrain). i know a single triangle in T and i want to orient O to be aligned to that triangle (torate O to align to T in that point). i have only the normal in the triangle. how can i achive the roation matrix? i have thought this algorithm pseudocode float normal2rotation(Vector3D normal) angleX Vector3D.angleBetween(normal, Vecto3D.Axis3D.X) angleY Vector3D.angleBetween(normal, Vecto3D.Axis3D.Y) angleZ Vector3D.angleBetween(normal, Vecto3D.Axis3D.Z) float result angleX, angleY, angleZ return result but it does not give me the desired result.


Arcball Problems with UDK I'm trying to re create an arcball example from a Nehe, where an object can be rotated in a more realistic way while floating in the air (in my game the object is attached to the player at a distance like for example the Physics Gun) however I'm having trouble getting this to work with UDK. I have created an LGArcBall which follows the example from Nehe and I've compared outputs from this with the example code. I think where my problem lies is what I do to the Quaternion that is returned from the LGArcBall. Currently I am taking the returned Quaternion converting it to a rotation matrix. Getting the product of the last rotation (set when the object is first clicked) and then returning that into a Rotator and setting that to the objects rotation. If you could point me in the right direction that would be great, my code can be found below. class LGArcBall extends Object var Quat StartRotation var Vector StartVector var float AdjustWidth, AdjustHeight, Epsilon function SetBounds(float NewWidth, float NewHeight) AdjustWidth 1.0f ((NewWidth 1.0f) 0.5f) AdjustHeight 1.0f ((NewHeight 1.0f) 0.5f) function StartDrag(Vector2D startPoint, Quat rotation) StartVector MapToSphere(startPoint) function Quat Update(Vector2D currentPoint) local Vector currentVector, perp local Quat newRot Map the new point to the sphere currentVector MapToSphere(currentPoint) Compute the vector perpendicular to the start and current perp startVector cross currentVector Make sure our length is larger than Epsilon if (VSize(perp) gt Epsilon) Return the perpendicular vector as the transform newRot.X perp.X newRot.Y perp.Y newRot.Z perp.Z In the quaternion values, w is cosine (theta 2), where theta is the rotation angle newRot.W startVector dot currentVector else The two vectors coincide, so return an identity transform newRot.X 0.0f newRot.Y 0.0f newRot.Z 0.0f newRot.W 0.0f return newRot function Vector MapToSphere(Vector2D point) local float x, y, length, norm local Vector result Transform the mouse coords to 1..1 and inverse the Y coord x (point.X AdjustWidth) 1.0f y 1.0f (point.Y AdjustHeight) length (x x) (y y) If the point is mapped outside of the sphere ( length gt radius squared) if (length gt 1.0f) norm 1.0f Sqrt(length) Return the "normalized" vector, a point on the sphere result.X x norm result.Y y norm result.Z 0.0f else It's inside of the sphere Return a vector to the point mapped inside the sphere sqrt(radius squared length) result.X x result.Y y result.Z Sqrt(1.0f length) return result DefaultProperties Epsilon 0.000001f I'm then attempting to rotate that object when the mouse is dragged, with the following update code in my PlayerController. Get Mouse Position MousePosition.X LGMouseInterfacePlayerInput(PlayerInput).MousePosition.X MousePosition.Y LGMouseInterfacePlayerInput(PlayerInput).MousePosition.Y newQuat ArcBall.Update(MousePosition) rotMatrix MakeRotationMatrix(QuatToRotator(newQuat)) rotMatrix rotMatrix LastRot LGMoveableActor(movingPawn.CurrentUseableObject).SetPhysics(EPhysics.PHYS Rotating) LGMoveableActor(movingPawn.CurrentUseableObject).SetRotation(MatrixGetRotator(rotMatrix))


3d rotation of a Gunner unit to shoot the target I'm developing a scenario to shoot incoming targets by a specific gunner unit, however I'm confused to actual logic of shooting an object with a gun. I'm working in 3D environment. I'v target's position vector i.e x,y,z and its rotation vector x,y,z,angle , and also Gun's position vector i.e x,y,z and its rotation vector x,y,z,angle . The gun has two components, i.e a TopDondur and a set of Barrels, both components have the rotation along y axis, i.e only angel of rotation vector 0 1 0 angle is required to move the Gunner Unit to the target. What rotataions shuould give the Gunner unit to rotate both TopDondur and Barrels, i.e TopDondur rotates to the target and Barrels are to move up down with respect to that target.


How to set object's node's absolute rotation correctly? Usually when I want to rotate an object node in my Ogre scene I call the node's rotate() method. That rotates the node locally relative to it's current rotation. So for example, when I start with 0 rotation, then rotate twice for 5 degrees about one axis, then after the second call the object is rotated by 10 degrees in total. Now I need to set the absolute rotation of the node object directly, regardless of its current rotation. Thus, say I don't know the objects current rotation, I need to set it say to 45 degrees on the X axis. Something like setRotation(). I know there is a setOrientation() method in the SceneNode class, which expects a quaternion object. I also know that I can get the current orientation quaternion. What I don't know how can I use change this current orientation quaternion to set the new absolute rotation of the node? PS Crosspost at http www.ogre3d.org forums viewtopic.php?f 2 amp t 77710


Rotating hitboxes in PyGame? I'm using pygame.rect.colliderect() to check hitbox collision between sprites in my game, but now that I'm rotating the sprites, I'm realizing I can't do this because there's no way to rotate a PyGame rect, so the hitboxes are way off now. How should I handle collision in a game with rotating sprites if I don't want to use masks or pixel perfect collision? Is there a way to make a hitbox that rotates with the sprite?


Rotating and pitching a turret I am new to game development and I was trying to build a turret model, and control it through lua script in shiva3d. I can rotate it around the y axis which is no problem, but when it comes to pitching, I am not sure how to do that in a way which is independent of the Y rotation, for example, in the default position, rotating with a positive value around X aims upwards, which is what I expect. when I rotate it by 180 degrees around Y, the positive rotation around X aims downwards towards the ground instead of upwards. on the other hand, if I rotate by 90 degrees, the turret rotates around it self as if its rolling... I am not sure what to look for in order to understand how rotation in a 3d world should happen, so any pointers on that would be much appreciated


Transform inertia tensor using quaternion I have inertia tensor T in body coordinates and quaternion q for the body. I know I can transform T to world coordinate by converting quaternion to rotation matrix R and then use the relation (R T R T). However this seems unnecessarily expensive and unwieldy (especially if you are doing this often). So my question is How do I transform inertia tensor from body to world coordinate directly using quaternion and without having to generate rotation matrix from quaternion?


Godot 3.0 Constant 2D Angular Velocity I am making a Top Down shooter in Godot 3.0 on Linux. I would like to have my character rotate to face the mouse pointer at a constant speed, and have rotation speed power ups that allow the player turn faster. So far, this is done by having a Position2D object called "Center" share the same position (but not be a child of) the player (below just called "Sprite"). The center always looks to the mouse, and the Sprite rotates with linear interpolation to eventually reach the same rotation as the "Center". The weight of linear interpolation is calculated by dividing the difference in rotation (in radians) by an arbitrary constant speed. Problem The speed of rotation increases as rotation occurs, or more specifically, the time it takes to reach the same rotation (a rotational difference of zero) becomes shorter over time. I have the following code extends Sprite onready var center get parent().get node("Center") var current time 0 var total time 0 var start rot 0 var end rot 0 func process(delta) center.look at(get global mouse position()) var amt 0 var theta abs(self.rotation center.rotation) var speed 0.05 total time theta speed start rot get rotation() end rot center.rotation if not total time 0 amt current time total time current time delta amt clamp(amt,0,1) var rot lerp(start rot,end rot,amt) center.rotation fmod(rot,(PI 2)) set rotation(fmod(rot,(PI 2))) get parent().get node("Control rotation").text str(int(self.rotation degrees)) get parent().get node("Control theta").text str(theta) get parent().get node("Control time").text str(total time) What am I doing wrong?


Rotate Translate a MatrixTRS Hello I have a question about translation amp rotation of a MatrixTRS... So basicly I have a given MatrixTRS A in space, define by a positionA, rotationA and scaleA. (DISCLAIMER I am using Unity, but I do not use Transform, therefore I have a Matrix4x4, created like that Matrix4x4 A Matrix4x4.TRS(position, rotation, scale) Ok, Now I have a Point in space, with a given rotation, named PositionB, and RotationB. I would like to translate amp Rotate my TRS matrix to that positionB, and rotationB. I know I have to do something like b.transform.TransformPoint() and Quaternion.Inverse(b.transform.rotation) a.transform.rotation, but i didn't manage to make it right yet. Thanks!


Bounding Box in Monogame for mouse picking Hello guys so I'm implementing this mouse manager to be able to pick up objects. My application uses mainly textured quads in 3d space. I'm using bounding boxes in monogame to do so, however my solution lacks accuracy. Right now what I have is this http imgur.com oySTCay you can clearly see what the problem is, so this solution is probably not the best. this is my method to calculate the bounding box public BoundingBox GetBoundingBox() Matrix transform Node.GetTransformForBoundingBox() vertices 0 Vector3.Transform(new Vector3(0, 0, 0), transform) vertices 1 Vector3.Transform(new Vector3(Texture.Width m fTexturescale, 0, 0), transform) vertices 2 Vector3.Transform(new Vector3(0, (Texture.Height m fTexturescale) 1, 0), transform) vertices 3 Vector3.Transform(new Vector3(Texture.Width m fTexturescale, (Texture.Height m fTexturescale) 1, 0), transform) return BoundingBox.CreateFromPoints(vertices) And the mouse picking part is the standard ray tracing into near far clipping planes with unproject. So I was thinking, maybe if I do the other way around, and instead of un projecting the mouse, i could project all the vertices and do some kind of polygon math to check if the mouse position is inside the polygon formed from the projected vertices, (occluded vertices are worrying me though). Do you think is feasible, or is there any other option, should i just go for OBB? Thanks alot, Roger Martins EDIT So after searching a bit for OBB's i found that CartBlanche had one implementation on his samples repo this https github.com CartBlanche MonoGame Samples blob master CollisionSample BoundingOrientedBox.cs so I just used it and it works pretty well, now i just have one bug that i cant figure out, one transformation must be wrong. result http imgur.com QOsIbj7 what i'm doing so now I have a box parameter in this class, nullable one. how I build the bounding box public SOrientedBoundingBox GetBoundingBox() create the initial bounding box if (obb null) calculate the vertices for the textured quad in model space at the origin (inferior left corner is origin because we invert the y to conpensate for the perspective projection) vertices 0 new Vector3(0, 0, 0) vertices 1 new Vector3(Texture.Width m fTexturescale, 0, 0) vertices 2 new Vector3(0, (Texture.Height m fTexturescale) 1, 0) vertices 3 new Vector3(Texture.Width m fTexturescale, (Texture.Height m fTexturescale) 1, 0) get bounding box and trasnform it to orientedboundingbox TODO remove the middle step BoundingBox box BoundingBox.CreateFromPoints(vertices) obb SOrientedBoundingBox.CreateFromBoundingBox(box) return obb.Value else return obb.Value.Transform(Node.GetQuaternion(), new Vector3(Node.AbsolutePosition.X, Node.AbsolutePosition.Y 1, Node.AbsolutePosition.Z) Node.Scale) I'm going to fiddle a bit more with it, but the problem is something minor, i think. But maybe one of you can detect something silly i did. Thanks, Roger.


Rotate an object around a point in Ogre3D Possible Duplicate How can I rotate about an arbitrary point in 3D (instead of the origin)? I am new to 3D programming and I have been using Ogre3D lately to get a grasp of it. What I am trying to do is the following I want to make an entity rotate around a point (probably the parent SceneNode) in a circular way only in the X and Z axis. I have tried using yaw pitch roll and rotate but no luck, and I can't find any good tutorials how tos online.


Translate extrinsic rotations to intrinsic rotations ( Euler angles ) The problem I have is very frustrating I am using the Jitter Physics library which gives Quaternion rotations, you can extract the extrinsic rotations but I need intrinsic rotations to rotate in OpenTK (There are other reasons as well so I don't want to make OpenTK use a Matrix) GL.Rotate(xr, 1, 0, 0) GL.Rotate(yr, 0, 1, 0) GL.Rotate(zr, 0, 0, 1) EDIT Response to the first answer Like This? GL.Rotate(zr, 0, 0, 1) GL.Rotate(yr, 0, 1, 0) GL.Rotate(xr, 1, 0, 0) Or This? GL.Rotate(xr, 1, 0, 0) GL.Rotate(yr, 0, 1, 0) GL.Rotate(zr, 0, 0, 1) GL.Rotate(zr, 0, 0, 1) GL.Rotate(yr, 0, 1, 0) GL.Rotate(xr, 1, 0, 0) GL.Rotate(xr, 1, 0, 0) GL.Rotate(yr, 0, 1, 0) GL.Rotate(zr, 0, 0, 1) I'm confused, please give an example


AABB of rotated sprite? Say I have a sprite. Its AABB is easy to find since I know the width and height. Say I rotate it 45 degrees, I don't think the AABB would be big enough to cover it, so I need a new AABB. How can I calculate the bounding rectangle of a rotated rectangle (given a center point, an angle, and its width and height)? Note that OpenGL does the rotation so I do not have access to the vertex information. What I'm trying to do is get AABBs so I can do 2D culling for rendering. Thanks


Rotate can I rotate an object to a target angle using Euler Angles? How do I rotate an object from its current angle to the desired angle in increments on 1 axis? The problem is the wraparound at 360 degrees What I have so far (Note pseudocode) double MaxSpeed 5 double CurrentAngle 170 double DesiredAngle 40 double Distance DesiredAngle CurrentAngle How do I calculate this value considering angle wraparound? CurrentAngle Mathd.clamp(Distance, MaxSpeed, MaxSpeed) Caps the rotation speed


I'm rotating an object on two axes, so why does it keep twisting around the third axis? I see questions come up quite often that have this underlying issue, but they're all caught up in the particulars of a given feature or tool. Here's an attempt to create a canonical answer we can refer users to when this comes up with lots of animated examples! ) Let's say we're making a first person camera. The basic idea is it should yaw to look left amp right, and pitch to look up amp down. So we write a bit of code like this (using Unity as an example) void Update() float speed lookSpeed Time.deltaTime Yaw around the y axis using the player's horizontal input. transform.Rotate(0f, Input.GetAxis("Horizontal") speed, 0f) Pitch around the x axis using the player's vertical input. transform.Rotate( Input.GetAxis("Vertical") speed, 0f, 0f) or maybe Construct a quaternion or a matrix representing incremental camera rotation. Quaternion rotation Quaternion.Euler( Input.GetAxis("Vertical") speed, Input.GetAxis("Horizontal") speed, 0) Fold this change into the camera's current rotation. transform.rotation rotation And it mostly works, but over time the view starts to get crooked. The camera seems to be turning on its roll axis (z) even though we only told it to rotate on the x and y! This can also happen if we're trying to manipulate an object in front of the camera say it's a globe we want to turn to look around The same problem after a while the North pole starts to wander away to the left or right. We're giving input on two axes but we're getting this confusing rotation on a third. And it happens whether we apply all our rotations around the object's local axes or the world's global axes. In many engines you'll also see this in the inspector rotate the object in the world, and suddenly numbers change on an axis we didn't even touch! So, is this an engine bug? How do we tell the program we don't want it adding extra rotation? Does it have something to do with Euler angles? Should I use Quaternions or Rotation Matrices or Basis Vectors instead?


Programmatically determine UVs by rotating a plane along X axis I'm having a math brainfart while trying to solve what might be a simple problem. I've got a plane in 3d space (it's actually the face of a 10 sided die) Coordinates x,y,z Point top 0,0,1 Point left Sin (2pie9 10), Cos(2pie9 10), 0.1 .5878,.809,.1 Point right Sin (2pie 10) , Cos(2pie 10), 0.1 .5878,.809,.1 Point bot 1,0, 0.1 If you project that out, it's a plane with the top leaning back away from you, and the bottom closer to you. I'm trying to automatically build a UV map of that face to put a texture on, so think I should rotate it around the x asix so that it's only in 2D, then scale that to best fill up a 256x256 texture. I'm doing this in Three.JS for a canvas app. Is this the right approach? In this example http wecreategames.com games DiceBoard ( die creation code is in http wecreategames.com games DiceBoard die10.js ), I'm estimating the UVs by Build UVs scope.faceUvs scope.faceVertexUvs for (var f 0 f lt numHalfFaces f ) var faceuv new THREE.UV(.2, .6), new THREE.UV(.5, .75), new THREE.UV(.8, .6), new THREE.UV(.5, .2) scope.faceUvs 0 .push(new THREE.UV(0, 1)) scope.faceVertexUvs 0 .push(faceuv) But when I view on an iPhone or Android, it shows weird screen artifacts... I'm thinking because the UVs aren't exact. I think I'd apply some function like this (where andDist is an angle) rx x ry (y Math.cos(angDist)) (z Math.sin(angDist)) rz (y Math.sin(angDist)) (z Math.cos(angDist)) But, I'm not sure how to get the angle that the face is inclined at. Any suggestions? Or, are those white screen artifacts due to something else I've overlooked?


Align Players Rotation I'm currently working on rope Swinging. The Rope consists of Physics Constraints Joints and between them the rope is rendered. I would like align my Character's Pitch to the Rope. I'm horribly bad at vector Math, and I have trouble finding the solution. Here's a picture that shows what I want to achieve I tried using the Difference between two joints but somehow it doesn't work. I'm using Unreal Engine if that helps.


Rotate around an axis function for euler angles representation For a 3d game i need a function to rotate an euler representation around an arbitary axis by an angle. For example an object is rotated with euler angles (0,90,0). Now the object should be rotated by 100 degrees around the axis (0,1,0). The resulting angle will be (0,190,0) using rotation order YXZ. In this case I can add the angle to the euler value of the axis, however for an arbitary axis this will not work. Problem with Quaternions amp Rotation matrices With these representations the resulting rotations will always be smaller that 180 for each axis. I need the rotation to be lerped afterwards for example from (0,0,0) to (0,720,0). Basically I am searching for a way to display euler angles like most of the 3D editors. When you rotate an object around any arbitary axis rotation might be larger than 360 in the editor, like (420,720,15).


How to eliminate roll rotation? Let's say I have Rotation(0, 0, 180) pitch, yaw, roll . How to do it that I would have Rotation(180, 180, 0) which is exactly the same?


THREE.JS why is the rotation only applied on the last axis used? my function function rotateAroundWorldAxis2(object, radians1, radians2) object.rotWorldMatrix.makeRotationX(radians1).makeRotationZ(radians2) object.rotWorldMatrix old code for Three.JS pre r54 rotWorldMatrix.multiply(object.matrix) new code for Three.JS r55 object.rotWorldMatrix.multiply(object.matrix) pre multiply object.matrix.copy( object.rotWorldMatrix ) old code for Three.js pre r49 object.rotation.getRotationFromMatrix(object.matrix, object.scale) old code for Three.js pre r59 object.rotation.setEulerFromRotationMatrix(object.matrix) code for r59 object.rotation.setFromRotationMatrix(object.matrix) my object was initialized like this object.rotWorldMatrix new THREE.Matrix4()


How can I modify the UV co ordinates on a texture so they converge to a point? I'm building a roof visualiser app, where someone can take a picture of their roof, define its outline, then visualise a new roof texture on it. I'm generating a 3D plane that matches the roof outline points, but I'd like the 3D planes material's UV's to match the perspective of the existing roof (i.e the lines converge into the distance as they move away from the user. Is this possible? The alternative solution is to figure out how to rotate the generated 3D plane to match the roof outline points, while matching the perspective too, but I'm thinking this may be more complicated. Step 1 Define roof oultine with points Step 2 Texture 3D plane with UV's mapped to maintain roof perspective based on slant defined in the 4 points Any tips on how to solve this?


TiledMaps and real objects I'm creating a simple game for the iPhone using Cocos2d. I'm having a hard time understanding how add real objects to a tiled map. I know that you can add an object layer to the tiled map and set the position of it, but I'm not sure how to define WHAT object it should be. For example, if I'm creating a simple Super Mario Bros. I want to add different blocks to the map, one should hold a star, one should hold a coin, and so on. How should I define what object it is? So my question, how do I correctly create class objects in a tiled map?


create a simple tilemap programatically i am working on a tile roguelike i got some of the basics working using this tutorial http www.raywenderlich.com 1163 how to make a tile based game with cocos2d but i want to be able to create a map programatically instead of using the tiled editor just add a NSArray of sprites tiles to my CCLayer derived class or something, or should i make use of the CCTMXTiledMap class? can anyone gimme some hints about how to do this? or know of a tutorial or sample code somewhere? thanks a lot


How to get a large quantity of photographs in an app while being memory efficient?? There have been a lot of word games (apps) lately and some use graphics but others use photographs and I was hoping that someone could explain how these games manage to get so many photos in an app without taking up huge amounts of memory? The easiest example I can give is an app called '4 pics 1 word' it has over 350 levels and obviously 4 pics on each level and the photos are good quality on retina screens but the memory of the app is less than 40mb, if I have remembered correctly. I was curious as to how this works, is it each photo being optimized in photoshop (save for web and devices) (png or jpeg) or is it something to do with the code or something else? I know this question is quite broad but any answers, help, links to anything would be greatly appreciated.


iPhone, iPad Rendering Ahead of Input (4 5 seconds) UPDATE I think I solved this one, though any thoughts or suggestions are always welcome! This one is truly bizarre... I'm developing using both an iPhone 3GS and an iPad 2. This symptom is repeatable on the older iPhone hardware much more readily than on the iPad 2. Here's what happens I start the game and the FPS is ticking at about 47 on the 3GS in OpenGLES2.0. I have quite a lot on screen right now, so that is reasonable at this stage (I still have a few optimizations I can make too). If you put a break in touchesBegan, it takes roughly 4 5 seconds before the break occurs and the game halts. This doesn't happen all of the time, and in fact, if you restart the app several times, it usually goes away. Moreover, if I let the game sit for a bit, it will eventually "sync." Like I said, the iPad 2 rarely exhibits the problem (one out of every 15 20 test runs), but it is definitely still present. If you perform a series of touches and accelerometer events in sequence, they are queued up and rendered just like you did them 4 5 seconds later. Very reminiscent of 4 5s lag delays back in the day online ) I've tried a couple things like glFlush, or glFinish at the end of each render loop (doesn't seem to have any effect). Here's the top game loop (void) drawView (CADisplayLink ) displayLink double dt 0.0f Time in seconds since last loop if (displayLink ! nil) dt displayLink.timestamp m timestamp m timestamp displayLink.timestamp Update the game m gameEngine gt Update(dt) Render the game m gameEngine gt Render() m context presentRenderbuffer GL RENDERBUFFER UPDATE The more I think about it... this could be a loading issue. Right now, I instantiate my main controller class for the game loop in the (id) initWithFrame (CGRect) frame call, which is also where I initialize OpenGL and (finally) call displayLink addToRunLoop NSRunLoop currentRunLoop forMode NSDefaultRunLoopMode . It's almost as if the renderer gets behind or ahead of the game logic and it takes it awhile to get caught back up. From research, I could also just be throttling the CPU too hard. But if that were the case, I would imagine it wouldn't catch up... the FPS stays at a solid 44 46, and the input lag does go away if you let it sit for 10 15 seconds (with or without doing anything, it eventually catches up). I'm stumped, but I'll keep digging... UPDATE 2 Doing some profiling... figured out that the accelerometer being polled 1 60 was a bit taxing. If I moved it to 1 30, this problem went away. This is concerning to me, as it likely suggests I do have a CPU overloading issue that will only be solved through some serious optimizations across the board (which is okay, I knew I had to do it anyway). For anyone with a similar issue, especially if you are using the accelerometer, make sure you disable it if when you aren't using it. I only use the accelerometer to allow the player to rotate move the camera so when the player has the camera locked, I am now toggling it off. This has solved my problem for now, but like I said, I probably only solved it temporarily. A real solution is going to take more work! Hope this helps.


Saving data in games? I'm soon going to make a game for the iPhone as a school project. My idea was to make a TLOZ remake, with Tiled Maps. However, I'm not quite sure how save the data. In TLOZ you have a lot of sub quests, treasures, items, and much more. I want the user to only be able to open a treasure once. Therefore I have to save this information somehow. However, I'm not sure how to assign the data to that certain object, for example that treasure that Link has opened. I thought about making id's for every object, but I'll have multiple maps, and it doesn't seem like the right solution. Are there any standards for this? Or does anyone have another idea?


Creating Level iPhone I am thinking about a new game idea for the iPhone and presumably all the levels would have to be made programatically. So Im wondering what the best method to approach it? Say I have a game with a standard typical 2d, top down maze. Thise maze is simply made up of walls, multiple rectangles on screen, making paths. Do I have to manually work out the position of every rectangle and put it in with an x and y position or is there a better way? I see this taking, forever, there must be certain ways developers approach these situations to get by them efficiently and quickly surely? Thanks.


How can I make a rectangle to an irregular shape? I used masking for breaking an image into the below pattern. Now that it's broken into different pieces I need to make a rectangle of each piece. I need to drag the broken pieces and adjust to the correct position so I can reconstruct the image. To drag and put at the right position I need to make the pieces rectangles but I am not getting the idea of how to make rectangles out of these irregular shapes. How can I make rectangles for manipulating these pieces? This is a follow up to my previous question.


Game server for an android iOS turn based board game I am currently programming an iPhone game and I would like to create an online multiplayer mode. In the future, this app will be port to Android devices, so I was wondering how to create the game server? First at all, which language should I choose? How to make a server able to communicate both with programs written in objective c and Java? Then, how to effectively do it? Is it good if I open a socket by client (there'll be 2)? What kind of information should I send to the server? to the clients?


Efficient Bullet Firing Class I've been struggling with this for a while. I have been trying to create a bullet pool class for a game I have made that doesn't cause a significant fps drop. I have tried creating a bullet pool and have also tried dynamically creating and deleting bullets, both of which drop the fps of the game around 10 15. I ran a test a few days ago and just put a return statement in the bullet pool's firebullet function, which represented the logic leading up to this, function calling, etc. This only dropped the fps 2 4. If I can fire bullets without dropping the fps more than another 2 3, I would be satisfied. My bullets are autorelease objects that are a subclass of a ccnode. I create a ccsprite and a box2d b2body for each one. I am working on the ios platform. Any thoughts on how to make this more efficient? Has anyone managed to do something similar to this?


How do I repeatedly move an image by 1 pixel? I have a method that is moving a UIImageView called shootImg across the screen (IBAction)shoot if (appDelegate.shootInt gt 0) if (direction 1) shootImg.center CGPointMake(shootImg.center.x 1, shootImg.center.y) appDelegate.shootInt appDelegate.shootInt 1 shootLabel.text NSString stringWithFormat " d", appDelegate.shootInt This does seem to work. But it only moves shootImage 1 pixel. What I want to do is make it repeatedly move 1 pixel. I tried a while loop but that didn't seem to work. I'm not using cocos2d or anything like that and if you need to see more code just ask. Thanks )


Best way to learn iphone game development? I know php and some python, but not much c. Where should I start to learn iphone game development? Is there some recommended books tutorials for beginners? I'm looking at using cocos2d but I'm open to anything that isn't too limited.


Set texture of a LHSprite that is loaded from LevelHelper How do i set the image texture of an LHSprite that is loaded into xCode using levelHelper amp spriteHelper? I am using sprite sheets. So i tried to load the image the old fashioned way using CCSpriteFrameCache, but unfortunately it isnt recognizing the .pshs file ( Any Help would be great!


Getting started with Box2D for iOS I just want to run any Box2D "Hello World" or test apps. I've downloaded the source twice (zip file the first time and via svn the second time), followed the build instructions (do stuff w cmake, "make", "make install" etc) and don't know where to go from there. How do I run the test apps or Hello World apps that come w Box2D on my iPhone (or simulator)?


How can I make iPhone apps (games) on Windows? I want to start making iPhone games, but sadly I'm a Windows geek.. Is there a way to make good profesional iPhone games without Xcode owning a Mac computer? If not, what do you recommend, a Mac Mini? Thanks in advance!


.NET WCF as backend server for iPhone games I'm planning to develop an iPhone game. Is it possible to use .NET WCF as a backend? The server would be windows 2008 and MS SQL database.


Looking for the reference tutorials for the joints in the Box2D for iphone I can't find the tutorials of joints class in the Box2D for iPhone. I am unable to run a Testbed for iPhone Box2D. (void)ccTouchesBegan (NSSet )touches withEvent (UIEvent )event if ( mouseJoint! NULL)return UITouch mytouch touches anyObject CGPoint location mytouch locationInView mytouch view location CCDirector sharedDirector convertToGL location b2Vec2 locationWorld b2Vec2(location.x PTM RATIO,location.y PTM RATIO) ristrict the player within the ground limit keep stucking the player with grounditself..... if ( playerFixture gt TestPoint(locationWorld)) b2MouseJointDef md md.bodyA groundBody md.bodyB playerBody md.target locationWorld md.collideConnected true md.maxForce 100.0f playerBody gt GetMass() mouseJoint (b2MouseJoint ) world gt CreateJoint( amp md) playerBody gt SetAwake(true) (void)ccTouchesMoved (NSSet )touches withEvent (UIEvent )event if ( mouseJoint NULL) return UITouch myTouch touches anyObject CGPoint location myTouch locationInView myTouch view location CCDirector sharedDirector convertToGL location if (location.y lt 240.00 amp amp location.y gt 20.0f) b2Vec2 locationWorld b2Vec2(location.x PTM RATIO, location.y PTM RATIO) mouseJoint gt SetTarget(locationWorld) (void)ccTouchesEnded (NSSet )touches withEvent (UIEvent )event if ( mouseJoint) world gt DestroyJoint( mouseJoint) mouseJoint NULL


iPhone 3GS can't ever seem to hold 60fps with CADisplayLink So I've switched from NSTimer to CADisplayLink and I'm still seeing unexpected variation in my frame counter it fluctuates between 59 60fps, even when I'm not rendering much. Has anyone else seen this? Is this an expected variation in iOS? Or should I look more closely at my game loop?


Creating 2D waveform for Cocos2d game I'd like to have a Waveform in my iPhone game that I am developing using Cocos2d v2.0. That's the ideal wave I'd like to achieve. A simpler wave which I would still be happy with is this one. Some people suggested me to use ParticleEffects ands ParticleDesigners like 71squared but I am not sure that this is the right approach. Brainstorming, I think that at the end a wave is a plot of some function, and at each frame translate the wave points that where from the origin apart ( x and x) and computes new wave points for the origin. Something like this for (duration of effect) compute wave point intensity at origin and display it and for each wave point before the center translate to x and display it and after the center translate to x and display it Let me know what you think and if you have any better solution. I was thinking to achieve the display point by colouring a particular pixel but I need to figure out how )..


UDK iOS System Requirements confusion Unreal Development Kit for iOS was recently released. The system requirements note that Windows is needed. Does this mean that iOS game development is possible on a PC now? I am confused since I thought iOS development required an OSX machine. Thanks in advance.


shake Vibrate a body in box2d? How do you vibrate or cause a shake effect to a body of type static or dynamic or kinematic. I tried applying forces to a dynamic body in the timeStep, which did not work, as well I tried ApplyLinearImpulse many times a sec within the timeStep, which again did not give me the result. So right now Iam experimenting with adding a static circle body as a hinge point to my rectangular body and create a revolute joint between them. May be then applying a force could result in Tension between the 2 bodies? Does anybody know about this? have any ideas please let me know?


How to support all iOS device screen sizes resolutions in my game I made this game. Right now the game supports all iOS devices except iPhone 5. The definition of each level of the game is kept in a plist. The creation of each level is done through a graphical level editor. Each device family has its own plists. So, right now the game has 100 levels and 200 plists 100 plists for the iPhone family and 100 plists for the iPad family. In order to support the iPhone 5 I need to create 100 new plists and adjust the plists accordingly, which is time consuming, not to mention the creation of new levels... The editor for creating and editing the levels is solely based on the manipulation of UIViews that describe the game elements. So, this is the code that I wrote to save and restore the state of each UIView in one level of the game. (void)encodeWithCoder (NSCoder )aCoder Save the screen size of the device that the view was saved on aCoder encodeCGSize self.gameView.bounds.size forKey "saveDeviceGameViewSize" ALL properties are saved in normalized coords Save the center of the view CGPoint normCenter CGPointMake(self.center.x self.gameView.bounds.size.width, self.center.y self.gameView.bounds.size.height) aCoder encodeCGPoint normCenter forKey "center" I rely on view bounds NOT frame CGRect normBounds CGRectMake(0, 0, self.bounds.size.width self.gameView.bounds.size.width, self.bounds.size.height self.gameView.bounds.size.height) aCoder encodeCGRect normBounds forKey "bounds" Here I save the transformation of the view, it has ONLY rotation info, not translation or scalings aCoder encodeCGAffineTransform self.transform forKey "transform" (id)initWithCoder (NSCoder )aDecoder self super initWithCoder aDecoder if (self) Restore the screen size of the device that the view was saved on saveDeviceGameViewSize aDecoder decodeCGSizeForKey "saveDeviceGameViewSize" Adjust the view center CGPoint tmpCenter aDecoder decodeCGPointForKey "center" tmpCenter.x self.gameView.bounds.size.width tmpCenter.y self.gameView.bounds.size.height self.center tmpCenter Restore the transform self.transform aDecoder decodeCGAffineTransformForKey "transform" Restore the bounds CGRect tmpBounds aDecoder decodeCGRectForKey "bounds" CGFloat ratio self.gameView.bounds.size.height saveDeviceGameViewSize.height tmpBounds.size.width (saveDeviceGameViewSize.width ratio) tmpBounds.size.height self.gameView.bounds.size.height self.bounds tmpBounds return self I am really stuck here. I cannot explain what is wrong with this code. The UIViews are correctly positioned when restored on the same device. This is not true when the level is opened on another device. There are slightly misplaced elements and distortions. Here are two pairs of screenshots demostrating the issues What is the correct approach to handle the scaling of the levels on different screens? Should I rely on AutoResizingMasks (I need to support iOS 4 and later)? In any case I would like to give a solid paradigm on how to achieve this.


How do I randomly create and store enemy data for my iPhone game? In my game you need to protect something from enemies. There can be many on the screen at once. But I don't know how to create the enemies randomly, and how I can save the data to each enemy? Can give good tips or good links to tutorials?


i want to move arrow by dragging and than want to toss throw when i give swipe event In My Application I Have One Arrow Image With Fix Center and i Can rotate it by touch move method on same center but i also need to Toss trow the arrow after doing some rotation with dragging or without doing that How Can I Put The Toss Throw Action in MyApplication Thank You Very Much In advance


Updating games for iOS 6 and new iPhone iPod Touch Say I have a game that runs full screen on iPhone 4S and older devices. The balance of the game is just right for the 480 x 320 screen and associated aspect ratio. Now I want to update my game to run full screen on the new iPhone iPod Touch where the aspect ratio of the screen is different. It seems like this can be challenging for some games in terms of maintaining the "balance". For example if the extra screen space was just tacked onto the right side of Jet Pack Joyride the balance would be thrown off since the user now has more time to see and react to obstacles. Also it could be challenging in terms of code maintenance. Perhaps Jet Pack Joyride would slightly increase the speed of approaching obstacles when the game is played on newer devices. However this quickly becomes messy when extra conditional statements are added all over the code. One solution is to have some parameters that are set in once place at start up depending on the device type. What are some strategies for updating iOS games to run on the new iPhone and iPod Touch? Edit more info I wonder what happens with a game like Plants vs Zombies? There's quite a bit of artwork that's probably sized to the 320x480 screen. Perhaps the lawn background's width can be increased while the size of the zombies and the row heights stay the same.


Which iPhone iPod Hardware to Support for iPhone Game I'm coming from a background of Android. I would like to figure out what kind of iBlah device hardware I need to support for iPhone game development something like Android's OS distribution stats, but for iBlah hardware. From my research, it seems that I need to support both iPod and iPhone. But which versions of hardware? is 3G still used? What about 3GS? For example, the S phones seem to have dual core instead of single core CPUs. I also worry about performance. In Android, I had a severely low end phone, which meant pretty much anything that ran okay there ran okay on other phones. For iPhone, how do I figure out what to support in terms of performance?


Has anyone used PhoneGap to make 2D games for the iPhone? I love simple casual games. I've been riding the bus a lot recently and so simple, no brainer games are great fun and well worth the small price I pay on the App Store. It got me thinking... I know HTML5, CSS3 and JS very well. I looked into PhoneGap and it looks like it's something I could use for making apps for the iPhone. The games I've been fleshing out myself are very simple 2D affairs. Fun, simple and high quality. That's what I'm after with my games... I also make music and my friend is an digital illustrator so together we have all the media covered. Does any one make 2D games for the iPhone using PhoneGap? I'm presuming that because I want to code in JS and use the HTML5 Canvas tag, that PhoneGap does nothing more than provide me a wrapper with a WebKit view? I know it won't be as fast as using native... But is using PhoneGap a viable option?


Cocos2d Using single timer scheduler for multiple sprites want to know if is it possible to use single timer or scheduler method for multiple sprites ? Like I am now working on a game and there could be any number of sprites and i want to perform some actions on all of that sprites, So do I have to use as many timers or schedulers as sprites ? Or How can the job be done using only a single timer or scheduler ? What is I schedule a method and use it for, Say 10 sprites ? Will it affect the performance..?


How do you get textures out of a png file I have 1 png of many different textures. I want to use these textures in my iphone game using cocos2d. I found the program "Zwoptex" where you can combine many textures to one png and create a plist file that you can use in your program. But if you have already a png file how do you get all these textures out of this file automatically OR how do I create a plist file from this png file?


Saving data in games? I'm soon going to make a game for the iPhone as a school project. My idea was to make a TLOZ remake, with Tiled Maps. However, I'm not quite sure how save the data. In TLOZ you have a lot of sub quests, treasures, items, and much more. I want the user to only be able to open a treasure once. Therefore I have to save this information somehow. However, I'm not sure how to assign the data to that certain object, for example that treasure that Link has opened. I thought about making id's for every object, but I'll have multiple maps, and it doesn't seem like the right solution. Are there any standards for this? Or does anyone have another idea?


What to think about when designing a simple GUI for a quiz game I am coming close to finish my first iPhone game ever, as a matter of fact also my first programming experience ever, which is a quiz game. I have all the functionality i want and is currently polishing it both from a code point of view as well as looking at the GUI. My initial idea was not to use any specific graphics but rather focus on the game experience and simplicity and by that only using background color, orange, and white text as well as buttons. The design is based on that all ages, from learning to read, should be able to host and play this game. However, as i am now getting close to the finish line i am starting to think what is needed from a GUI point of view. I would like to ask for some advice what to think about when designing a GUI. Is it considered OK without any 'fancy' graphics, what is the risk without it etc.? Also, what colors goes well together if i choose to use a simple GUI. I am thinking about color blindness etc. In other words how do i design a good and effective GUI for a simple game as mine? Thanks


As an Android dev, what should I keep in mind for porting to iPhone? As an Android game developer, what should I keep in mind while developing my game if I ever wanted to cross platform the game to the iPhone? Any strategies, tips, etc. on porting to both of these mobile platforms?


How can I create a smooth simulation for a fast paced, multiplayer table hockey game? I'm adding multiplayer to an iPhone game that we have in our company. It's a sort of 'table hockey' game, with a puck and two mallets. It's a pretty fast game, so I need a smooth experience at both ends. What I'm doing right now is using Game Center, and setting up the iPhone that starts the game as the "server." So, the client runs its physics the same as the server, but the server adjusts the speed of the puck on the client and adjust its position when they are going on the same direction. The problem that it has some glitches, when the physics simulations differs a bit between then and the server sends the command to correct and the client kind of jumps around. Does anyone has a suggestion how should I can handle this? Or should I try a different way?


What does everyone like to use for UI elements for their games on the iPhone? I'm asking this to get everyone's opinion I realize there isn't one "right way" to do this. I've tried a few ways myself, including using Cocoa for everything including the game itself (good for simpler games, like card games for example), using Cocoa for the screens outside of the game and using my game engine to present game objects on the screen as UI. What do people prefer to use for game UI? I'm particularly interested in hearing about why you chose to go that way and if you found that your choice was a good one after implementing it.


Make a layer over an image and adjust its co ordinates by touch I need to make a layer over an image and adjust the layer to fit to image and get its co ordinates of the layer. I need to adjust the layer by touch and pinch. The sample image is as below. I need to do this in ios, and can I get any ideas to do this?


What should I use for the event name when logging metrics with Flurry? I'm working on a multiplayer game and I want to use Flurry to record game events. In the game you can build, grow and train troops. In Flurry you can log an event (optionally with parameters). It would be great to be able to track the progress of a player depending upon what kinds of things they build, grow and so on and at what experience levels they do that at, but I don't know whether it's best to just have different sets of events for different types of actions... like this NSDictionary buildParams NSDictionary dictionaryWithObjectsAndKeys "Build Type", "Castle", "EXP", "234523", Capture user status nil Flurry logEvent "Build Action" withParameters buildParams And so on... so another for growing something, another for training, et cetera. Or is it better to have one global type of record of an event like this NSDictionary actionParams NSDictionary dictionaryWithObjectsAndKeys "Action", "Build", "Type", "Castle", "EXP", "44234", nil Flurry logEvent "Game Action" withParameters actionParams In this method all the data is stored in the one event type. I'm not sure which will give me the best result when it comes to funneling, segmentation, and all that?


Game Development Resources? I want to make an iPhone game and I was wondering if somebody could point me to some resources. Before you rage and close this, I am not looking for just a tutorial on programming, I could just google that. I need to find a tutorial on how to actually make a game, as in how to organize your code, what type of methods to run in separate threads, how to manage these threads in a game, etc. I already know everything I need I can write a physics engine from scratch, I can write a 3D graphics pipeline from scratch, and so on. What I cannot figure out is how to combine all of this knowledge into correctly and efficiently making a game. Obviously for this one would probably go to college, but seeing as I am still in high school, that is not an option. If anyone would know some tutorials or resources, any pointers would be appreciated.


Cocos 2D Hold down CCMenuItem I am using the following code to move a CCSprite left and right. (id)init CCMenuItemImage moveLeftButton CCMenuItemImage itemFromNormalImage "Move Left Button.png" selectedImage "Move Left Button.png" target self selector selector(moveLeftVoid ) (void)moveLeftVoid id moveLeft CCMoveBy actionWithDuration .3 position ccp( 10, 0) mainSprite runAction moveLeft This does work, but only as a single tap. What I want for the CCSprite to move continously in that direction when the CCMenuItem is held down. Then when it's released the character stops moving. If you need to see more code, please just ask. ) Thanks


iPhone app activated before associated in app purchase activated? I recently submitted my iPhone game for review. I also approved the in app purchase for my game (and provided the in app purchase screenshot). It's a few days later and the app status has been updated from "waiting for review" to "in review"... while the in app purchase status is still "waiting for review". Could the app go live in the store before the in app purchase? If so what happens when the user tries to make the in app purchase? Anything the developer can do to remedy this?


Any way to track speed of hand movements below iPhone 3.2? I have used the pan gesture for tracking the Pixel Per Second (or speed of the movement of the hand) but the real trouble is that the PanGesture library doesn't support any deployment target less than 3.2. So how would I track the speed of hand movements below a deployment target of 3.2?


What are the restrictions of 3g online games I am looking into make a 3g online multiplayer game for the iphone. Multiplayer is my main focus but I have noticed all game apps require wi fi. Dose anyone know if this is simply an issue with the speed of the 3g network or dose apple put restrictions on their 3g network that prevents developers from doing this?


Moving 2d camera in the y direction I'm developing a simple game for the iphone and am struggling to work out the best way for the camera to follow the main character. The following picture hightlights the three main components There are 3 components to this Circle the main character Green line terrain Black background The terrain is simply made from an array of points (approx 20 points per screen width). The terrain is moved in the x direction relative to the black background in order to keep the circle in its position shown. The distance to move the terrain is simply movex circle.position.x terrain.position.x with a constant to fix the circle at some distance from the left of the screen. I am struggling to determine the best way to position the terrain in the y plane keep the focus in the character. I want to move the terrain in the y direction smoothly and not fix it to the position of the circle, so the circle can move in the y plane. If I take the same approach as the x positioning, the character is fixed at a point on the screen and the terrain moves. I could sample some terrain points either side of the character and produce an average, but in my implementation this was not smooth. I thought another approach might be to create a camera 'line' that is a smooth version of the terrain line and make the camerea follow this, but I'm not sure if this is the optimum solution. Any advice is much appreciated!


How can I implement temporary effects in Objective C? How could I use this IBAction (IBAction)shield (id)sender appDelegate.healthInt 150 and simply make it work for a limited time. I want to set appDelegate.healthint 150 for about 20 seconds. I'd assume this works with some sort of NSTimer. Not really sure. I'm not using any frameworks.


How do I open the camera in a CCScene node in a Cocos2D application? I am new to Cocos2D and I can't find the way to open the camera from the library. I want to open the camera in the my game, can any one help me with with this? Thank you in advance.


Issues with background coordinate configuration in objective c with runAction? In my game I want to have two backgrounds going one after the other creating a continuous loop moving to the left. However, right now one goes, and the other does not follow it. Here's what I currently have, which isn't working. if((self super init )) self.isTouchEnabled YES background CCSprite spriteWithFile "testbackground88.png" self addChild background z 1 background.position ccp(500,240) id repeat1 CCRepeatForever actionWithAction CCSequence actions CCMoveTo actionWithDuration 7 position ccp( 300,240) , CCPlace actionWithPosition ccp(800,240) ,nil background runAction repeat1 background2 CCSprite spriteWithFile "testbackground92.png" self addChild background2 z 1 background2.position ccp(500,240) id repeat2 CCRepeatForever actionWithAction CCSequence actions CCMoveTo actionWithDuration 7 position ccp( 300,240) , CCPlace actionWithPosition ccp(800,240) ,nil background2 runAction repeat2


RTS game engine for iOS iPhone Anyone know any free or non free RTS engine that can be used for iOS game development?


Detecting right left collisions with a bounding box I'm building a platformer in cocos2d, my first game project. I'm working on movement and collision detection. I'm using a tilemap with a "meta" layer of invisible blocks that are designated collidable. Everything seems to work pretty well except for one minor detail when the character jumps from above into a platform, he does not fall but clips through it. If he jumps from below, it recognizes it and resets his Y velocity accordingly. I know that it's because of how I'm detecting the collisions, and just doing a simple comparison of the origin.y's, but I'm unsure of how to refactor this code better (void) update (ccTime) dt CGPoint scaledVelocity ccpMult(leftJoystick.velocity, 35.0f) CGPoint newPosition ccp(player.position.x scaledVelocity.x dt, player.position.y) CGPoint oldPosition player position float velocityX player.Velocity.x scaledVelocity.x dt float velocityY player.Velocity.y BOOL isCollision NO BOOL isCollisionBelow NO BOOL isCollisionRight NO BOOL isCollisionLeft NO NSMutableArray collisionSprites NSMutableArray alloc init if (oldPosition.x gt newPosition.x) player.flipX YES else if (oldPosition.x lt newPosition.x) player.flipX NO for (CCSprite sprite in gameplayLayer.collidableTiles) if (CGRectIntersectsRect(player.boundingBox, sprite.boundingBox)) isCollision YES collisionSprites addObject sprite Figure out which direction collision is in if (isCollision) for (CCSprite collisionSprite in collisionSprites) if (collisionSprite.boundingBox.origin.y lt player.boundingBox.origin.y) isCollisionBelow YES if ((collisionSprite.boundingBox.origin.x gt player.boundingBox.origin.x) amp amp (collisionSprite.boundingBox.origin.y gt player.boundingBox.origin.y)) isCollisionRight YES if ((collisionSprite.boundingBox.origin.x lt player.boundingBox.origin.x) amp amp (collisionSprite.boundingBox.origin.y gt player.boundingBox.origin.y)) isCollisionLeft YES if (isCollisionLeft) velocityX 0.5f else if (isCollisionRight) velocityX 0.5f if (isCollision amp amp !isCollisionBelow amp amp player.characterState ! kStateFalling) velocityY 0 velocityY 0.8f player setCharacterState kStateFalling else if (!isCollisionBelow) velocityY 0.7f else if (isCollisionBelow) velocityY 0 player setCharacterState kStateIdle if (rightButton.active) if (player.characterState ! kStateJumping) velocityY 15.0f player setCharacterState kStateJumping Ground friction if (player.Velocity.x gt 0) if (player.Velocity.x lt 0.5f) velocityX 0 else velocityX 0.5f if (player.Velocity.x lt 0) velocityX 0.5f player setVelocity ccp(velocityX, velocityY) player setPosition ccp(player.position.x player.Velocity.x, player.position.y player.Velocity.y) gameplayLayer setViewpointCenter newPosition player setOldPosition player.position How can I refactor this code to work properly from all angles and reduce the complexity (I feel that there's too many booleans, and they all get a bit confusing).


Why does my sprite player move faster when I move the mouse? I'm trying to develop a simple game made with Pygame (Python library). I have a sprite object which's the player and I move it using arrow keys. If I don't move the mouse, the sprite moves normally, but when I move the mouse, the sprite moves faster (like x2 or x3). The player object is inside the charsGroup var. I've run the game in W7 and in Ubuntu. Same thing happens in both OS. I have more entities which move like NPCs and bullets but they don't get affected, just the player. Given this, I think that the problem maybe has a direct connection with the player moving system (arrow keys). Here is the update() method of the player object def update(self) for event in pygame.event.get() key pygame.key.get pressed() mouseX, mouseY pygame.mouse.get pos() if event.type pygame.MOUSEBUTTONDOWN self.bulletsGroup.add(Bullet(pygame.image.load("bullet.png"), self.rect.x (self.image.get width() 2), self.rect.y (self.image.get height() 2), mouseX, mouseY, 50, 50)) if key pygame.K RIGHT if not self.checkCollision() self.rect.x 10 else self.rect.x 10 if key pygame.K LEFT if not self.checkCollision() self.rect.x 10 else self.rect.x 10 if key pygame.K UP if not self.checkCollision() self.rect.y 10 else self.rect.y 10 if key pygame.K DOWN if not self.checkCollision() self.rect.y 10 else self.rect.y 10 And here is the while loop while True if PLAYER.healthBase lt 0 GAMEOVER True if not GAMEOVER mapTilesGroup.draw(SCREEN) charsGroup.update() charsGroup.draw(SCREEN) npcsGroup.update() npcsGroup.draw(SCREEN) drawBullets() for event in pygame.event.get() if event.type pygame.QUIT pygame.quit() sys.exit() if GAMEOVER myfont pygame.font.SysFont("monospace", 30) label myfont.render("GAME OVER!", 1, (255, 255, 0)) SCREEN.blit(label, (400, 300)) freq.tick(0) pygame.display.flip() I don't know what more you can need to help me, but anything you need (more info or code) just ask for it!


Varying framerate (FPS) In my game loop, I am using fixed time step for physics and interpolation for rendering as suggested on Gaffer on Games Fix Your Timestep! However, when the framerate is varying between 30 60fps during the game, the game looks jumpy. For example, balls suddenly look accelerated when the frame rate increases from 35 to 45 suddenly. Is there a way to make the game look smooth while framerate is varying? Here is my game loop protected void update(float deltaTime) do some pre stuff deltaTimeAccumulator deltaTime deltaTimeAccumulator is a class member holding the accumulated frame time while(deltaTimeAccumulator gt FIXED TIME STEP) world.step(FIXED TIME STEP, 6, 2) perform physics simulation deltaTimeAccumulator FIXED TIME STEP world.step(deltaTime, 6, 2) destroyBodiesScheduledForRemoval() render(deltaTimeAccumulator FIXED TIME STEP) interpolate according to the remaining time Here is the part related to the interpolation (related inner works of render() method) this.prevPosition this.position get previously simulated position this.position body.getPosition() get currently simulated position interpolate Vector2 renderedPosition new Vector2() if (prevPosition ! null) amp amp !isFloatApproximatelyEquals(this.prevPosition.x, this.position.x) amp amp !isFloatApproximatelyEquals(this.prevPosition.y, this.position.y)) renderedPosition.x this.position.x interpolationAlpha this.prevPosition.x (1 interpolationAlpha) renderedPosition.y this.position.y interpolationAlpha this.prevPosition.y (1 interpolationAlpha) else renderedPosition position Draw the object at renderedPosition


How and when should I update events occuring after a while? This question is not language specific but a more generic approach on how to deal with lazy updates for some game variables. Let's say, for instance, that I want to implement a "character age system" for a game. I guess that the "age" attribute does not need to be updated 60 times per second for each of my 10.000 or so RTS MMO characters. So, how to implement in the game loop the update of this "long term" variables that may have it value changed very sparsely? At the moment, I would implement some global variables to accumulate the delta time between the frames until it reaches a certain value, then, it resets and updates that variables. Is that correct? I mean, that's how things work? Or depending on the language plataform you would set some timers, or events that trigger the update of these variables?


random spike in delta time The title pretty much sums it up. I'm using delta time to move my objects and every few seconds the delta time will spike and all the objects will jump forward. Should I just Interpolate the delta time to eliminate spikes, I don't want to do this because it could cause other problems but it could be a solution


Design of a turn based game where actions have side effects I am writing a computer version of the game Dominion. It is a turn based card game where action cards, treasure cards, and victory point cards are accumulated into a player's personal deck. I have the class structure pretty well developed, and I am starting to design the game logic. I'm using python, and I may add a simple GUI with pygame later. The turn sequence of the players is governed by a very simple state machine. Turns pass clockwise, and a player can't exit the game before it is over. The play of a single turn is also a state machine in general, players pass through an "action phase", a "buy phase", and a "clean up phase" (in that order). Based on the answer to the question How to implement turn based game engine?, the state machine is a standard technique for this situation. My problem is that during a player's action phase, she can use an action card that has side effects, either on herself, or on one or more of the other players. For example, one action card allows a player to take a second turn immediately following the conclusion of the current turn. Another action card causes all other players to discard two cards from their hands. Yet another action card does nothing for the current turn, but allows a player to draw extra cards on her next turn. To make things even more complicated, there are frequently new expansions to the game that add new cards. It seems to me that hard coding the results of every action card into the game's state machine would be both ugly and unadaptable. The answer to Turn based Strategy Loop does not go into a level of detail that addresses designs to solve this problem. What kind of programming model should I use to encompass the fact that the general pattern for taking turns can be modified by actions that take place within the turn? Should the game object keep track of the effects of every action card? Or, if the cards should implement their own effects (e.g. by implementing an interface), what setup is required to give them enough power? I have thought up a few solutions to this problem, but I am wondering if there is a standard way to solve it. Specifically, I'd like to know what object class whatever is responsible for keeping track of the actions that every player must do as a consequence of an action card being played, and also how that relates to temporary changes in the normal sequence of the turn state machine.


Implement an upper FPS limit in the gameloop I implemented my game loop as described in deWiTTER's article, using the last approach with an unlimited FPS and a constant game speed. My problem is, that the unlimited FPS cranks up my CPU usage to nearly 100 . I understand that this is desired (as the hardware does as much as it can), but for my game, it's not really necessary (it's pretty simple). So I'd like to limit the FPS to some upper bound. Consider my game loop private static final int UPDATES PER SECOND 25 private static final int WAIT TICKS 1000 UPDATES PER SECOND private static final int MAX FRAMESKIP 5 long next update System.currentTimeMillis() int frames skipped float interpolation Start the loop while (isRunning) Update game frames skipped 0 while (System.currentTimeMillis() gt next update amp amp frames skipped lt MAX FRAMESKIP) Update input, move objects, do collision detection... Schedule next update next update WAIT TICKS frames skipped Calculate interpolation for smooth animation between states interpolation ((float)(System.currentTimeMillis() WAIT TICKS next update)) ((float)WAIT TICKS) Render events repaint(interpolation) How would I implement a maximum FPS? If i implement the repaint the way I implemented the update (or use a sleep instead of "do nothing cycles"), then the FPS is locked, right? That is not what I want. I want the game to be able to work with lower FPS (just as it does now), but limit the FPS to a maximum of, say 250.


Windows Forms game loop There is a very good game loop in the link which is tailored for windows forms. I need it in c cli so I converted the code as below. Here is my main loop. using namespace System using namespace System Windows Forms HWND g theAppHandle nullptr bool IsApplicationIdle() MSG msg return PeekMessage( amp msg, g theAppHandle, 0, 0, 0) 0 void OnIdle(System Object sender, System EventArgs e) while (IsApplicationIdle()) if (PunkEd ABTCLI g initSuccess) PunkEd ABTCLI Frame(0.0f) STAThread int CALLBACK WinMain( In HINSTANCE hInstance, In HINSTANCE hPrevInstance, In LPSTR lpCmdLine, In int nCmdShow ) CrtMemState memstate CrtMemCheckpoint( amp memstate) PunkEd PunkEdMain theApp gcnew PunkEd PunkEdMain g theAppHandle (HWND)theApp gt Handle.ToPointer() Application Idle gcnew System EventHandler( amp OnIdle) Application Run(theApp) CrtMemDumpAllObjectsSince( amp memstate) return 0 This loop triggers PunkEd ABTCLI Frame(0.0f) every time the application is idle. And Frame(float deltaTime) function triggers everyting related to game. Like render and physics. However my rendering window is a panel. And I override its mouse move callback as below. private System Void panel1 MouseMove(System Object sender, System Windows Forms MouseEventArgs e) Debug WriteLine(e gt Location) glm vec3 cp glm vec3(e gt Location.X, e gt Location.Y, 0) glm mat4 view g camera gt GetViewMatrix() glm mat4 project g camera gt m projection glm unProject(cp, view, project, glm vec4(0.0f, 0.0f, (float)panel1 gt Width, (float)panel1 gt Height)) cp.x panel1 gt Width 2.0f cp.y panel1 gt Height 2.0f g cursor gt m node gt m translation cp.xzy This function updates my curser's position in the game. However my render function is get called after I stop moving the mouse. How can I overcome this stuation such that my curser position gets update and renders immediatly after I moved mouse.


JavaFX AnimationTimer VS Swing Game Loop After looking at some code sources out there I noticed Java Swing Games usually create a class implementing Runnable, create a new Thread and set up the game loop in the run() call. But JavaFX games seem to simply extend from Application and run the game loop in a new AnimationTimer() ... public void handle() ... What gives?


NodeJS setTimeOut How to run callback before delay time exceeded I'm developing a card game server. I want to do this While server process a turn for players, players have 20 seconds to do something. If players send a request to server within 20 secs, timer will stop and the callback will fire. I'm doing like this self.tables table.id .currentTimer setTimeout(function () callback() , 20 1000) How should I run the callback before delay time exceeded ?


How do games implement client server frame rate? Do games have a frame rate at X fps that updates logic and also renders? Or do games update logic at a much slower frame rate than rendering? Let's say 20 25 fps for logic, and 60 fps for rendering. I am writing a game engine and I am a bit confused on how frame rate is handled. If I were to run logic slower than rendering, then wouldn't I just be wasting the rendering frames because it is rendering the same thing over and over...? Unless I also interpolate the rendering with a delta. I have read some game servers run at a much slower frame rate (let's say 20 FPS), so shouldn't the client also run logic at 20 FPS?


What is the point of update independent rendering in a game loop? There are dozens of articles, books and discussions out there on game loops. However, I pretty often come across something like this while(running) processInput() while(isTimeForUpdate) update() render() What basically is bothering me about this approach is the "update independent" rendering e.g. render a frame when there is no change at all. So my question is why this approach is often taught?


Game Loop Problem Growth and Recharge as Integer Values I have a question about game loops. I understand that you shouldn't have a static loop, say 100ms and set something's speed to 1px frame so it moves 10px sec. You should have a speed and multiple that by the elapsed time so frame rate does not effect game speed. This works fine for values that can be floats, but what if I need integer values? Say shields recharging or something. I have a damage system is my game and I would really love to stay away from float damage values, both for memory and game design reasons. However if I just have a running total of elapsed time, and I recharge one point once this elapsed time is over 1 second then over the course of time won't I have some consistency errors between recharging over one set of 100 real seconds and another set of 100 real seconds because those two sets may not have the same number of frames in them. This questions also comes up in rate of fire. If I need a turret to fire every .5seconds, won't there be some variance if I do a running total of elapsed time? Sometimes it may fire every .501 seconds and other time .510 seconds? I guess my question is, how exact are games really? Do most games just do a check every frame and say, "Well your rate of fire is .5 seconds, and its been .504 since you last fired, so fire now." If so would it work out for the next fire cycle to only check for .496 seconds to average out? I know it most games under 10 minutes this would barely be noticeable, but over the long term this may actually mater in some cases.


Separate draw and physics loops I there a point in updating the physics at a different rate than drawing taking input? Is it just to exploit parallelism? I've heard that many engines update the physics at 15FPS but render at 60FPS. What's the point in rendering the same image four times until it changes if it doesn't add fluidity?


LUA Keeping track of game state for a digital card trading game I am building a card game. Let's say it's similar to Magic the Gathering, Hearthstone, etc. The problem I am trying to figure out is how to architect "auras" and how much damage each card takes. Right now I have a deck and I store card data as follows. I've made up names for the types of cards that will exist. M.card Minion cards have health and damage M.card 1 .name "Minion" M.card 1 .hp 1 M.deck 1 .dmg 1 Super Minions have more health and damage M.card 2 .name "Super Minion" M.card 2 .hp 4 M.card 2 .dmg 4 Spell cards have no health and damage. Instead they affect the health and damage of other cards. M.card 3 .name "Heal" M.card 3 .details "This card heals any character for 2 health" M.card 3 .healthboost 2 M.card 4 .name "Damage Boost" M.card 4 .details "This card gives 1 damage to any other card for 1 turn" M.card 4 .dmgboost 1 Super damage boost gives more damage boost to other cards M.card 5 .name "Super Damage Boost" M.card 5 .details "This card gives 3 damage to any other card permanently" M.card 5 .dmgboost 3 So when one card attacks another card, I need to keep track of the damage taken by both cards. I don't want to change the base stats of each card so I need to keep track of adjustments. I could do something like this Super Minion takes 3 damage M.card 2 .newHp 1 or M.card 2 .adjHp 3 Not sure which is better. During the battle I need to keep track of which auras are played. So for example if the Damage boost card is played. I need to give another card 1 damage for just one turn. Let's say that I am keep track of each turn number starting from 1. Should I do something like this M.aura 1 4 ( aura 1 is card 4) M.aura 1 .target 2 (this aura is applied to card 2) M.aura 1 .expires 5 (this aura expires on turn 5) M.aura 2 3 ( second active aura is heal, card 3 ) M.aura 2 .target 2 M.aura 2 .expires 0 this is a one time aura. So I need to apply it to card 2 and then immediately expire it so it never activates again. Then on every new turn I loop through all the auras and make sure they are still active before a fight begins? Just wondering architecturally what is the best way to keep track of Damage that characters have taken and spells that are active that are giving characters special abilities.


Game loops using Hard realtime systems vs Soft realtime systems I have read the article here about realtime systems and am looking for examples specific to game loops. Am I correct in saying Hard realtime systems will lag and slow down gameplay causing slow motion if processing of AI, collision detection, or user input is delayed past the rendering deadline set by the realtime system. Example, must render every 1 30 sec but processing caused delay to 1 20 sec. Soft realtime systems will render at 30 FPS regardless of the other subsystems processing but if there is a delay in AI, collision detection, or user inputs, the game will be presented in stop motion instead of slow motion every 1 30 sec.


Delta times and frame lag in the game loop Let's say we have a standard gameloop like this, in pseudocode while (true) dt GetDeltaTime() Update(dt) Render() Here Update(dt) either uses a true variable timestep, or it determines how many cycles of a fixed timestep physics loop to execute based on dt. Now say we have the common case where we have mostly constant framerate except for infrequent single frame hiccups, so let's say we have dt values like 1 60, 1 60, 1 60, 1 6, 1 60, 1 60, ... By the time our GetDeltaTime() detects the larger timestep in the fourth frame, we have already rendered and presented the fourth frame! So one frame will already have been rendered with a wrong (too small) timestep no matter what we do. So if we now use the larger dt 1 6 to render the fifth frame, my understanding is that we artificially create a second frame where a wrong timestep is used, this time a too large one. I wonder if this problem is acknowledged anywhere. Wouldn't it be better, say, to use the averaged dt over the previous few frames to combat this? Here are some pictures to illustrate what I mean. I use the example of an object moving along a fixed axis with a constant speed, and using a variable timestepping scheme. The problem is essentially the same with fixed timesteps, though. The plots have time on the x axis, and the object position on the y axis. Let's say the object moving at 1 unit s, and framerate is 1 Hz. This is the ideal situation. Now let's say we have a frame where the time interval is 2 instead of 1. With a classical dt based scheme, we get this So we have one frame where the velocity is perceived too low, and one where it is perceived too high and which corrects for the velocity in the previous frame. What if we instead, say, always use a constant (or very slowly changing) dt? We get this The perceived velocity seems smoother using this approach to me. Of course, the object position is now not the "true" one, but I think humans perceive abrupt changes in velocity more clearly than such small positional offsets. Thoughts? UPDATE At least Ogre can do this http ogre.sourcearchive.com documentation 1.6.4.dfsg1 1 classOgre 1 1Root 1f045bf046a75d65e6ddc71f4ebe0b2c.html So I guess I just got downvoted for people not understanding my question, which is rather frustrating.


UPS and FPS What should I limit and why? I'm currently writing a game using C and SDL2 and there's one thing that I'm wondering about does it make sense to limit my frames per second (FPS) and or my updates per second (UPS)? I get the idea that if you limit the UPS, you essentially control the speed of the game if the player moves 1px per update and you always update it 30 times per second, he'll move at a speed of 30px s and you'll probably also relieve the CPU since the amount of calculations per second decreases. If you limit the FPS, the amount of drawcalls per second decreases, therefore you relieve your GPU. I hope I understood all of that correctly, if not, feel free to correct me. My question is what am I supposed to limit in my game? FPS? UPS? Both? Neither? Is there another, better approach to this? How is this done in most games and why? Answers are greatly appreciated!


render draw or input first? When creating the main game loop, what order should things generally happen? IE, should i be getting input, doing logic and then rendering, or something else? does this even matter? when i was coding with python and pygame the tutorial i was using pointed me towards the aforementioned method. however, A tutorial for LWJGL2 (http thecodinguniverse.com lwjgl window ) does it like this while (!Display.isCloseRequested()) While no attempt to close the display is made.. Put render code here. Put input handling code here. Display.update() Refresh the display and poll input. Display.sync(60) Wait until 16.67 milliseconds have passed. (Maintain 60 frames per second) and (so far) doesn't seem to have hinted at logic (though i assume it will later on, and looks like it might put it last) so which should i be using? does it matter at all? i'm using LWJGL2.


Exchanging data between custom built hardware and games I have a built my own steering wheel and motion platform that I would like to connect to popular car racing games (e.g. iRacing, Dirt Rally). I need to read data such as the car's acceleration (to send to the motion platform) from these games and send information such as steering wheel's angle to the game. I have written an SDK in C to communicate with my steering will and motion platform. Now I need to interface different games with to that SDK. I searched quite a bit but could not find much information about how this is generally done. Do game developers provide some sort of extension which allows third party hardware developers to communicate with their game? Any guidance from the community is much appreciated. Kam


How and when should I update events occuring after a while? This question is not language specific but a more generic approach on how to deal with lazy updates for some game variables. Let's say, for instance, that I want to implement a "character age system" for a game. I guess that the "age" attribute does not need to be updated 60 times per second for each of my 10.000 or so RTS MMO characters. So, how to implement in the game loop the update of this "long term" variables that may have it value changed very sparsely? At the moment, I would implement some global variables to accumulate the delta time between the frames until it reaches a certain value, then, it resets and updates that variables. Is that correct? I mean, that's how things work? Or depending on the language plataform you would set some timers, or events that trigger the update of these variables?


Events and objects being skipped in GameMaker Update Turns out it's not an issue with this code (or at least not entirely). Somehow the objects I use for keylogging and player automation (basic ai that plays the game) are being 'skipped' or not loaded about half the time. These are invisible objects in a room that have basic effects such are simulating button presses, or logging them. I don't know how to better explain this problem without putting up all my code, so unless someone has heard of this issue I guess I'll be banging my head against the desk for a bit Update I've been continuing work on modifying Spelunky, but I've run into a pretty major issue with GameMaker, which I hope is me just doing something wrong. I have the code below, which is supposed to write log files named sequentially. It's placed in a End Room event such that when a player finishes a level, it'll write all their keypress's to file. The problem is that it randomly skips files, and when it reaches about 30 logs it stops creating any new files. var file name file count 4 file name file find first("logs .txt", 0) while (file name ! "") file count 1 file name file find next() file find close() file file text open write("logs log" string(file count) ".txt") for(i 0 i lt ds list size(keyCodes) i 1) file text write string(file, string(ds list find value(keyCodes, i))) file text write string(file, " ") file text write string(file, string(ds list find value(keyTimes, i))) file text writeln(file) file text close(file) My best guess is that the first counting loop is taking too long and the whole thing is getting dropped? Also, if anyone can tell me of a better way to have sequentially numbered log files that would also be great. Log files have to continue counting over multiple start stops of the game.


how to handle interactive choice in the middle of the game loop? I am programming a turn based game, 2D tile based, overhead view. I have an update function and a render function running in separate threads. When it's the player's turn, the player can e.g. select a target tile from the map then a popup menu with the available interactions appears player selects interaction and the interaction gets executed One tedious way is the following GameLoopUpdate() switch( interaction state ) case tile selected lookup interactions for selected tile() break case tile and interaction selected() execute interaction at tile() break default break Of course the above does not scale when the interactions get complex. Conceptually, I would like it to be more like KeyListener() if tile is clicked set tile selected() GameLoopUpdate() if tile is selected interaction spawn thread interaction selection() execute interaction at tile( interaction ) where the spawned thread would somehow override the input listeners AND the rendering. But this looks bad as well. Another idea (I'm starting to consider implementing this) is the following GameLoopUpdate() if it's player's turn set next state as PlayerState Base else run ai turn PlayerState Base() if tile is selected set next state as PlayerState TileSelected PlayerState TileSelected() if interaction is selected execute interaction set player's turn as done where each state above would have dedicated key listener and rendering functions Any other ideas?


Is creating a separate thread for each game session a bad idea? I'm currently working on iocp game server. My game is just like diablo3 basically. 1 4 players join a separate session. I did basic iocp preparations and now I'm working on game session class. The reason why I'm stuck right now is that I'm not sure if I should create a separate thread for each game session. This concept is the first idea that I came up with but I can't come up with other ideas to avoid creating so many threads for sessions when there are so many game sessions. So here's my question. Should I create a separate game logic loop(thread) for each game session? Because that sounds so inefficient when it comes to the situation where only one player joins each session. If there are some other ways to design the server, please let me know what I should look for to study. Thanks for your help in advance and sorry for my bad English.


random spike in delta time The title pretty much sums it up. I'm using delta time to move my objects and every few seconds the delta time will spike and all the objects will jump forward. Should I just Interpolate the delta time to eliminate spikes, I don't want to do this because it could cause other problems but it could be a solution


Why does the triangle rendered by OpenGL ES 2.0 , with SDL 2.0 context, vanishes after a single render, if events are not polled? I was experimenting with OpenGL ES 2.0 and being new to OpenGL, I was trying to render a simple triangle. But I was shocked to see that, if I do not call SDL PollEvent(...) after glDrawArrays(...) in the game loop, I see the triangle render on the screen for a split second and then it vanishes altogether ! But, if I call SDL PollEvent then everything is fine ! Can anyone explain to me the reason for this abnormal behavior??? However, this is the interesting part of my code This code works perfectly, if I uncomment the commented block of code uint32 t vbo glGenBuffers(1, amp vbo) glBindBuffer(GL ARRAY BUFFER, vbo) glBufferData(GL ARRAY BUFFER, sizeof(vertices), vertices, GL STATIC DRAW) glEnableVertexAttribArray(pos) glVertexAttribPointer(pos, 3, GL FLOAT, GL FALSE, 3 sizeof(float), (void )0) bool run true SDL Event e while (run) glDrawArrays(GL TRIANGLES, 0, 3) SDL GL SwapWindow(window) while(SDL PollEvent( amp e)) switch(e.type) case SDL QUIT run false break Vertex Shader precision mediump float attribute vec3 pos void main() gl Position vec4(pos.xyz, 1.0) Fragment Shader precision mediump float void main() gl FragColor vec4(0.0, 0.0, 1.0, 1.0) Every help will be greatly appreciated, Thankyou everyone in advance !


JavaFX AnimationTimer VS Swing Game Loop After looking at some code sources out there I noticed Java Swing Games usually create a class implementing Runnable, create a new Thread and set up the game loop in the run() call. But JavaFX games seem to simply extend from Application and run the game loop in a new AnimationTimer() ... public void handle() ... What gives?


Varying framerate (FPS) In my game loop, I am using fixed time step for physics and interpolation for rendering as suggested on Gaffer on Games Fix Your Timestep! However, when the framerate is varying between 30 60fps during the game, the game looks jumpy. For example, balls suddenly look accelerated when the frame rate increases from 35 to 45 suddenly. Is there a way to make the game look smooth while framerate is varying? Here is my game loop protected void update(float deltaTime) do some pre stuff deltaTimeAccumulator deltaTime deltaTimeAccumulator is a class member holding the accumulated frame time while(deltaTimeAccumulator gt FIXED TIME STEP) world.step(FIXED TIME STEP, 6, 2) perform physics simulation deltaTimeAccumulator FIXED TIME STEP world.step(deltaTime, 6, 2) destroyBodiesScheduledForRemoval() render(deltaTimeAccumulator FIXED TIME STEP) interpolate according to the remaining time Here is the part related to the interpolation (related inner works of render() method) this.prevPosition this.position get previously simulated position this.position body.getPosition() get currently simulated position interpolate Vector2 renderedPosition new Vector2() if (prevPosition ! null) amp amp !isFloatApproximatelyEquals(this.prevPosition.x, this.position.x) amp amp !isFloatApproximatelyEquals(this.prevPosition.y, this.position.y)) renderedPosition.x this.position.x interpolationAlpha this.prevPosition.x (1 interpolationAlpha) renderedPosition.y this.position.y interpolationAlpha this.prevPosition.y (1 interpolationAlpha) else renderedPosition position Draw the object at renderedPosition


Games development with a game loop that's abstracted away Most game development happens with a main game loop. Are there any good articles blog posts discussions about games without a game loop? I imagine they'd mostly be web games, but I'd be interested in hearing otherwise. (As a side note, I think it's really interesting that the concept is almost exclusively used in gaming as far as I'm aware, perhaps that may be another question.) Edit I realize there's probably a redraw loop somewhere. I guess what I really mean is a loop that is hidden to you. Frames are something you as the developer are not concerned with as you're working on a higher level of abstraction. E.g. someLootItem.moveTo(inventory, someAnimatationType) and that will move from the loot box to your inventory using the specified animation type without the game developer having to worry about the implementation details of that animation. Maybe that's how "real" games end up working, but from reading most tutorials they seem to imply a much more granular level of control is used, but that might just be an artifact of being a tutorial. Edit2 I think most people are misunderstanding what I'm trying to ask, likely because I'm having trouble describing exactly what I'm trying to ask. After some more thinking perhaps what I'm referring to is more along the lines of what I believe is referred to as "scripting" where you're working at a very high level and having some game engine take care of the low level details. For example, take custom maps in Starcraft II or Warcraft III. Many of the "maps" have gameplay that deviates enough from the primary game that they could be considered a separate game written on the same engine. What I'm referring to then is along those lines. I may be wrong because I only dabbed in the Warcraft III editor, but as far as I remember no where in the map editor do you control the game loop, and yet you can create many different games out of it. In my mind, these are games in their own right. If you're playing DotA you don't say you're playing Warcraft III, you say you're playing DotA because that's the actual game you're playing. Such a system may impose limitations that don't exist if you're creating a game from scratch, but it greatly reduces development time because much of the "hard" work has already been done for you. Hopefully that clarifies what I'm asking. Another example of what is I mean, is when you write a web app, of course it communicates through sockets and TCP. But does the average web developer doesn't explicitly write code for connecting sockets. They just need to know about receiving a request and sending a response. There are unique scenarios where you do occasionally need to use raw sockets, but it's generally rare in web development. In a similar fashion, it's very possible to write a game without directly using the game loop, even though one is used behind the scenes. Probably not a AAA title, but there must be hundreds of smaller scale games that can and possibly are written this way. Are there any good resources on writing these "simpler" games?


Why does my sprite player move faster when I move the mouse? I'm trying to develop a simple game made with Pygame (Python library). I have a sprite object which's the player and I move it using arrow keys. If I don't move the mouse, the sprite moves normally, but when I move the mouse, the sprite moves faster (like x2 or x3). The player object is inside the charsGroup var. I've run the game in W7 and in Ubuntu. Same thing happens in both OS. I have more entities which move like NPCs and bullets but they don't get affected, just the player. Given this, I think that the problem maybe has a direct connection with the player moving system (arrow keys). Here is the update() method of the player object def update(self) for event in pygame.event.get() key pygame.key.get pressed() mouseX, mouseY pygame.mouse.get pos() if event.type pygame.MOUSEBUTTONDOWN self.bulletsGroup.add(Bullet(pygame.image.load("bullet.png"), self.rect.x (self.image.get width() 2), self.rect.y (self.image.get height() 2), mouseX, mouseY, 50, 50)) if key pygame.K RIGHT if not self.checkCollision() self.rect.x 10 else self.rect.x 10 if key pygame.K LEFT if not self.checkCollision() self.rect.x 10 else self.rect.x 10 if key pygame.K UP if not self.checkCollision() self.rect.y 10 else self.rect.y 10 if key pygame.K DOWN if not self.checkCollision() self.rect.y 10 else self.rect.y 10 And here is the while loop while True if PLAYER.healthBase lt 0 GAMEOVER True if not GAMEOVER mapTilesGroup.draw(SCREEN) charsGroup.update() charsGroup.draw(SCREEN) npcsGroup.update() npcsGroup.draw(SCREEN) drawBullets() for event in pygame.event.get() if event.type pygame.QUIT pygame.quit() sys.exit() if GAMEOVER myfont pygame.font.SysFont("monospace", 30) label myfont.render("GAME OVER!", 1, (255, 255, 0)) SCREEN.blit(label, (400, 300)) freq.tick(0) pygame.display.flip() I don't know what more you can need to help me, but anything you need (more info or code) just ask for it!


Game Logic Update Order Is there a commonly accepted general approach to the order of processing logic updates? My current 2D platformer has objects that implement different concerns, including the following Notifiable can be event driven and scripted Collidable can interact with solid tiles (eg NPCs) Intersectable exists in 2D space and can intersect with the player (eg doors) In general the order of events in a game loop is Get input Act on input and update stuff Render I'm not sure what order to do things in point 2. I've concluded moving things like moving platforms that the player can stand on first is a good idea, but I don't know when to consider scripting. The scripting in my game can give NPCs behaviours (walk between here and there), suspend player input for 'cutscenes', show dialog screens, and move the player to a new level.


Game Loop design that is speed hack proof I'm not sure if this is possible, but it's worth a shot asking. How does one design a game loop in such a way that hooking and enabling a speed hack app to the game(dx11) doesn't matter? I found this in stackoverflow I think the reason why i does not work in some applications (mostly games) is because some games link the in game clock to the frames per second. Therefore your game will either tank or crash altogether if you try to speedhack it ref https stackoverflow.com questions 17512906 how does cheatengines speed hack work


What is the point of update independent rendering in a game loop? There are dozens of articles, books and discussions out there on game loops. However, I pretty often come across something like this while(running) processInput() while(isTimeForUpdate) update() render() What basically is bothering me about this approach is the "update independent" rendering e.g. render a frame when there is no change at all. So my question is why this approach is often taught?