game state update structure and distribution in MMO? I'm developing an MMO, which has to maintain a global game state. Now I want to distribute the updates, which the players make to this state, to players which can see those updates (area of interest etc.) Is there a common structure format for these updates and for a global game state? Like, every action a player sends to the server has to include a type, the coordinates etc. And are the updates, which gets distributed from the server to the players in the same format or are they different? Also should I include timestamps or use the receive time from the server to check which action came first and which sencond etc.? And what should I send back to the player if he send an invalid action?


Should I keep login server apart from game server? I'm thinking of making a MMO server, and I've been looking at how other games structure their network. One of the things I've noticed is that there's always a Login server and then the game server(s). I'm still deciding if I should do this, but I would like to hear some opinions first. What are the advantages of this, and how does the login server communicates with game server to handle logins?


List of Anti Cheat Packages for MMOs? i would like to start this topic for programs to counter attack link text. I am not aware of a big list but with everyone's help i hope to make this a fine topic. Posting format NAME nProtect GameGuard GAME TYPE any type of game Website http global.nprotect.com product gg.php FEATURES? Protect the users' PC from fast evolving hacking technologies and viruses. Real time protection, diagnose various patterns latest hacking tools that can harm games, but also memory debugging prevention technology will be applied, completely blocking hacking tools through real time hacking tool monitoring and blocking function. Blocks hacking attacks through memory scan Blocks online outflow of personal information


is it possible to make a MMO starting with scalable hosting? I made a really basic 2D RPG. I want to know whether I can turn it into a free to play MMO. I cannot afford to rent a server with enough capacity to serve a big number of players but I'm wondering whether I could get a hosting plan that starts cheap but scales enough to eventually handle a big numer of users so I have minimum fixed costs and I can cover expenses on the go with ads or whatever. Is there such a thing? Thanks


Why are so many games not fully voiced? I'm wondering why so many MMOs are only partially voiced? I asked makers of games (Thimbleweed Park, in their Q amp A) how expensive voiceover is, and they said it wasn't especially expensive unless you hire A list stars. So why would so much game dialogue be only present as text to be read onscreen? The only reason I can think of is the same that exists for localization in all software You can't record VO until all the dialogue is finished and frozen, so it is another fixed delay between finishing the rest of the game and shipping. So it doesn't seem like it's not manageable. To be clear I'm not looking for opinions or theories (that would only make the mods close this question) but actual reasons and experiences from people who have shipped games with partial voiceover.


Fair monetization of a MMO with a simulated economy I am in the design phase of a MMO game based around flying age of sail airships. Players will be able to captain their own ship (owned by their in game nation or faction or themselves if they become sufficiently wealthy), or play as a crewmember on their own or another ship in battle , or as ground defence personnel when their own ship becomes too boring. The players might also design or redesign the flying sailing ships (and later, as technology progresses, flying steam or diesel ships), and test new ship design, or plan ground defences. All of this would be based around a simulated economy, where resources are produced, shipped and either consumed or lost to make value added foods, commodities, communities or vessels. In a war, commerce raiding should eventually have an impact as much as direct military action against enemy troops and vessels. Players could be merchants, pirates, smugglers, privateers, naval captains, or just another member of a ship's crew. Players could also design airships and ground defences, and contribute to the governance of their province. So, for all of this, how can I monetize this game? I need to consider startup capital, but more importantly, it needs to make a profit. However... I don't want to fall into the ways of many games with micro transactions. That means no pay to win a paying player must have only their own skills and equipment to help them win against a free to play player... if I go with that method. The economy is simulated, and I would like the method of monetization to have a minimal impact on that, but not necessarily no impact. Players must know exactly what they are spending their in game currency upon, an must be able to sell for in game or possibly even real currency any 'physical' game object with a cut to the broker (i.e. the developer). I have considered an up front cost, but that alone does not guarantee an income stream as the player base becomes saturated. I have considered instant IAP of objects that would otherwise take time to produce the player buys them from the developer's nation. I have considered allowing a certain amount of free screen time per month, extendable by a purchase. What methods would guarantee continual income for a number of years at least, without unduly upsetting players who may be wary of traps such as loot chests or pay to win? Can a game such as this be funded prior to the commencement of development?


what is the most popular mmorpg game that has an out of game api? World of Warcraft is off the table, because of the "WOW Glider Lawsuit" of 2008. Also see Where is Blizzards official World of Warcraft API? Eve Online has an API But, what is the MOST popular (in terms of usership) MMO Game that does allow programmers to develop out of game things (like an Android app).


How is load balancing achieved in MMOs? I believe it's a common requirement of MMOs that processing for a single shard or realm can be done over several servers to ease the load. I'm curious as to how this can be done whilst maintaining a unified consistent world where all the players, and all the NPCs can interact. My question is how is load balancing achieved in MMOs? Any links, books or general information on how to improve my knowledge on this subject is also appreciated.


Low traffic client synchronization with server in MMO I am implementing MMO where player flies in space on his starship controlling it with arrow keys and cooperate with other players. I want to implement it so that player will be able to dodge his ship from rocket or something else, so I am trying to predict whole game state on client side using the same world simulating algorithm as server use. That game world is written on C and will be called within client directly (it's written on Unity3D) and through CLR on C server (under Linux). Connection through UDP. Problem is how to maintain, for example, 1000 players within single map (exclusing all other game objects, mobs...) Let's say I will synchronize server with clients 50 times per second send to each client states of just that game objects (and players) which he is able to see (within some radius) have to send 100 objects to each player within his view radius must send averagely 50 bytes per game object (it's id, x,y coords, rotation, state...) so, it will need to have such network bandwidth 1000 (clients) 50 (times per second) 100 (objects to send to each player) 50 (bytes per object) 250 000 000 bytes per second! It's impossible! Is it possible to reduce this value somehow? For example let clients to fully simulate their game worlds (for a long period of time) and send them just inputs of other clients and synchronize game worlds, let's say, each several seconds but it will cause weird desynchronization issues at leash because of float computations. Anyway, how such games are programmed in common way? Thank you.


Integer vs String for "type" data in data driven games I've been developing a few mobile games, in which those games fetch their data from a server database. I'm used to storing "type" values as an integer identifier, and an enum in the client to identify the data coming from the server. I'm under the impression that games like MMOs or PC games that get patches model their data to identify "types" as integers. As an example On the database table Monsters Table MonsterId(int), Name(string), MonsterType(int) On the client sided code typedef enum MonsterTypeGround 1, MonsterTypeAquatic 2, MonsterTypeAmphibious 3, MonsterTypeAerial 4 MonsterType Is there an objectively correct answer on what to use (int vs string) for these types of data? Do I have the correct impression that MMO's usually use integers for this, or it highly depends on the developers as well?


How to implement server side auto attack? I'm writing a basic MMORPG and im trying to implement auto attack. At client side I send an AutoAttackMessage to the server. Should I send this message every X ms to the server, or juste one time and then server handle this himself ? How to handle delay between 2 auto attack at server side ? (timer, special thread)...


What is the best way to check for intersection of two bounding boxes, given a minimum and maximum Vector3 for each one I have a BoundingBox object which holds two Vector3's (x, y, z), one for the minimum point and one for the maximum point. ( 1.5 0 9 1.5 3 10) What is the best way to check for any intersection or overlap of two BoundingBoxes? The test for intersection will happen more often than not when there are no points actually intersecting, just faces. The code that I currently am using is bb1.max .x gt bb2.min .x amp amp bb1.min .x lt bb2.max .x amp amp bb1.max .y gt bb2.min .y amp amp bb1.min .y lt bb2.max .y amp amp bb1.max .z gt bb2.min .z amp amp bb1.min .z lt bb2.max .z However this leads to problems when points are, for example 1.5 0 9 1.5 3 10 intersecting with 0.5 0 8.5 0.5 1.8 10.5... The Z minimum and maximum points for the second object laying entirely outside of the Z min and max for the first object.


Am I implimenting a sweep and prune broadphase correctly? The code that I am using is std vector lt PhysicsBody gt physicsChildren containing all objects ... std sort(physicsChildren.begin(), physicsChildren.end(), sortByLeft) std vector lt PhysicsBody gt activeList unsigned int one unsigned int two for(one 0 one lt physicsChildren.size() one) activeList.push back(physicsChildren one ) for(two 0 two lt activeList.size() two) if (physicsChildren one gt m position.x physicsChildren one gt m radius gt activeList two gt m position.x activeList two gt m radius) CheckIntersectionBetween(physicsChildren one , activeList two ) else activeList.pop back() I think something is wrong because for 800 objects 309169 calls to CheckIntersectionBetween. A bruteforce would use 640000 calls, I didn't think this was much improvement (considering only objects close in the x axis should test). I wrote the code from reading Jitter Physics article about SAP Create a new temporary list called activeList . You begin on the left of your axisList, adding the first item to the activeList. Now you have a look at the next item in the axisList and compare it with all items currently in the activeList (at the moment just one) If the new item s left is greater then the current activeList item right, then remove the activeList item from the activeList otherwise report a possible collision between the new axisList item and the current activeList item. Add the new item itself to the activeList and continue with the next item in the axisList. What have I done wrong?


Pygame collision detection less frequent when objects are increased I currently experiencing an issue in pygame where whenever i increase the number of objects e.g. platforms, rocks for a in range(150) rock Rock(0,0) OR incresing the range which they spawn in rock.rect.x random.randrange( 200,30000) rock.rect.y random.randrange(80,500) rock list.add(rock) all sprites list.add(rock) LINE 232 (which i really need to do for an ENDLESS mode) collision detection between the player and all the objects that have have been changed will become less frequent, so the character will just go through th objects as they weren't even there... you can see the character fall through the objects, it falls through in front of the object and not behind. All game code is below, I have tried a number of different techniques and values but I have found that these numbers and ranges work best. Collision Detection code FOR PLATFORM medium collide pygame.sprite.spritecollide(player, medium list, False) if medium collide player.rect.y 2 FOR ROCK rock collide pygame.sprite.spritecollide(player, rock list, True) if rock collide lives 1 if rock collide player.rect.y 100 player.rect.x 50 !!!!!GAME CODE BELOW!!!!! GAME CODE


physics.addBody() with custom shapes in Corona SDK Does the physics.addBody() only work with Circles and Rectangles? Or is it possible to physics.addBody() on vector shapes or sprites or with masks or something?


How do I detect the intersection of a curve with itself? I'm developing a game in which the player can draw a line. I want to detect if that line intersects with itself. How would I do this?


How can I determine the direction of the balls after collision in billiards game? I'm making a billiard game and I have two questions How do I find the velocity of two balls when they collide with each other and how do I apply it to both balls? I already know the angles that they're gonna move, I just need to find the velocity that they'll move in those directions. My game is in 3D, and I'm using Unity. I don't want to use Unity's built in physics to compute the result in this case, I'd like to know how to compute it myself.


Weird issue in collision resolution of non static bodies I'm a bit of a beginner in engine development, so I decided to write my own engine from scratch so I could learn more about what happens under everything. I've been progressing fairly well, except the physics engine side of things have been giving me a bit of a headache. Here's a gif of what I mean Essentially, the engine works just fine as long as the player is not colliding with another non static body from either above, or from right to left. Here's my collision resolution code written in go package resources import ( "game pidgeot socket ecs" "github.com bxcodec saint" ) type PhysicsSystem struct Hub Hub func (system PhysicsSystem) Loop() entities, err system.Hub.World.AllEntitiesWithComponent(ecs.CollisionComponent) if err ! nil return for e, range entities apply impulse c p, system.Hub.World.GetComponent(e, ecs.CollisionComponent) c ( c p).( ecs.Collision) p p, system.Hub.World.GetComponent(e, ecs.PositionComponent) p ( p p).( ecs.Position) if c.WithGravity Add gravity c.ImpulseY saint.Min(c.ImpulseY 1, c.MaxSpeedY) apply impulse p.NextY p.Y c.ImpulseY p.NextX p.X c.ImpulseX resolving collisions for e1, range entities c1 p, system.Hub.World.GetComponent(e1, ecs.CollisionComponent) c1 ( c1 p).( ecs.Collision) if c1.IsStatic continue for e2, range entities if e1 e2 continue system.ResolveCollision(entities, e1, e2) moving entities for e, range entities p p, system.Hub.World.GetComponent(e, ecs.PositionComponent) p ( p p).( ecs.Position) if (p.X ! p.NextX p.Y ! p.NextY) p.X p.NextX p.Y p.NextY system.Hub.broadcast lt system.Hub.World.GetComponentMessage(e, p p) func (system PhysicsSystem) ResolveCollision(entities map ecs.EID ecs.Component, e1 ecs.EID, e2 ecs.EID) c1 p, system.Hub.World.GetComponent(e1, ecs.CollisionComponent) p1 p, system.Hub.World.GetComponent(e1, ecs.PositionComponent) c1 ( c1 p).( ecs.Collision) p1 ( p1 p).( ecs.Position) c2 p, system.Hub.World.GetComponent(e2, ecs.CollisionComponent) p2 p, system.Hub.World.GetComponent(e2, ecs.PositionComponent) c2 ( c2 p).( ecs.Collision) p2 ( p2 p).( ecs.Position) resolve y axis collidingX IsOverlapping(p1.X, p1.X c1.W, p2.X, p2.X c2.W) collidingY IsOverlapping(p1.NextY, p1.NextY c1.H, p2.NextY, p2.NextY c2.H) colliding collidingX amp amp collidingY if colliding direction func (impulse int) int if impulse lt 0 return 1 else return 1 (c1.ImpulseY) overlap CalculateOverlap(p1.NextY, p1.NextY c1.H, p2.NextY, p2.NextY c2.H) p1.NextY (direction overlap) c1.ImpulseY 0 c1.IsJumping false resolve x axis collidingX IsOverlapping(p1.NextX, p1.NextX c1.W, p2.NextX, p2.NextX c2.W) collidingY IsOverlapping(p1.Y, p1.Y c1.H, p2.Y, p2.Y c2.H) colliding collidingX amp amp collidingY if colliding direction func (impulse int) int if impulse lt 0 return 1 else return 1 (c1.ImpulseX) overlap CalculateOverlap(p1.NextX, p1.NextX c1.W, p2.NextX, p2.NextX c2.W) p1.NextX (direction overlap) for e3, range entities if e1 e3 continue c3 p, system.Hub.World.GetComponent(e3, ecs.CollisionComponent) p3 p, system.Hub.World.GetComponent(e3, ecs.PositionComponent) c3 ( c3 p).( ecs.Collision) p3 ( p3 p).( ecs.Position) collidingX IsOverlapping(p1.NextX, p1.NextX c1.W, p3.NextX, p3.NextX c3.W) collidingY IsOverlapping(p1.NextY, p1.NextY c1.H, p3.NextY, p3.NextY c3.H) colliding collidingX amp amp collidingY if colliding system.ResolveCollision(entities, e1, e3) Anything I could do to solve that issue?


Libgdx collision detection and response I am trying to create a simple platformer game with libgdx. I implemented a collision detection for the player's bounding box with the map's tiles using the Rectangle.overlaps method. In response I am trying to find out at what edge the player hits the tile and then react accordingly. Somehow it happens that when the player collides on the X axis, the response of a collision on the Y axes happens (player gets moved to the top of the tile). I was looking into the SAT (Seperating Axis Theorem), but I don't feel like it's applicable here, since I am not trying to draw any line betwen the Rectangles. In fact, since Rectangle.overlaps() is used I am only reacting to a collision already happening. Here the source private void resolveCollision() setUpPlayerRec(allObjects.get(0)) for (Rectangle r2 tiles) if (!playerRec.overlaps(r2)) continue else onCollisionWithTile(r2) private void onCollisionWithTile(Rectangle r2) Gdx.app.log("Collision Detected", "Player collided with tile") float diff if (playerRec.x playerRec.width lt r2.x) LEFT EDGE OF TILE controlledPlayer.getPosition().x (r2.x playerRec.width) controlledPlayer.getVelocity().x 0 else if (playerRec.x gt r2.x r2.width) RIGHT EDGE OF TILE controlledPlayer.getPosition().x (r2.x r2.width) controlledPlayer.getVelocity().x 0 if (playerRec.y lt r2.y) HIT TOP OF TILE diff (playerRec.y playerRec.height) r2.y controlledPlayer.getPosition().y Math.abs(diff) jumptime MAXJUMP controlledPlayer.setJumpState(JUMP STATE.GROUNDED) else if (playerRec.y lt r2.y r2.height) HIT BOTTOM OF TILE controlledPlayer.setJumpState(JUMP STATE.GROUNDED) jumptime 0 diff playerRec.y (r2.y r2.height) controlledPlayer.getPosition().y r2.y r2.height


Different collision effects on different objects I'm a beginner to Corona and game development. I am using a variety of objects in my game. On collision, they all perform the same function. I want them to do different things, and also want some objects to only collide with certain other objects. How would I go about doing this?


Separation of axis theorem implementation at normals This might be more of a math question, but it relates to the development of a simple physics engine I am trying to create. I have been stumped on this for about a week now, and have been unable to find an answer in any of the SAT tutorials. (http www.metanetsoftware.com technique tutorialA.html toc, http gamedevelopment.tutsplus.com tutorials collision detection using the separating axis theorem gamedev 169, etc.) I understand how SAT is supposed to work, however I am little confused on the math. First, I am finding my normals like so Block.prototype.findNormals function () var axisVectors new Array() var vertices this.Properties.Vertices var keys Object.keys(vertices) for( var i 0 i lt keys.length i ) var last x 0, y 0 axisVectors.push( xComponent (vertices keys i .y last.y), yComponent (vertices keys i .x last.x) ) last x this.x, y this.y return axisVectors I am then precede to project each vertex of the shapes I am testing on those normals. The problem occurs, and the part of the math that I am not fully understanding, is when I have a situation like so axis ( 5, 6) vertex (6, 5) math.dot(vertex, axis) This results in 0. Thus my min value for shape1 is always 0. And this results in a false collision. Can anyone explain the math a little better?


Collision detection Swinging bat racket and ball I am programming a side view tennis game, inspired by an old arcade game, using Javscript and HTML5 canvas elements. The player can move left and right and holds a racket at arms length which can be rotated 360 degrees around the shoulder joint. I am quite happy with the collision detection and resulting deflection angle between the racket and the ball in the case where the player stands still and the racket does not move. I use a ray casting approach for this collision detection between the vector that represents the racket and the trajectory vector for the ball as proposed here. However, I am having trouble implementing the collision detection between the rotating racket and the ball. When the racket is swung, the area in which a collision would apply has a shape similar to a circular segment , but the racket rotates rotates to fast and the collision detection does not pick it up in most cases. The image bellow illustrates the problem, the red arrow indicates the direction of the swinging racket. The following code snippet from the player entity's update function shows how the racket is updated. arcmx and armcy is the location of the shoulder joint, rstart and rend are the beginning and end of the racket. if(KEY STATUS.rleft KEY STATUS.rright) if(KEY STATUS.rright) this.rangle this.rspeed else if (KEY STATUS.rleft) this.rangle this.rspeed this.armcx this.x this.width 2 this.armcy this.y 46 this.rstartx this.armcx Math.cos(this.rangle) 40 this.rstarty this.armcy Math.sin(this.rangle) 40 this.rendx this.armcx Math.cos(this.rangle) 71 this.rendy this.armcy Math.sin(this.rangle) 71 I am pretty lost on this problem and appreciate any hints on how to approach it.


RK4 integration and Continuous Collision Detection I'm using this method to detect collision between two AABBs. The algorithm is simple, fast and works great. It uses the relative velocity between the two objects to calculate TOI. This works fine with Euler, but now i'm trying to switch to RK4, which makes it hard for me to determine the TOI since i can't just divide the distance between the two AABBs by their relative velocity. Since RK4 is so popular, how do people deal with this issue? How to calculate a TOI for a swept AABB with RK4?


Delaying certain actions functions in libgdx using Timer? Hello I am trying to delay a part of the processes in my game, but it happend that I use one of my variables in an inner class so I have to make it final, but by making it final I can't assign new value when I find it. All I am asking for is to explain me how to do the delay without making my variable final. Here is my code public class TomatoScript implements IActorScript private CompositeActor tomato private static final int speed 100 private BitmapFont bFont private Batch bch ArrayList lt FruitScript gt fruits private final int dmg 10 private int hp 50 private Rectangle bounds private int state 0 private FruitScript collidetFruit private boolean dead() return hp lt 0 private void setHp(int dmg) hp hp dmg public TomatoScript(Batch b, BitmapFont bf, ArrayList lt FruitScript gt fruits) this.bch b this.bFont bf this.fruits fruits Override public void init(CompositeActor entity) this.tomato entity tomato.setPosition(200, 129) bounds new Rectangle(tomato.getX(), tomato.getY(), tomato.getWidth(), tomato.getHeight()) bch.begin() bFont.draw(bch, Integer.toString(hp), tomato.getX() 20, tomato.getY() 95) bch.end() Override public void act(float delta) switch (state) case 0 tomato.setX(tomato.getX() speed delta) bounds.setX(tomato.getX()) bch.begin() bFont.draw(bch, Integer.toString(hp), tomato.getX() 20, tomato.getY() 95) bch.end() if (tomato.getX() gt 1090) tomato.remove() if (collisionFound()) state break case 1 if (collisionAct(collidetFruit)) state 0 break private boolean collisionFound() for (FruitScript f fruits) if (f.getBounds().overlaps(bounds)) collidetFruit f return true return false private boolean collisionAct(FruitScript f) com.badlogic.gdx.utils.Timer.schedule(new com.badlogic.gdx.utils.Timer.Task() Override public void run() f.setCol(true) here it says I should make the "f" final. f.setHp(dmg) here also. setHp(f.getDmg()) ,2) if (f.dead()) fruits.remove(f) return true if (dead()) if (!f.dead()) f.setCol(false) tomato.getScripts().remove(this) tomato.remove() return false return false Override public void dispose() I've tried to make it final, but it ruins everything it's supposed to stop the actors do the damage taking and then the one alive to continue, but it was doing it too fast in a blink of an eye. When you make the f final, it can't get the new item it should collide with. I hope someone can help )


2D collision rectangles can glitch into each other I have implemented a simple rectangle based collsion detection where you can "slide" around the edges on diagonal movement. Works fine but the thing is, it is somehow possible that e.g. the player (rectangle) glitches into the one of a collision object. It seems, that it appears only when the player "slides" around the corners. I suspect that if the player walks around the corners that the movement direction (Vector2) cuts off the corner and at some point glitches into the collision rectangle. I hope I've explained the problem somehow understandable? The code looks like this The UpdateCall recieves the playerMovement from the keyboard input public void UpdatePlayer(GameTime gameTime, Vector2 playerMovement) ... playerMovement CalculatePlayerMovement(Vector2.Normalize(playerMovement) movementspeed) if (playerMovement.Length() ! 0) MoveBy(playerMovement) ... The CalculatePlayerMovement Method checks world bounds, collision objects and so on. Depending on what side the collsion happens, the x or y movement will be zeroed. private Vector2 CalculatePlayerMovement(Vector2 movement) Rectangle destRect new Rectangle(BoundingBox.X (int)movement.X, BoundingBox.Y (int)movement.Y, Width, Height) Vector2 returnValue movement ... foreach (Rectangle r in TileMap.collisionObjects) if (destRect.Intersects(r)) string collsionSide GetCollisionSide(destRect, r) if (collsionSide "top" collsionSide "bottom") returnValue.Y 0 if (collsionSide "left" collsionSide "right") returnValue.X 0 ... Finally the check itself. I took this part from HERE since I was not sure what the best way would be. private string GetCollisionSide(Rectangle destRect, Rectangle r) float w (destRect.Width r.Width) 2 float h (destRect.Height r.Height) 2 float dx destRect.Center.X r.Center.X float dy destRect.Center.Y r.Center.Y if (Math.Abs(dx) lt w amp amp Math.Abs(dy) lt h) float wy w dy float hx h dx if (wy gt hx) if (wy gt hx) return "top" else return "right" else if (wy lt hx) if (wy gt hx) return "left" else return "bottom" return "" I am not sure where the problem is, but it is probably something I don't see myself.


How to build bullet (hit) damage detection in Augmented Reality to a real life person acting as an opponent? I am building an Android AR game using ARcore 1.18 in Unity 2019.4.5f1 (LTS). Now I want to create something like bullet damage detection just like it is built in a normal Unity 3D game. Of course, the biggest problem is how can I even detect the real person's hitbox like it is done in a normal game? I need to somehow be able to attach the bullet damage script to the body of the real life person in real time. Has anyone tried this before? How can we achieve this? I understand if I might not get a spoonfed tutorial but some help towards what should I be doing to achieve this will be greatly appreciated. I see some other FPS Augmented Reality games which either uses Laser Tag (Father.io) or Barcodes to scan the opponents. These are definitely some great ideas to create an FPS game experience but still, if possible, I want to try it with just the mobile camera without any external support. I am ready to bear some accuracy loss )


Unity OnTriggerEnter2D does not get called when using Raycast In a previous post I talked about creating wires (using B zier curve) using LineRenderer. I am using a PolygonCollider2D to wrap the wire (see below) GameObject wire new GameObject () LineRenderer lineRenderer wire.AddComponent lt LineRenderer gt () PolygonCollider2D wireCollider wire.AddComponent lt PolygonCollider2D gt () After drawing the curve and attaching the collider (as described in previous post), I added a new component to my gameObject (a WireController) WireController wireController wire.AddComponent lt WireController gt () The WireController currently has only one method void OnTriggerEnter2D(Collider2D other) Debug.Log ("I'm hit!") I use a Physics2D.Raycast to check if my mouse pointer is at any point interacting with the wire void CastRay() Ray ray Camera.main.ScreenPointToRay (Input.mousePosition) RaycastHit2D hit Physics2D.Raycast (ray.origin, ray.direction, 100) if (hit) Debug.Log (hit.collider.gameObject.name) If I call CastRay() inside a Update() loop, if (hit) returns true (if the mouse pointer is over the gameObject, in this case, the wire), but the OnTriggerEnter2D method never gets called. A few observations collider.isTrigger true The WireController is attached to the newly created gameObject (it's visible in the Unity editor at runtime) Any help is much appreciated!


What's the fastest collision detection (Game Maker) I want to build a simulator using Game Maker in which there are many (up to hundreds) of obj Cell, each has a radius of 10, (they don't have sprites, they just draw a circle with radius 10). Each step, I want the cells to check around itself for obj A to see if any obj A is "touching" it, (has a distance less than 10 from the cell). However, since I have so many obj Cell and so many obj A, the most straight forward code (below) will have to be executed tens of thousands of times (number of obj A number of obj Cell) In obj Cell (with obj A) if distance to object(other) lt 10 do stuff Is there any possible way to make this faster?


Python collision problem I have a hero character with jumping physics that I am trying to figure out the collision detection for. Right now, the problem that I am running into is as soon as the character hits the floor (while I'm pressing left on the left side of the screen) the rect that it recognizes that it is colliding with is the ground. Which is to be expected. However, based on the checks that I have, for sprite in self.group.sprites() wall collide sprite.feet.collidelist(self.walls) if wall collide gt 1 print wall collide if self.col ground(sprite, wall collide) self.hero.jumping False sprite.move back y(dt) if self.col left(sprite, wall collide) sprite.move back x(dt) if self.col right(sprite, wall collide) sprite.move back x(dt) print quot quot since the character is colliding with the ground, the check to see if the character's rect is inside the colliding rect fails for 2 reasons 1 The current collision rect is the ground which the character is above, so the test fails 2 Because of 1, the character will keep moving left until it realizes it's colliding with the left side, at which point it will have already gone too far into the wall. What's the best collision solution? Note the character starts to the right of the left wall, on the ground but isn't colliding with the ground since the start position is right above it. Also, I realize that my code is a bit jumbled and I'm not taking care of every sprite in the group. I'll fix that once I have this fixed. I can provide more code pictures if necessary Edit More code def col ground(self, sprite, wall) if self.walls wall .collidepoint(sprite.feet.midbottom) return True return False def col left(self, sprite, wall) if self.walls wall .collidepoint(sprite.feet.midleft) return True return False def col right(self, sprite, wall) if self.walls wall .collidepoint(sprite.feet.midright) return True return False


When is a quadtree preferable over spatial hashing? I'm making a 2d platformer with lots of objects at the same time. They're all AABB collision detected. I first tried a quadtree to decrease the number of of objects to check, tried a few different configurations, but it didn't prove as effective as I needed. I implemented a spatial hash and it's way more efficient, the number of objects to check for each collision went down drastically. Is there a case when doing 2d collision detection using a quadtree is preferable over spatial hashing? According to my tests, it seems spatial hashing always ends up with less objects to be tested for collision? I haven't done timing over the algorithms, but is hashing simply very expensive or difficult to implement when you're, for example, coding in C? Worth noting is that I'm writing the game in javascript, where you have hashing "for free". Here's the comparison, did I overlook something? http zufallsgenerator.github.io 2014 01 26 visually comparing algorithms


Is an extra collision mesh for level data worth the hassle? What is the optimal approach for collision detection with the environment in an 3D engine (with triangle mesh based geometry, no bsp)? A) Use the render mesh no need for additional work for artists to fiddle with collision detection high detail is harder for physics calculation maybe use collidable flags for materials compute the collision mesh from the render mesh B) Use an additional collision mesh faster more optimal collision detection additional work (either by the artist or by the programmer who has to develop an algorithm to compute it from the render mesh) more memory useage How do AAA title handle this? And what are the indie dev's approaches?


Exact collision time of two axis aligned bounding boxes I am trying to calculate the exact collision time of two axis aligned bounding boxes (aabb) as fast as possible (in the sense of CPU time). I have all the required information (aabb min, max, center, etc., velocity vector, and so on) My aabbs are not rotating, so they have linear velocity The aabbs can be both moving, only one of them might be moving, or they both might be steady My current approach creates lines from one of the boxes' corners and checks the collision among the planes of the other box (you can see the algorithm below) however it takes 6 times longer than I can afford. So, I am trying to find a faster algorithm however, I couldn't have managed, yet. My current quot slow quot algorithm Add velocity of Aaabb to Baabb and assume Aaabb is steady and Baabb is moving Calculate the corner positions of Baabb For each corner of Baabb, perform the line plane intersection with Aaabb's each 6 planes (I use the line intersection formulate (algebraic form) on Wikipedia) to check if there is an intersection. If a corner of Baabb intersects with a plane of Aaabb, verify the intersection point is behind the other 5 planes of Aaabb Keep the smallest value of d and return


Godot raycast colliding too high I am making an fps that uses a raycast for shooting. I used some suggestions taken from a few reddit pages, but it's mostly my own code. It was working properly, until I noticed that when you shot up above the enemy, it still registered as a hit. Does anyone know why this might be happening? code func use weapon() Raycast.force raycast update() if Raycast.is colliding() var collider Raycast.get collider() if collider if collider.has method( quot takedamage quot ) collider.takedamage(10)


How do I compute the angle between a pixel on an irregular curve and a circle colliding with it? I'm building a custom physics engine to accompany a level editor. This image shows how the level editor outputs levels Now, some explanation is in order. The curve is defined by the red points. After they are connected in threes by circles (yellow lines show these circles), a system connects them in a 'streamlined' way as shown by the blue lines. This makes the curves flow seamlessly. Now, these curves are 'irregular,' so to say. For the accompanying physics engine how do I detect the angle made between a pixel on the curve and a colliding circle (per pixel collision check)?


Tiles and a walkable path My game a sidescrolling platformer. I've created my own Tile app which in the end export an xml file detailing what each 32x32 space (in the entire image) contains (environment, platform, etc.). I get how to use it for static things collision detection and quad trees and so forth but still have no clue how to use this map xml file for keeping my character on a path in my background image which in my case is a hill with lots of odd curves. Also, yes, there are tutorials on tile movement, but they are mostly movement from a top down view which is slightly more trivial to implement. 80 of the image in my game is just a pure background and the very bottom are bricks covered with grass with some weirder angles. The thing is, I can have mixed tiles of empty space and grass which contains a part of a curve so I don't know how I would want the player leg to interact with this. Can anyone give me an idea or an example?


IntersectMovingAABBAABB weird behavior I'm using the IntersectMovingAABBAABB implementation from the book Realtime Collision Detection and I'm having a little bit of an issue. When I have two AABBs next to each other (not touching), A being stationnary and B moving up or down, I'm getting a result saying there's a collision. Obviously this is wrong. A B B moving up down I've rechecked my code multiple times to make sure I had the same thing as in the book. Stepping through the code, I realized that the check for v i lt 0 and v i gt 0 will never be true for either X or Z axis when moving straight up or down. Therefor, no checks for intersections on these axis will be done. I find that quite weird, and I was wondering if I was missing something, or if this code is simply bad. Here's my implementation for reference public static bool IntersectMovingAABBAABB(AABB a, AABB b, Vector3 va, Vector3 vb, out float first, out float last, out BlockFace face) face BlockFace.None if (TestAABB(a, b)) first last 0 return true Vector3 v vb va float current first 0 last 1 for (int i 0 i lt 3 i ) if (v i lt 0) if (b.Max i lt a.Min i ) return false if (a.Max i lt b.Min i ) if ((first Math.Max(current (a.Max i b.Min i ) v i , first)) current) face (BlockFace)(1 lt lt (i)) if (b.Max i gt a.Min i ) last Math.Min((a.Min i b.Max i ) v i , last) if (v i gt 0) if (a.Max i lt b.Min i ) return false if (b.Max i lt a.Min i ) if ((first Math.Max(current (a.Min i b.Max i ) v i , first)) current) face (BlockFace)(1 lt lt (i 3)) if (a.Max i gt b.Min i ) last Math.Min((a.Max i b.Min i ) v i , last) if (first gt last) return false return true


Understanding unknown mesh data structure I have a large number of old mesh files in a custom, undocumented binary format. I have managed to parse almost everything but am left with one group of structures, described below, that I don't understand. I hope an experienced graphics programmer can explain what is happening. Here are the structures concerned These types are defined below. We're trying to understand what these three arrays are used to achieve. VertexRef vertexRefs Triangle triangles Unknown unknowns struct VertexRef Earlier in the file, there are several vertex buffers. The file can contain multiple meshes, either as components of a larger mesh, or as multiple LODs. This value group picks out one of these buffers. uint8 t group Index into the vertex buffer picked out by group . uint16 t vertexIndex struct TriangleVertex Index into the array vertexRefs uint16 t vertexRef Index into the array unknowns uint16 t unknownIndex struct Triangle TriangleVertex verts 3 struct Unknown Index into the array vertexRefs uint16 t vertexRef1 Index into the array triangles uint16 t triangleIndex1 Another index into the array vertexRefs uint16 t vertexRef2 triangleIndex2 can be 0xffff, while triangleIndex1 never is uint16 t triangleIndex2 The array of VertexRef is straightforward. It picks vertices, potentially from multiple meshes, to form a composite mesh. The array of Triangle is formed by vertices from the array of VertexRef. Each vertex is also associated with an Unknown. I am out of my depth in understanding what Unknown is doing. Member triangleIndex2 sometimes being 0xffff (or invalid, or nonexistent?) might indicate it is a leaf node of a tree? Perhaps the structure comprising the arrays vertexRefs, triangles and unknowns is some kind of collision detection tree? I'd be very grateful for any hints. Please ask questions if I've failed to be clear enough about something. Edit In answer to a request in comments, I am attaching a sample file and code to load it. The code should run on any likely system. The file is a mesh of a pair of boots. The file is hosted at uploadfiles.io https ufile.io w66mh


How to do collision detection on marching cubes terrain? I'm writing the physics part of my game engine. The world uses the marching cubes algorithm on a 3d perlin noise to make the terrain. How do I do collision detection on the resulting mesh? I can't use SAT since the terrain is not convex and subdividing it into smaller convex parts seems to be nearly impossible. What is the best collision detection algorithm for such a mesh? The objects that are supposed to collide with the terrain can be any convex polyhedron. EDIT The terrain is not "cubed" (like minecracft). The terrain is smooth with slopes. This is pretty close to what my terrain looks like (this is NOT my video) https www.youtube.com watch?v 4rA3fdKWQA I am looking for a general collision detection here. I need the point(s) of contact and the normals so that I can put these into my collision resolver. Example of usage is throwing a box onto the terrain and it should roll and bounce approximately like it would in the real world.


Meaning of offset in pygame Mask.overlap methods I have a situation in which two rectangles collide, and I have to detect how much did they collide so I can redraw the objects in a way that they are only touching each other's edges. It's a situation in which a moving ball should hit a completely unmovable wall and instantly stop moving. Since the ball sometimes moves multiple pixels per screen refresh, it is possible that it enters the wall with more than half its surface when the collision is detected, in which case I want to shift its position back to the point where it only touches the edges of the wall. Here is the conceptual image it I decided to implement this with masks, and thought that I could supply the masks of both objects (wall and ball) and get the surface (as a square) of their intersection. However, there is also the offset parameter which I don't understand. Here are the docs for the method Mask.overlap Returns the point of intersection if the masks overlap with the given offset or None if it does not overlap. Mask.overlap(othermask, offset) gt x,y The overlap tests uses the following offsets (which may be negative) .. A yoffset .. B xoffset


Allowing one sprite to move through another in Quintus I have a Bumper class extended from Sprite Q.Sprite.extend("Bumper", init function(p) this. super(p, gravity 0 ) this.add("2d, ... etc. I have an Enemy class that should trigger a function when the center of the Bumper and of the Enemy collide. I was thinking about doing something like this in my Enemy class this.on("bump.top, bump.bottom, bump.left, bump.right", function(collision) if(collision.obj.isA("Bumper")) if (this.p.x collision.obj.p.x amp amp this.p.y collision.obj.p.y) Do something ) But for that I need the two sprites to move through one another. Is there a way to do that while still checking for collision ?


Calculating contact points with SAT After detecting a collision between two convex shapes by using separating axis theorem and calculating MTV. How can I calculate the contact points?(for applying torque to the rigid body).


Area attack collision resolving I'm planning to write little 2D go right and swing your sword game. When i started to write my ideas on paper i've come across a little problem. Let's say i'm using magic spell, ex. fireball which technically is a signle projectile flying slowly in a specified direction. As it's defined to be a piercing projectile, I want it to hit every enemy only once, no matter how big their sprites are. And how I do it? I know i can use the array of already hit enemies and check every frame if projectile collides something new, but is it a correct way? Are there any tried and true ways of resolving problems like this?


Can Bullet Physics (or another 3d physics engine) use callbacks in my engine to check static geometry? I'm wondering if it's possible to use or hack Bullet 3d Physics (or another free 3D physics engine) so that I don't need to "import" my static geometry into Bullet instead I want to do it the other way, so Bullet uses some sort of callback system to check geometry properties of my mesh polygons. Sort of like that Bullet would expect a method in my static geometry classes "checkRayIntersection" or similar, and I take care of the details and optimizations myself. The meshes are immovable, so the only thing that I expect Bullet to care about is intersections and their normals, but I might be missing something.. EDIT as an example, consider a 10 million polygon terrain mesh which is changing all the time. You probably don't want to keep parallel data structures in the render engine and in the physics engine for this. You don't want to use an approximation for the physics either. Bullet uses something called MotionStates to solve this problem for its output I was hoping there was a similar design pattern for passing geometry input.


Rotated Sprites collision detection I am trying to implement checkCollision function in my game, I used AABB method but the problem is that my sprites are rotated so it's not really precise. I could finely describe my Sprites with rotated ellipses. Is there any more precise way of detecting the collision if I have the following attributes of entities entity.x entity.y entity.width entity.height entity.angle Here is what I have coded so far (x and y are in the middle of my sprite) this.checkCollision function(entity1, entity2) return (entity1.x (entity1.width this.COLLISION EPSILON WIDTH) 2 lt entity2.x (entity2.width this.COLLISION EPSILON WIDTH) 2 amp amp entity1.x (entity1.width this.COLLISION EPSILON WIDTH) 2 gt entity2.x (entity2.width this.COLLISION EPSILON WIDTH) 2 amp amp entity1.y (entity1.height this.COLLISION EPSILON HEIGHT) 2 lt entity2.y (entity2.height this.COLLISION EPSILON HEIGHT) 2 amp amp (entity1.height this.COLLISION EPSILON HEIGHT) 2 entity1.y gt entity2.y (entity2.height this.COLLISION EPSILON HEIGHT) 2) PS my cousin told me to do it with three circles (which creates a shape very similar to the ellipse) but I do not really know how to do it.


Custom Tile Collision Detection Has Trouble With Edges So, I'm writing my own game to expand on my abilities as a programmer. However, I have come to a writer's block of sorts. The game I am building uses tile collision, but allows the player to be in an unaligned space (like at the edge of a tile rather than directly above it). The code I have written to determine which tile the player is standing on is failing. On certain edges, when standing on top of the tile, the player will fall through the tile. Here is an example of this occurrence http i.imgur.com CACfhIP.gifv I have narrowed this down to this specific segment of code (Please note that SPRITE WIDTH is 20, which also means 20 pixels) BOOL changePos(Player player, Level level, int newX, int newY) int roundedY int roundedX if (newX lt player gt pos.x) roundedX roundDownTo(newX, SPRITE WIDTH) round down to a multiple of SPRITE WIDTH else if (newX gt player gt pos.x) roundedX roundUpTo(newX, SPRITE WIDTH) ditto but up The problem seems to be that both parts of the if...else if... statement require the equality symbol to work correctly. Meaning that in the provided example, the fall through glitch will happen to the tile on the left instead if I move the equality symbol to the else if portion. I attempted to fix this issue by adding an else clause and removing the equality from the if...else if... parts. My method was to determine which half of the tile the player was on and determine if it required them to fall. So, my code became this BOOL changePos(Player player, Level level, int newX, int newY) int roundedY int roundedX if (newX lt player gt pos.x) roundedX roundDownTo(newX, SPRITE WIDTH) else if (newX gt player gt pos.x) roundedX roundUpTo(newX, SPRITE WIDTH) else if (newX SPRITE WIDTH gt SPRITE WIDTH 2) roundedX roundDownTo(newX, SPRITE WIDTH) else roundedX roundUpTo(newX, SPRITE WIDTH) But this created an even stranger case where the middle part of the tile would cause a fall through but the edges would work correctly on both the left and the right tile. This can be seen here http i.imgur.com lTaUuzh.gifv I've been at this all day (literally), I appreciate any help you can provide. If I have not provided enough information, please let me know and I will do my best to provide it.


How do I determine wall direction, with information of normal and incoming direction? What is formula and theorys used to determine wall direction, with only knowing the normal of the wall and the direction of the incoming object? This answer has already stated a formula, but I don't know where it came from, and I am in need of understanding.


3D line segment AABB collision, with hit normal? I'm embarrassed I can't find this, but I'm wanting to detect intersection with a 3D line segment (not an infinite ray) with a 3D AABB, the AABB being defined as two Vec3f's which represent the Min and Max extents. So the AABB can be arbitrarily sized. I also need the surface normal of the AABB, if there was a hit. From looking at similar algorithms I at least know it seems good to calculate the inverse direction of the line beforehand, at least, if you're needing to check against multiple AABBs per frame. I have struct AABB VEC3F min VEC3F max a and b representing start end points of the line segment returns true if intersects, also fills out "normal" if true bool LineIntersectsAABB(const VEC3F amp a, const VEC3F amp b, const VEC3F amp inv dir, const AABB amp aabb, VEC3F normal) The implementations I've found either do not find the hit normal, and or they're intended for boxes cubes where the three dimensions of the box are always equal length, which doesn't work for me. Implementations seem to vary greatly, which is confusing for me (since I'm still trying to learn it), and, considering that I need the hit normal, I'd imagine that that may rule out certain implementations.


How to implement 2d collision detection that is immune to low framerate and fast movement? I am trying to implement my own collision detection for a 2.5d voxel style platformer using Three.js. I have a problem with my implementation if the framerate is too low or the character is moving too fast (usually when falling from high places) it falls right through. Is there a way to improve collision detection to be immune to problems like this? This is how I detect collisions function render() requestAnimationFrame(render) setVelocity() animate() manageCollisions() renderer.render(scene, camera) function manageCollisions() Check every game object for collision gt TODO implement broad phase when dealing with many objects for(i 0 i lt world.length i ) Check for bottom collision lt ALWAYS check (unless moving up) if(velocityY lt 0) if( (character.position.y character.height 2) lt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2)) console.log("bottom collision " i) velocityY 0 jumped false grounded true character.position.y world i .position.y world i .height 2 character.height 2 0.1 0.1 prevents shaking else grounded false Check for right collision lt ONLY if moving right (velocityX is positive) if(velocityX gt 0) if( (character.position.y) lt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2)) console.log("right collision" i) velocityX 0 character.position.x world i .position.x world i .width 2 character.width 2 check for left collision lt ONLY if moving left (velocityX is negative) if(velocityX lt 0) if( (character.position.y) lt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2)) console.log("left collision" i) velocityX 0 character.position.x world i .position.x world i .width 2 character.width 2 check for top collision lt ONLY if moving up (velocityY is positive) if(velocityY gt 0) if( (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) lt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2)) console.log("top collision" i) velocityY 0 character.position.y world i .position.y world i .height 2 character.height 2


Collision detection recommendations I am currently developing a prototype game for mobile devices in which the user will see several objects on the screen and will have to touch them one by one in the correct order to win. I guess it that you can say that it is similiar to a Whack a Mole game, but instead of having moles popping up on the screen, I will have several objects moving around. I am having some difficulties in implementing a collision detection algorithm for this game, thefore I would like your recommendation on what is the best method to use. For example suppose an object is moving in a given direction, then I could use the SAT to check if it collides with other objects. If it does collides, then it will stop and move in another direction which is randomly chosen. Another option would be to divide my screen into square or hexagonal tiles. This way I could just check if the tiles are free or occupied before moving the objects. My game be 2D and will use a top down ortographic projection and I am developing it using Cocos2d X and Marmalade SDK. I am not using any physics engine, because my game does not require them (the objects just have to move around, they don't bounce or need any sort of physics behavior).


Tile based collision detection errors if player is smaller than tiles I have implemented a tilemap where each tile is at a non negative x and y position. (So at the moment think like chess) At the moment a tile is 16, 16 pixels in size Tile 0,0 is at the left bottom corner Some tiles should be collidable. I've never implemented something like that and during research stumbled upon https jonathanwhiting.com tutorial collision The general idea collision response handling let mut new pos Point2 new(curr pos.x x offset, curr pos.y) let collision on x collide with world( amp new pos, amp world) if !collision on x transform.translate x(x offset) new pos.y curr pos.y y offset let collision on y collide with world( amp new pos, amp world) if !collision on y transform.translate y(y offset) The collision detection fn collide with world(new pos amp Point2 lt f32 gt , world amp World) gt bool TODO make these sizes i16 instead so we can grow in any direction! let mut left tile u16 (new pos.x TILE SIZE IN PIXELS as f32) as u16 1 so that we do not collide until we are exactly at the thing let mut right tile u16 ((new pos.x PLAYER WIDTH 1.0) TILE SIZE IN PIXELS as f32) as u16 let mut top tile u16 ((new pos.y PLAYER HEIGHT 1.0) TILE SIZE IN PIXELS as f32) as u16 let mut bottom tile u16 (new pos.y TILE SIZE IN PIXELS as f32) as u16 println!("new pos ? , left , right , top , bottom ", (new pos.x, new pos.y), left tile, right tile, top tile, bottom tile) Useless as long as we use unsigned coordinates if left tile lt 0 left tile 0 if right tile gt WORLD WIDTH IN TILES right tile WORLD WIDTH IN TILES Useless as long as we use unsigned coordinates if bottom tile lt 0 bottom tile 0 if top tile gt WORLD HEIGHT IN TILES top tile WORLD HEIGHT IN TILES let mut any collision false for i in left tile.. right tile for j in bottom tile.. top tile let tile world.get tile(i, j) println!("tile at ? is ? ", (i, j), tile) match tile Some(tile) gt if tile WALL println!("hit a wall at ? !", (i, j)) any collision true None gt (), return any collision I basically took (or tried to take) the optimised version of the linked blog entry. Now to the problems If PLAYER WIDTH and PLAYER HEIGHT are both 16.0 collision works fine But note that I had to put 1.0 in the calculation of the right tile and top tile, else the collision for UP and RIGHT would occur one pixel to early (so the player would never touch walls to their top or right) This change alone makes me a bit suspicious looks like I made an error there. The real problems start if the player is smaller than a tile In the following screenshots the following rules apply ) the PLAYER WIDTH and PLAYER HEIGHT are both 8 ) Greenish tiles are the only walls! ) All the screenshots were taken in ONE run no parameters were changed during this run! 1) Trying to collide with right tile overlapping 2) Trying to collide with top tile cannot go any nearer than 4 pixels (half the height of the player) 3) Trying to collide with left tile cannot go any nearer than 4 pixels (half the width of the player) 4) Trying to collide with top tile suddenly overlapping although different tile didn't collide? 5) Trying to collide with bottom tile cannot go any nearer than 4 pixels I cannot grasp 2 and 4 at the moment.


How to calculate max region area of 2d circles? I have some 2d circles on a plane, each has its own minRadius and maxRadius. When two circles collides, both of them will shrink their radius, so the actual radius of a circle is in range minRadius, maxRadius . I need to calculate the max possible radius of each circle. See below image for an example. Currently, I use the following algorithm to calculate the radius of each circle. I try to increase each circle's radius a little each steps, then check and solve if there is any collisions. foreach c in circles c.radius c.minRadius for (int i 0 i lt 10000 i) foreach c in circles c.radius c.radius 1 foreach c in circles calculate radius(c) function calculate radius(c) collides find all circles which radius is overlap with c() foreach x in collides x.radius somevalue c.radius somevalue end For now, the result looks fine, but the algorithm costs too much time. So I wonder if there exists other ways to solve it? wondra counterexample(maybe) The image below illustrates the problem. From my understanding of your algorithm, the final radius of circle A is 1.6, the calculation sequence is (BC, AB, AD) But if using my algorithm(increase radius by a small amount each step), the final radius of circle A is 1.5. I don't think recalculate the dist matrix after each selection will solve the problem, as stated in my question, each circle may have its own minRadius and max Radius.


How do I detect collision between movie clips? I know there are some methods you can use, like hittestPoint and so on, but I want to see where my movie clip collides with another another movie clip. Are there any other methods I can use? I have had trouble finding a good introduction to game physics, and I would like to know how to something like this, properly.


What are the advantages and disadvantages of overlap testing and intersection testing? I have been looking for the advantages and disadvantages of both overlap testing and intersection testing, but I was only able to find a few disadvantages overlap testing may fail for objects moving very fast, and intersection testing makes assumptions that may lead to wrong predictions, such as a constant speed and zero accelerations. What are the advantages and disadvantages of overlap testing and intersection testing?


Collision Managers and bitmaps I am rewriting a game I made to use a (custom) collision manager that uses the minimum displacement method. As of now, my simple manager can only recognize and act on a couple of shapes Circles and AABB's. Those were pretty simple to implement, but I've run into a problem My game also needs to be able to have bitmaps that the player (represented by an AABB) can interact with, such as the one below I have a couple of questions 1) Does it make sense to have a shape BitmapShape, which does collision detection at the pixel level and searches outward in the bitmap for a place to move intersecting objects to? In the image above, it would make sense to check the players bottom center coordinates against the bitmap of the hill, but you can imagine that this would provide odd results for an intersection from the top of the player. 2) How could any system like this allow for a rectangle to move up a hill? Wouldn't an minimum displacement based method always move the rectangle backwards down a hill? Thanks


How to move towards a point in 2D, stopping at obstacles I want to do a 2D game, where you can mouse click anywhere on the map and the player will go there. If there is obstacle in the way, the player will go as close as possible to where you clicked without going into the non walkable area. What would be the optimal way to accomplish this?


Typical collision detection I would like to know how is the typical collision detection of most games. For example, you control a character which can move in 2 dimensional directions (except up and down). Now lets asume he walks into a wall, most of the games depending on character angle and the BB normal face will only stop the player in one axis, but will continue moving in the other along the wall axis. How is that done? I've only managed to stop the character from going through the wall by seting the position to the last one in the past frame if the new position colllisions the bounding box. But this just makes the player stop sharply and unrealisticly.


When there are multiple objects of the same type, how do I know which one I am colliding with? I'm working on a platformer game using Gamemaker Studio 2. , and currently I'm dealing with implementing platforms (Platforms are able to pass through from the bottom, but remains solid when landing on) It's all working good and well for a single platform, but when I add multiple, then only the lowest placed platforms will work properly. I'm already aware that the problem lies on the second if statement in the code below. if (place meeting(x, y mySpeed 1 , o platform) amp amp If the player collides with a platform mySpeed 1 gt 0 ) if the player is falling if ((y 29) lt o platform.y) if the player's feets are located higher than a platform while !place meeting(x, y sign(mySpeed 1 ), o platform) y sign(mySpeed 1 ) mySpeed 1 0 The problem is likely because it's reading information from any platform. but not the higher platform I'm colliding with. So I should need a check to make sure I'm talking about the same object I'm colliding with. If it was a build in collision event, I could use the other statement to get the right instance, but currently I'm using place meeting in a step method to collide, and other would be too broad to use properly. So how would I be able to archieve this?


Finding roots zeros for collision detection? For the most simple of 2D games, I have implemented a posteriori collision detection (overlapping rectangles) on the x y Cartesian plane, but am now interested in understanding the basics of a priori collision detection... In the link here, I noticed the reference to Newton s Method. So, I want to better understand the link b w finding zeros of an equation and detecting a posteriori collision. Let's start with the most obvious case of finding roots of an equation If you have a projectile's trajectory modeled as a quadratic function, you can find the roots to predict at what time the height will equal zero (or any other constant height, actually, by just solving f(x) C to be f(x) C 0 and then finding roots of that expression). So, as I understand, finding the root can tell me the time at which the object will be at any chosen height. More broadly, we basically know the (x,y) location of the object for any given time. But how does root finding, in particular, translate to detecting collisions with another object? (The other object may be stationary, or be moving. If the latter, do you also determine roots location of this moving object as well? Calculate the (x,y) trajectory of both objects and determine where they will intersect?) Again, the basic question is where does root finding come into play? Any links to a basic primer on this topic, with a simple example would also be greatly appreciated.


Polling events with SDL results in stuttering response when dealing with multiple objects I'm new to SDL programming and I'm not quite sure I got how it handles events. Given an instance like this defined in quot game.c quot static struct SDL Window window SDL Renderer renderer BinaryTree objects game NULL, NULL, NULL (Which of course gets properly initialized) My game loop is defined in the same file as follows void game run() bool closeRequested false while(closeRequested false) SDL RenderClear(game.renderer) binaryTree startIteration(game.objects) while(binaryTree hasNext(game.objects)) GameObject gameObject (GameObject ) binaryTree getNext(game.objects) SDL Event event while(SDL PollEvent( amp event)) if(event.type SDL QUIT) closeRequested true else if(event.type SDL KEYDOWN) gameObject onKeyPressed(gameObject) if(event.key.keysym.scancode SDL SCANCODE UP) gameObject onUpKeyPressed(gameObject) if(event.key.keysym.scancode SDL SCANCODE DOWN) gameObject onDownKeyPressed(gameObject) if(event.key.keysym.scancode SDL SCANCODE LEFT) gameObject onLeftKeyPressed(gameObject) if(event.key.keysym.scancode SDL SCANCODE RIGHT) gameObject onRightKeyPressed(gameObject) if(event.type SDL KEYUP) gameObject onRendering(gameObject) SDL RenderCopy(renderer, gameObject getTexture(gameObject), NULL, gameObject getDestination(gameObject)) SDL RenderPresent(game.renderer) game.objects contains every object which has to be rendered (via game.renderer) onto the the window (game.window). So, on each frame game.objects gets iterated on and for each element various functions get executed, before its texture is loaded to the renderer. Of course gameObject onRightKeyPressed() is called only if the right key was pressed, so if this function is defined as void gameObject onRightKeyPressed(GameObject gameObject) gameObject gt destination.x 1, On each frame that the right key is pressed, gameObject's texture will move by 1 pixel to the right. This works perfectly if game.objects contains only one element, but if a second element gets added, only the first one will smoothly respond to my input, while the other will move by 1 or 2 pixels just once in a while by keeping the right key pressed. It's like the first element contained in game.objects quot steals quot the input, so that when the second element's turn comes, there's no input for it to respond to. What did I do wrong?


Best way to distribute graphics, audio and levels with an SDL game? I'm working on finishing up a game written in C with SDL I've been working on for awhile, and I'm starting to ponder how I'm going to distribute it. It has hundreds of images that are loaded and used throughout the game, as well as a couple dozen .wav files for audio effects. What is the best way to distribute these? Should I just include the folders with all the files? Or is there a way I can package them into a single file, then open and extract them in my application? What's the best way to go about this?


SDL Multiple keyboard support I am making a game with multiplayer split screen mode using SDL. Basically, I like the idea of having each player plug in his own keyboard to the PC, set custom controls via options and being able to play it with controls that he likes. However, there's a problem. This code gets the keyboard event SDL Event event SDL PollEvent( amp event) SDL Event has member SDL KeyboardEvent key, which has member Uint8 which. In short event.key.which According to this, it should represent keyboard device index, however, I've tried connecting three keyboards to my PC and press the buttons at the same time and the result wasn't satisfying they all had same keyboard indexes. Is there a solution to this? Or am I missing something?


Should I cull off screen objects in SDL2 My game will have a large number of objects moving offscreen at any given time, can i just render them all with SDL RenderCopy even though they are off screen or should I only render them if they are on screen? I will probably have many hundreds or throusands of objects loaded at a time. My dev machine is quite overpowered for what I'm trying to do but I am conserned that I just won't notice a preformance drop that may affect players with less powerful computers. So, will checking if each object is on screen before drawing increase performance lower CPU load, or can I safely let SDL handle this with clipping?


Scaling an SDL Surface I want to create a button for a game's UI. The background uses a gradient and then I blit a surface on top of the gradient and use SDL SetColorKey to delete the unwanted pixels. The surfaces are not the same size the clipping mask is 200 x 50 and the gradient 1 x 50, so I need to stretch the gradient to the same width of the cliping mask, I can't use a wider image because the purpose of doing this is to save memory and storage and using the same gradient image on multiple clipping masks of different widths. I found I can use SDL BlitScaled but I need to blit the surface to itself and it appears to be useless because the surface remains the same size, am I doing something wrong? Is there a way to do it without blitting the surface to itself? SDL Rect final size final size.w 200 final size.h 50 final size.x 0 final size.y 0 SDL BlitScaled(gradient surface, NULL, gradient surface, amp final size) do some stuff with those textures SDL CreateTextureFromSurface(renderer, final button surface)


SDL2 jagged staircase edges I am using SDL2 and SDL2 Image to render png images. When I rotate the textures, they turn out very ugly, like this This is the code responsible for the rotation and alpha mod. SDL Rect srcRect SDL Rect destRect srcRect.x width currentFrame srcRect.y height currentRow srcRect.w destRect.w width srcRect.h destRect.h height destRect.x x destRect.y y SDL SetTextureAlphaMod(m textureMap id , alpha) SDL RenderCopyEx(pRenderer, m textureMap id , amp srcRect, amp destRect, 10.0, 0, flip) Do I need to set a blendmode too?


Is there a way how to handle multiple SDL PollEvent loops without clearing the event queue? Is there a way how can I handle more SDL PollEvent while loops for one SDL Event, without taking the events off from the event queue? Let us say I have something like this void Game processInput() SDL Event event SDL PollEvent( amp e) Engine InputManager processInput( amp e) GUI Library InputManager processInput( amp e) And then the engine processes the input in function like this void Engine InputManager processInput(SDL Event e) mainEvent e while (SDL PollEvent( amp mainEvent)) switch ( mainEvent.type) case SDL KEYDOWN Engine InputManager pressKey( mainEvent.key.keysym.sym) break case SDL KEYUP Engine InputManager releaseKey( mainEvent.key.keysym.sym) break However, this while loop clears the whole event queue, and another input manager (my GUI, for example) does nothing because it no longer has events in the queue. Is there a possible way to handle this situation?


Errors in Xcode using SDL I am using Lazy Foo's Production tutorials for making an SDL game in C in Xcode 6.1 http lazyfoo.net tutorials SDL index.php Hello 20SDL. I'm using Xcode 7 but I don't think they are very different. In the second tutorial (http lazyfoo.net tutorials SDL 02 getting an image on the screen index.php). I cannot seem to compile properly without an error regarding one of the functions. The function prototype Frees media and shuts down SDL void close() Then the function declaration void close() Deallocate surface SDL FreeSurface( gHelloWorld ) gHelloWorld NULL Destroy window SDL DestroyWindow( gWindow ) gWindow NULL Quit SDL subsystems SDL Quit() And then the function call at the end close() I am getting these errors and am not quite sure how to fix them. Other solutions online are for problems that are not quite the same as mine. SDL Tutorial SDL Tutorial using image.c 28 6 Conflicting types for 'close' SDL Tutorial SDL Tutorial using image.c 28 6 Conflicting types for 'close' SDL Tutorial SDL Tutorial using image.c 127 5 Implicit declaration of function 'close' is invalid in C99 SDL Tutorial SDL Tutorial using image.c 127 11 Too few arguments to function call, expected 1, have 0 clang error linker command failed with exit code 1 (use v to see invocation) Any help would be much appreciated, as I am struggling to make progress with learning SDL game programming at the moment. Thank you.


SDL 1.2 reports wrong screen size I have a multi monitor setup with two displays, both 1920x1200. In games, I can only select resolutions 1920x1200 (like 2560x1200) which makes games unusable. Full screen doesn't work either because it switches one display to 800x600 which means I can't reach the close button... I have to kill the game and then, I have to restore my desktop because all windows are moved resized. How can I force SDL to use any resolution that I want?


SDL PollEvent very slow on SDL2, but works fine on SDL1.2 I have this simple app that displays a screen and handles the quit event while( SDL PollEvent( amp e ) ! 0 ) User requests quit if( e.type SDL QUIT ) quit true If I compile this with SDL1.2 it runs fine, the quit event is handled immediately. However if I compile it for SDL2, then it takes 5 seconds to get that event. And not just quit, but other events also, like mouse. With sdl2 it takes 95 of the cpu, while with sdl1.2 it's 30 40 . The cpu is dual core, 1.2 ghz (pandaboard). I suspect something, but I'm not 100 sure I'm running this on ubuntu 12.04 which natively supports only sdl1.2. So I had to compile sdl2 from source code, as it's not available in that ubuntu. Could this be the reason? Or any other clues what might be wrong? Thanks!


How do I modify textures in SDL with direct pixel access? I'm trying to use SDL LockTexture and SDL UnlockTexture for directly editing pixels in a texture. I'm using SDL 2.0. Setting the pixel value using the following code doesn't modify the texture void pixels int pitch SDL LockTexture(mytexture, NULL, amp pixels, amp pitch) Set pixel 100,100 to blue ((uint32 t )pixels) 100 100 255 SDL UnlockTexture(mytexture)


Setting Square to Dim in Color on MOUSEUP I'm trying to create a simple recreation of the popular memory game "Simon" using C and SDL2. The idea is that the game is a small window with four squares of different colors that are purposefully dim. When the player clicks on a square, I want it to "light up" until the player let's go of their mouse button, in which it returns to it's original dim color. I have this working to an extent, but the problem is that it only works if the player let's go of the mouse button while the pointer is over the square. If they let go anywhere else, the square stays lit up. Here is the example code if(e.type SDL MOUSEBUTTONDOWN amp amp mouseX gt 10 amp amp mouseX lt 110 amp amp mouseY gt 10 amp amp mouseY lt 110) if(e.button.button SDL BUTTON LEFT) SDL SetRenderDrawColor(renderer, 0, 255, 0, 255) SDL RenderFillRect(renderer, amp squareOne) SDL RenderPresent(renderer) if(e.type SDL MOUSEBUTTONUP amp amp mouseX gt 10 amp amp mouseX lt 110 amp amp mouseY gt 10 amp amp mouseY lt 110) if(e.button.button SDL BUTTON LEFT) SDL SetRenderDrawColor(renderer, 0, 50, 0, 255) SDL RenderFillRect(renderer, amp squareOne) SDL RenderPresent(renderer) As you can see, I'm looking for the user to be clicking in a very specific area, and waiting for them to "unclick" in that same specific area. There has got to be a better way to do this. Would anyone do me the pleasure of offering a few hints?


Should I cap the frame rate in SDL? I know this question has been asked a lot, but I never found an answer suitable for me. I have a game with a fairly big logic system and the movement system I am currently using is calling SDL GetTicks() and measuring the delta time between the frames. I multiply the delta with the speed and I get the pixel movement. The problem with this is that the CPU usage is quite high. I didn't really mind it until my friend started going on about how it was "the end of the world". The question I really want an answer to is if I should cap the framerate, and if a high CPU usage is unwanted (or even dangerous!).


Unable to detect continuous keypress event in SDL I am developing a game using SDL, and am unable to do continuous motion for my object when a key is held down. I'm calling SDL PollEvent() to retrieve all events during a frame, and passing each resulting SDL Event structure into this function void Avatar handle input(SDL Event keyInput) if( keyInput.type SDL KEYDOWN ) Adjust the velocity switch( keyInput.key.keysym.sym ) case SDLK LEFT Move(1) break case SDLK RIGHT Move(2) break The problem is that when I hold down the right or left arrow keys, the avatar only moves once instead of moving continuously for as long as I hold down the key. How can I make the motion continue for as long as the key is held down?


SDL gray scale image from a a color image? I am new to sdl. I have basically have the following codes which can load the images. I know how to access the pixel as below. What I need it to convert the image to 8 bit grey level and 1 bit monochrome separately. I know it got to do with pixel manipulation. Any hint or idea how to to this? I am not too sure what to set for SDL CreateRGBSurface and also once I get the pixel what manipulation to be done?


Background color gradient with SDL I want to create a menu for a game using a color gradient as the background. Is there a way to create a gradient background instead of using an image for it (since I don't know what size the window will be, using an image is no option). Please note I need to achieve this using only the C standard library and the SDL, no other library and no C .


In SDL, what is the difference between using a Surfaces and a Renderer? I am new to SDL and I've been following some tutorials in one tutorial he used Surfaces (a window surface and image surface) and a BlitSurface function to draw images without using any renderer (used SDL Image library for JPG, PNG etc.). And in another tutorial, he used a Renderer. What's the difference between those two? It seemed to me they do the same thing but I'm assuming if they were the same, one wouldn't exist.


Can I create relative filepaths to images in an XCode SDL project? Can I create relative filepaths to images in an XCode SDL project? I have to use absolute filepaths as it is, but it would be much easier if I could make the filepaths relative.


SDL surface inside another GUI component? Is there a way to host an SDL surface inside another GUI component so that SDL is not at the top level? For instance, could I put an SDL surface inside a Java JPanel or other widget?


Can Simple Direct Media Layer be used with WebGL? I have read that on desktop OpenGL SDL is a great way to learn. In looking at WebGL I couldn't find a Web version of SDL. On their site I see bindings for all sorts of languages, but no JavaScript. It seems obvious that this gives an answer of 'no' to my question, but I also came upon code snips while googling around that seemed to be doing it. Whatever the missing piece is I'm not getting it...


Problem getting mouse events while keys held down in SDL2 I'm attempting to write input capturing code using SDL2 on Windows. However, I'm running into a problem. Whenever a key is held down, the SDL event queue has no mouse movement, nor will the mouse move on my screen. Instead, The SDL event queue continually returns the key I am holding down as an SDL KEYDOWN event. Here is a simple example program which reproduces the problem exactly include lt SDL2 SDL.h gt include lt iostream gt int main(int argc, char argv) SDL Init(SDL INIT EVERYTHING) SDL Window window SDL CreateWindow("Moust Input Test", SDL WINDOWPOS UNDEFINED, SDL WINDOWPOS UNDEFINED, 640, 480, SDL WINDOW SHOWN) SDL Event event for( ) while (SDL PollEvent( amp event)) if (event.type SDL QUIT) SDL DestroyWindow(window) return 0 else if (event.type SDL MOUSEMOTION) int x, y SDL GetMouseState( amp x, amp y ) std cout lt lt "Mouse moved to " lt lt x lt lt " " lt lt y lt lt std endl else if (event.type SDL KEYDOWN) std cout lt lt "Code of key pressed " lt lt event.key.keysym.sym lt lt std endl return 0 What I would expect to happen is that, when I hold down a key (for example, 'a'), it prints exactly once Code of key pressed 97 And then, while they key is held down, if the mouse is moved, it prints every time the mouse is moved Mouse moved to wherever Instead, I'll keep seeing over and over again Code of key pressed 97 And I will not get any mouse movement whatsoever on the screen, nor will I get my mouse movement log printed, until I release whatever keys I am holding down. Anybody know how I can capture mouse movement while I have a key held down? The only thing I can think of which could possibly be relevant is I am compiling with MinGW using g Dmain SDL main test.cpp o test.exe L. lib SDL2 lmingw32 lSDL2main lSDL2 mwindows mconsole Thanks. Edit I've also just noticed that the problem persists even when the window is minimized if I am holding a key down in this text window while my program is minimized in another Window, the mouse stops working, though my program is not printing out the key code.


SDL RenderDrawLines isn't drawing complete geometry So I am trying to draw hexagons with SDL RenderDrawLines . It looks to be working fairly well, however, it fails to draw some of the lines. So each of the hexagons in the screenshot is a hex object. They each have a center x y , and an array of SDL Points for the six corners of the hex. Here is the hex object draw call SDL RenderDrawLines( TheGame Instance() gt getRenderer(), corners, HEX NUMBER OF CORNERS) There is some reoccurring condition that causes a vertical line to not be rendered, and I can't seem to figure out why. The two obvious things that stand out don't explain why there is no line The draw order of the objects shouldn't matter since all of the borders for each hex are being drawn. The horizontal distance between adjacent hexes' centers can be 1 because of rounding would lead to a double thick border and not a missing border. If anyone has any insight, I welcome the input. EDIT I have been over suggestions you have mentioned prior to this question, increasing the array of points to 7 is correct, I tested it on a triangle before I tried with hexagons. When you don't close of the shape, you typically get drawn lines that shoot off the edge of the screen. The part on three lines is also something else I discovered while messing around. I included some of my code to show the two ways that I preformed the very thing you mentioned render the hexagon to on screen void Hex draw() draw order of points rotate ccw 90 degrees for actual postion 2 3 1 4 0 5 draw the hex with a fill color 0XAABBGGRR is the bit order for the color param filledPolygonColor( TheGame Instance() gt getRenderer(), vx, vy, HEX NUMBER OF CORNERS, r order(CLEAR)) set outline color to black SDL SetRenderDrawColor( TheGame Instance() gt getRenderer(), 0, 0, 0, 255) draw the hex outline SDL RenderDrawLines( TheGame Instance() gt getRenderer(), corners 2, HEX NUMBER OF CORNERS 2) or SDL RenderDrawLine( TheGame Instance() gt getRenderer(), corners 2 .x, corners 2 .y, corners 3 .x, corners 3 .y) SDL RenderDrawLine( TheGame Instance() gt getRenderer(), corners 3 .x, corners 3 .y, corners 4 .x, corners 4 .y) SDL RenderDrawLine( TheGame Instance() gt getRenderer(), corners 4 .x, corners 4 .y, corners 5 .x, corners 5 .y) Just for clarity, it still occurs in spots where there should be a drawn line. This is a shot with the above code


How can I perform a masked erase in SDL2? I'm trying to implement some shadow lighting effects in my 2D project, and I've concluded that if there is an easy way to perform a masked erase on an SDL Texture, it would make the drawing operations quite cheap. Let's say I have a texture of the part of the level where light is not meant to be rendered. I also have a texture with my "light map" I want to use this to just draw omni lights from my light sources. Then I want to use the first image to 'subtract' the portions of the light map that are not to be rendered on the final scene. Then I draw my "light map" texture on top of my scene, with additive blending enabled. This sounds like a good theory in my head, but I can't see any functions in the SDL2 API that let me do masked erase from a texture. Am I overlooking something? Does anything like this exist?


SDL2 for hardware accelerated graphics? I am attempting to make a 3d game using SDL2 just to learn and have a bit of fun. I was wondering if there is any way to get SDL2 do calculations on GPU. I have read that SDL2 Textures uses GPU for calculation, but is there any way to get it to do calculations from my functions using GPU? For example, if I have a function multiplyVectorWithMatrix, and there is a bunch of additions going on in that function, how would I get SDL2 to do those additions using GPU rather than CPU?


Luminance increase in SDL We have managed to create grayscale picture using the following snippet of codes in SDL. What we need to do now is how to first convert into YUV or YCrCb for it be able to set the luminance value and thereafter back into RGB? const unsigned int gray (component1 component2 component3) 3 const int gray rgb SDL MapRGB(original gt format, gray, gray, gray)


State machine in C for SDL game I want to create a state machine for menu in my SDL game. So this is my code without the SDL I just want to ask if this is a good way to create it. here is a code include lt stdio.h gt include lt windows.h gt enum states Menu, Game, Game over, Exit int main() int game is running 1 enum states state Menu while(game is running 1) switch(state) case Menu state Game printf( quot menu screen with play and exit button. n quot ) need to add if exit or play is pressed if exit then exit program if play than you know... break case Game state Game over printf( quot after play button is pressed game screen will show up. n quot ) after this i will come back to menu. break case Game over state Exit printf( quot screen after game. n quot ) break case Exit printf( quot turn game off. n quot ) this will be in the if function with a game. game is running 0 break Sleep(1000) sleep for a second just for test return 0


SDL Detect change score I have this in my loop , it works but I get verry low fps and game is working in slow motion while (!done) Check for events done processEvents(window, amp player) updateLogic( amp player) sprintf(buffer, "SCORE d", player.currentScore) textSurface TTF RenderText Solid(font, buffer, color) text SDL CreateTextureFromSurface(renderer, textSurface) SDL QueryTexture(text, NULL, NULL, amp textW, amp textH) SDL FreeSurface(textSurface) doRender(renderer, amp player) SDL DestroyTexture(text) I think I need to update those 2 only when score is changing , not every frame..and I don't know how to do it. textSurface TTF RenderText Solid(font, buffer, color) text SDL CreateTextureFromSurface(renderer, textSurface)


SDL TTF render variable This is the way I render the score in my main game , and I made this new project to understand how to use it... It works , the score is updated and it display on the screen but the problem is memory... it increase forever , from 20mb when I start untill it runs out of memory..it nevers stop. And in the main game it's working at 2fps... I hate TTF I just can't understand how it works and how should I do it... every tutorial is in c and I have to make the game in pure C for college...Help. include lt stdlib.h gt include lt stdio.h gt include lt conio.h gt include lt SDL.h gt include lt SDL ttf.h gt include lt SDL image.h gt int main(int argc, char argv) bool quit false SDL Event event SDL Init(SDL INIT VIDEO) TTF Init() SDL Window window SDL CreateWindow("Example",SDL WINDOWPOS UNDEFINED, SDL WINDOWPOS UNDEFINED, 640,480, 0) SDL Renderer renderer SDL CreateRenderer(window, 1, 0) SDL Surface surface SDL Texture texture int score 0 char buffer 50 int texW 0 int texH 0 TTF Font font TTF OpenFont("font3.ttf", 25) SDL Color color 255, 255, 255 while (!quit) SDL RenderClear(renderer) SDL WaitEvent( amp event) switch (event.type) case SDL QUIT quit true break score 100 sprintf(buffer, "SCORE d", score) surface TTF RenderText Solid(font, buffer, color) texture SDL CreateTextureFromSurface(renderer, surface) SDL QueryTexture(texture, NULL, NULL, amp texW, amp texH) SDL FreeSurface(surface) SDL Rect dstrect 0, 0, texW,texH SDL RenderCopy(renderer, texture, NULL, amp dstrect) SDL RenderPresent(renderer) SDL DestroyRenderer(renderer) SDL DestroyWindow(window) SDL DestroyTexture(texture) TTF CloseFont(font) TTF Quit() SDL Quit() return 0


How to alter image pixels of a wild life bird? Hello so I was hoping someone knew how to move or change color and position actual image pixels and could explain and show the code to do so. I know how to write pixels on a surface or screen surface usigned int ptr static cast lt unsigned int gt (screen pixels) int offset y (screen gt pitch sizeof(unsigned int)) ptr offset x color But I don't know how to alter or manipulate a image pixel of a png image my thoughts on this was How do I get the values and locations of pixels and what do I have to write to make it happen? Then how do I actually change the values or locations of those gotten pixels and how do I make that happen? any ideas tip suggestions are also welcome! int main(int argc , char argv ) SDL Surface Screen SDL SetVideoMode(640,480,32,SDL SWSURFACE) SDL Surface Image Image IMG Load("image.png") bool done false SDL Event event while(!done) SDL FillRect(Screen,NULL,(0,0,0)) SDL BlitSurface(Image,NULL,Screen,NULL) while(SDL PollEvent( amp event)) switch(event.type) case SDL QUIT return 0 break SDL Flip(Screen) return 0


Multiple keypresses causing wierd results in SDL I have been building a pong clone. I've been using a mixture of peoples different code to understand the way they structure their games as well as reading on game patterns. Currently I've gotten to draw a paddle on the screen and the player can move it with the keyboard no problem. The issue comes when a player presses a button that is not 'Up' or 'Down'. For instance when the player holds the 'Up' key the paddle travels upwards, but if they simultaneously hold the 'Right' key it causes the paddle to fly downwards at a much greater speed. My keyboard checking code is void GameLoop Input(SDL Event amp ev) if (ev.type SDL KEYDOWN) if (ev.key.keysym.scancode SDL SCANCODE DOWN) player1 gt IsMoving(true) player1 gt velocity 10 if (ev.key.keysym.scancode SDL SCANCODE UP) player1 gt IsMoving(true) player1 gt velocity 10 else if (ev.type SDL KEYUP) if (ev.key.keysym.scancode SDL SCANCODE DOWN) player1 gt IsMoving(false) player1 gt velocity 0 if (ev.key.keysym.scancode SDL SCANCODE UP) player1 gt IsMoving(false) player1 gt velocity 0 The GameLoop is ran within loop that is configured to run at 60FPS. You can see this in this code block here int main(int argc, char argv) Initialise the app and SDL App app(SDL INIT VIDEO) GameLoop game double lastTime 0.0, currentTime SDL Event e while (app.isRunning()) if (SDL PollEvent( amp e)) if (e.type SDL QUIT) app.exit() currentTime SDL GetTicks() 1000.0 if (currentTime gt lastTime 0.01666667) game.Input(e) game.Update() game.Render() lastTime currentTime return 0 This is the paddles update code void Paddle Update() if(moving true) rect.y velocity velocity 50 X rect.x Y rect.y I'm unsure of what is causing the paddle to behave so strangely. Any insight given into this problem or even just the way I've approached this problem would be appreciated.


What exactly does SDL RenderSetClipRect do? I assumed that this function would move the area which is clipped out of conceptual space and copied onto the renderer (and subsequently drawn to the window) i.e. change the origin of rendering but it doesn't seem to do this. Anybody know how it works?


How to make texture for text displaying using SDL ttf with good performance? In my game, there are many units and for each units there's an information widget attached next to them. I use SDL as the game rendering engine. I currently want to display their ID for debugging purposes. However, for each unit, I create a texture with their ID, I render it, then I destroy it. Needless to say that when there are about 40 units on my screen, the game gets pretty laggy (if its any indication, my game currenly weights 25 MB) How can I get over this?


Memory leak around SDL FreeSurface When I call my tile engine function, the amount of memory my program uses begins to spike at about 80 90 megabytes per second. The memory use continues to go up until the program crashes. The function is below. After tinkering with it, I figured out that I could reduce this bricking to about 15 megabytes per second if I called SDL FreeSurface every time I ran the function. But this confused me, because I thought that you are only supposed to use SDL FreeSurface when the program exits so that the images don't continue to occupy the memory. if I don't call SDL FreeSurface before I blit the tiles, do the previously blitted tiles continue to exist? If I don't how do I fix the aforementioned bug? The edit I made to bring the memory bricking down to 15 megabytes per second is commented out. SDL Surface loadedTile NULL SDL Surface modelIMAGE NULL void enviroment blitTiles(SDL Surface windowENVIRO, int tileAmount, int tileType , int tileXenviro, int tileYenviro, bool quitTiles) HDcounter 1 if(loadedTile ! NULL) SDL FreeSurface(loadedTile) loadedTile IBFobjectENVIRO.loadIMG("tileClipSheet.png") for(int tiles 0 tiles lt tileAmount tiles ) switch(tileType tiles ) Black square (unpassable) case 1 IBFobjectENVIRO.blitIMG(tileXenviro 75, tileYenviro, windowENVIRO, loadedTile, 0, 0, 75, 75) HDcounter 1 forbiddenX HDcounter tileXenviro 75 forbiddenY HDcounter tileYenviro forbiddenSpriteWidth HDcounter 75 forbiddenSpriteHeight HDcounter 75 forbiddenSpriteDepth HDcounter 75 break Grey square case 2 IBFobjectENVIRO.blitIMG(tileXenviro 75, tileYenviro, windowENVIRO, loadedTile, 75, 0, 75, 75) break Brown square case 3 IBFobjectENVIRO.blitIMG(tileXenviro 75, tileYenviro, windowENVIRO, loadedTile, 150, 0, 75, 75) break Invisible square (unpassable) case 4 IBFobjectENVIRO.blitIMG(tileXenviro 75, tileYenviro, windowENVIRO, loadedTile, 225, 0, 75, 75) HDcounter 1 forbiddenX HDcounter tileXenviro 75 forbiddenY HDcounter tileYenviro forbiddenSpriteWidth HDcounter 75 forbiddenSpriteHeight HDcounter 75 forbiddenSpriteDepth HDcounter 75 break tileXenviro 75 if(tileXenviro gt level1ObjectENVIRO.level1Width) tileYenviro 75 tileXenviro tileXenviro level1ObjectENVIRO.level1Width if(quitTiles true) SDL FreeSurface(loadedTile)


What does FPSManager.lastticks stand for in SDL gfx? I'm having trouble finding documentation on SDL gfx, and I can't figure this out. I've managed to use SDL gfx to automatically cap the framerate, and I it's working a lot better than my manual attempt (combining SDL Delay and SDL Getticks). Now I've been trying to learn more about it, and I stumbled onto something. Here's the whole struct typedef struct Uint32 framecount float rateticks Uint32 lastticks Uint32 rate FPSmanager Most variables in this struct are pretty straightforward, but I have no idea of what lastticks stands for. Does anyone know?


Background color gradient with SDL I want to create a menu for a game using a color gradient as the background. Is there a way to create a gradient background instead of using an image for it (since I don't know what size the window will be, using an image is no option). Please note I need to achieve this using only the C standard library and the SDL, no other library and no C .


Separating logic update from render drawing code in a single thread using sleep I've read that the speed of game objects should not be hindered by FPS but instead should be based on time. How can I seperate the update draw code to maximize performance without limiting the drawing rate and provide a constant logic update rate based on time? My current pseudo code is as follows loop draw() if (ticksElapsed() gt 100) update() ticks ticksElapsed() The problem is the drawing code hinders the performance of the update() rate. And it consumes 100 cpu because if sleep is thrown in, it throws off both drawing logic functions. I am also using SDL and it doesn't seem to have a vsync option. I've also heard of the terms fixed and variable time stepping however I'm not sure how that can be done with sleep()