texts:
I've got a bunch of objects of varying size and velocity which gravitate towards each other. On every update, I have to go over every object and add up the forces due to gravity of every other object. It doesn't scale very well, is one of two big bottlenecks I've found in my game, and I'm not sure what to do to improve the performance.

It feels like I should be able to improve the performance. At any given time, probably 99% of the objects in the system will only have a negligible influence on an object. I of course can't sort the objects by mass and only consider the top 10 largest objects or something, because the force varies with the distance more than with the mass (the equation is along the lines of force = mass1 * mass2 / distance^2). I think a good approximation would be to consider the largest objects and the closest objects, ignoring the hundreds of tiny fragments of rock on the other side of the world that can't possibly affect anything -- but in order to find out which objects are closest I have to iterate over all the objects, and their positions are changing constantly, so it's not like I can just do it once.

Currently I'm doing something like this:

private void UpdateBodies(List<GravitatingObject> bodies, GameTime gameTime)
{
    for (int i = 0; i < bodies.Count; i++)
    {
        bodies[i].Update(i);
    }
}

//...

public virtual void Update(int systemIndex)
{
    for (int i = systemIndex + 1; i < system.MassiveBodies.Count; i++)
    {
        GravitatingObject body = system.MassiveBodies[i];

        Vector2 force = Gravity.ForceUnderGravity(body, this);
        ForceOfGravity += force;
        body.ForceOfGravity += -force;
    }

    Vector2 acceleration = Motion.Acceleration(ForceOfGravity, Mass);
    ForceOfGravity = Vector2.Zero;

    Velocity += Motion.Velocity(acceleration, elapsedTime);
    Position += Motion.Position(Velocity, elapsedTime);
}

(note that I've removed a lot of code -- for example the collision tests, I do not iterate over the objects a second time to detect collisions).

So I'm not always iterating over the whole list -- I only do that for the first object, and every time the object finds the force it feels toward another object, that other object feels the same force, so it just updates both of them -- and then that first object doesn't have to be considered again for the rest of the update.

The Gravity.ForceUnderGravity(...) and Motion.Velocity(...), etc. functions just use a bit of XNA's built in vector math.

When two objects collide, they create massless debris. It's kept in a separate list and the massive objects do not iterate over the debris as part of their velocity calculation, but each piece of debris must iterate over the massive particles.

This doesn't have to scale to incredible limits. The world isn't unlimited, it contains a border which destroys objects that cross it -- I'd like to be able to handle maybe a thousand or so objects, currently the game starts to choke around 200.

Any thoughts on how I might improve this? Some heuristic I can use to shave the loop length from hundreds down to just a few? Some code I can execute less often than every update? Should I just multithread it until it's fast enough to allow for a decent sized world? Should I try to offload the velocity calculations to the GPU? If so, how would I architect that? Can I keep static, shared data on the GPU? Can I create HLSL functions on the GPU and call them arbitrarily (using XNA) or do they have to be part of the draw process?


texts: XNA partially extending the content pipeline using a ModelContent

texts:
I am trying to extend XNA's content pipeline in order to import a model in .obj format (a very simple and text-based format, see here for details). Writing a full extension library seems like an overkill to me so I decided I would only create a custom importer and a processor which returns a ModelContent so that I could use the default writer and reader.
My processor sort of works but not exacly as expected: what should look like an aircraft is actually a bunch of triangles stick together! Before writing this I had a simple class derived from DrawableGameComponent which loaded the model in its LoadContent, but that's not exacly XNA-ish. The point is that the code worked, so there must be a problem in the construction of the MeshContent.
I have followed the pattern I found in this question during my researches.

Here's the relevant part:

[ContentProcessor( DisplayName = "dotObjProcessor" )]
public class dotObjProcessor : ContentProcessor<dotObjContent, ModelContent> {
    public override ModelContent Process( dotObjContent input,
        ContentProcessorContext context ) {

        var mc = new MeshContent( );
        foreach ( dotObjContent.Vertex p in input.Vertices )
            mc.Positions.Add( new Vector3( p.X, p.Y, p.Z ) );

        var gc = new GeometryContent( );
        foreach ( dotObjContent.Face f in input.Faces ) {
            gc.Vertices.Add( f.V1 );
            gc.Vertices.Add( f.V2 );
            gc.Vertices.Add( f.V3 );

            gc.Indices.Add( f.V1 );
            gc.Indices.Add( f.V2 );
            gc.Indices.Add( f.V3 );
        }

        mc.Geometry.Add( gc );
        MeshHelper.CalculateNormals( mc, true );

        return context.Convert<MeshContent, ModelContent>( mc, "ModelProcessor" );
    }
}

A dotObjContent is the output of my importer, it simply contains two collections for vertices and indices.


texts: Normal maps in 3dsMax - OgreMax - how to view associated tangent vectors?

texts:
Reading this post I found out that 3dsMax might not use the same tangents when rendering normal mapped objects. In my case, I was using Ogre and OgreMax to analyze results and they were very inconsistent with what Max was showing. I am able to "colour map" the tangent space in Ogre using shaders, but in Max I can't find out how it is computed wrt to the actual geometry. I also posted the question on the Ogre forums, but nobody answered. Has anyone encountered such an issue up until now? How did you go around it?

For further information, this is the Ogre post.


texts: How to render a field of view of over 180 degrees?

texts:
In most 3D renderings, a view frustum is used.
This has the problem, that things get stretched out towards the edges.
At "normal" fov (field of view) of about 60 degrees, the effect is not very noticeable, unless compared side by side (example) but at a higher fov of something like 120 degrees it's really noticeable by making things near the edge look way larger/closer (example).
A fov of anything near or over 180 degrees breaks the rendering completely.
So far, I couldn't find anything on how to render in such a way that fixes this or even how it's called.
The ultimate goal would be to be able to render up to 360 degrees (ignoring the hardware needed, to display it) without any distortion, relative to other parts of the image.
So, how would I approach rendering that? Is there already some open source software, I can take a look at?


texts: How can I animate characters' static-geometry eyes?

texts:
Here's a Nintendo example:

Specifically, the animation of the pupils seems not to animate the geometry.

How is this done?


texts: How can Perlin Noise be modified to not tile?

texts:
In vanilla perlin noise, the texture repeats after 256 coordinates, due to the way it picks a gradient vector. In games that require an infinite procedural world, however, this is not an acceptable tradeoff. This requires a different method to pick the gradient vector. I need an alternative that is portable in C++, meaning that I will get the same noise for the same seed on different systems.

I have come across two options to do this:

Using C++'s random api, using bitshift-modified coordinates as the seed, but this is very slow in practice and is too reliant on the exact implementations of the C++ random number generators, which may or may not guarantee the same sequence of numbers across platforms.
Use a much faster random hash function I found in the old freespace virgin "perlin noise" (actually value noiswe) tutorial, which I saved before it went down. The issue with this one is that it has bitshift on signed integers, and thus has undefined behaviour in C++.

EDIT: Something I forgot to mention in the original question is that I need to be able to re-seed the perlin noise engine to get a different output. With vanilla perlin noise, I can simply use a seeded random shuffle on the hash table lookup array before calculating anything else.


texts: how to sync clients and local avoidance in mobile RTS game?

texts:
I have been making mobile RTS game in Unity look like Clash Royale similarly.

Unfortunately, I faced to two big problems.

First is two phones(clients) to be synchronized each other in game state.
And second is "path finding" or "local avoidance"(collision check).

To solve the path finding issue, I have searched about "Flow Field".

Should I do consider on 3 layer map(cost field, integration field, flow field) to apply "Flow field"?
If I do apply "flow field" to my game, can I have a liberty from the problem of Sync two clients?

Thank you in advance.


texts: Box2d on authoritative server for Unity client

texts:
I'm creating a multiplayer platform and shooting game in unity, using unity2d's own physics system (box2d).
But the truth is that I am quite lost in the creation of an authoritative server in c ++.
I have quite clear and experience in the use of socket for communication between client and server, I do not know how to approach the issue of simulating the physics of my game on the server so that it decides the positions/movements of the clients.
Can anyone guide me to use box2d on the server, as I simulate the game on the server? Is this a good option or would it be better to implement my own game physics than to use the non-deterministic engine?
Thank you very much and sorry for my level of English


texts: How do multi-platform games usually store save data?

texts:
I realize this is a bit of a broad question, but I was wondering if there is a "standard" in the industry when it comes to storing save data for games (and is it different across platforms - Xbox/PS/PC/Mac/Android/iOS?)

For example for a game like Assassin's Creed or The Walking Dead: They are on multiple platforms and they usually have to save enough information about the player and their actions. Do they use something like XML files, databases, or just straight binary dumps? How much does it differ from platform to platform?

I would appreciate it if someone with experience in the game industry would answer this.


texts: Collision causing First Person Controller to go haywire

texts:
I have created a first person controller as an enemy in my game (Zombie). My character is an archer that uses arrows as projectiles that are shot with the following code:

if(Input.GetButton("Fire1")) {
    shotForce += 45f;
}

if (Input.GetMouseButtonUp(0)) {
    Rigidbody shot = Instantiate (projectile, shotPos.position, shotPos.rotation) as Rigidbody;
    shot.mass = shotMass;
    shot.AddForce (Camera.main.transform.forward * shotForce);
    shotForce = 0f;
}

I have a script to parent the fired arrow to the collided object which works fine for most objects in the game, but  my enemy object (Zombie) speeds up and moves all around the place on a collision, I'm new to unity, I've spent a few hours trying to resolve this with out success.

I have a Rigidbody, Charcter controller and First person controller on the Zombie.

I have a Rigidbody and Sphere Collider on the Arrow.

The method I think is causing the problem:

void OnCollisionEnter(Collision collision){
        if (this.flying) {
            this.flying = false;
            Destroy (this.GetComponent<Rigidbody>());
            this.transform.position = collision.contacts [0].point;
            GameObject anchor = new GameObject ("ARROW_ANCHOR");
            anchor.transform.position = this.transform.position;
            anchor.transform.rotation = this.transform.rotation;
            anchor.transform.parent = collision.transform;
            this.anchor = anchor.transform;
            collision.gameObject.SendMessage ("arrowHit", SendMessageOptions.DontRequireReceiver);
        }
    }

I think the issue is with the line anchor.transform.parent = collision.transform;
Maybe there is a solution without parenting the arrow to the Zombie?

I'm stumped at this stage any help appreciated.


texts:
As a indie, you might not work in a company. And you may have a great game idea and you feel it gonna be a big success. When you released your game. How do you protect it as your own creation? So that someone also can't steal the title and publish a "sequel" e.g. Your-Game-Name 2,3,4. Or even produce by-products like Angry Birds but without your permission.

So how we can prevent these from happening by legal methods. Like copyrights, trademarks? If a professional can fill us those info, it will be great.


texts:
I'm making a game in which I have different weapons. One of them is a hand grenade. Well, the question is:

I made an animation with mecanim (I don't know if is the correct way) with the grenade being is a child of the main character. Then, the animation is correct (the grenade goes to high scale and I have the false sensation that is going up, to the camera).

The problem is that this grenade is attached to the character, and when I move the character, the grenade moves with him. I need the grenade to not be linked to the character when it's launched. And when I instantiate a new grenade, I need this animation playing.

I don't know if I explained the situation well, but this is the idea, an animated grenade launching when the player press the shoot button... what is the best way to do this?


texts:
(Sorry if this shouldn't be asked here, I'm unsure if it's appropriate based on what's allowed here.)

I'm not developing a game, but I'm very curious about this. I've played some large open-world games recently (Dishonored, for example), and it boggles my mind how much information must be stored for save files. If I pick up a bottle from where it spawned and throw it, then save while it's in mid-air, the save file needs to contain a) what type of bottle it is, b) where it is right now, c) what orientation it's currently in, and d) what its current trajectory is. This is the case for every non-fixed asset in the current level. Pathing NPCs have to have their current state tracked as well.

So, in general, how do games accomplish this? I'm sure the implementation varies, I'm not asking for any specific game, but the overall concept must be similar across games. Even more impressive to me is that quick saves often seem to be instant, with no delay whatsoever after pressing the key.


texts:
I'm creating a 2D Sidescrolling Action RPG with MonoGame and I am using a finite state machine. A state consists of an animation and some behavior, only one state can be executed at once, however:

If the player is moving left/right and then jumps, or if he's jumping and then moves left/right I want to play a specific horizontal jumping animation while executing the behavior of both states at once. How is this usually handled? Should I make a completely seperate state for this and copy the behaviors over? That doesn't seem right in accordance to the DRY principle.

BTW I'm going to have a lot of similar merge states, so just making an exception this time won't do.


texts: Trigger scene loading in one device from another device using Unity WWW class

texts:
I have a master device and client device. I want to load a scene in the client device by pressing a button in the master. My method is, when the button is pressed in the master device, a data is stored in a server using the WWW class and in the client device it is checked whether the data is there, through a coroutine.

But, in the client device, the coroutine is not waiting for the trigger from the master. Instead it continues the execution. Because in the yield return statement, it says downloading is complete. Can I make it to wait for a trigger from the server?


texts: Rasterizing parametric solids in Minecraft voxel space

texts:
I'm trying to render giant procedurally generated trees in Minecraft. I have code that generates a tree model and represents it parametrically as a collection of cones and spheres using vectors and scalar values. As a final step I'd like to rasterize the parametric model into Minecraft blocks.

So far I've only found resources for rendering 3d parametric solids onto the 2d viewport. Does anybody have any recommended resources or algorithms I can use to rasterize my tree model into Minecraft's 3d voxel space?


texts:
Base question: How can I make a swinging rope in box2d?

Context: The idea is to have a rope where the player can grab it, swing a little bit to get more "momentum" and reach the next platform. Like in the Mario games for Nintendo DS and Wii.

What I did: I constructed a chain like rope with a series of RevoluteJoint. This is the fixture of the different links:

fixtureDef.shape = robeLinkShape;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.0f;
fixtureDef.restitution = 0.0f;
fixtureDef.filter.categoryBits = Box2DConst.BIT_ROPE;
fixtureDef.filter.maskBits = Box2DConst.BIT_PLAYER;

BodyDef bodyDef = new BodyDef();
bodyDef.angularDamping = 1.0f;
bodyDef.linearDamping = 1.0f;

I've implemented a ContactListener which creates a RevoluteJoint to connect the body and on of the links of the body. Now the problem I face is this: The rope does not swing, if I apply a linearImpulse to the player (attached to the rope) e.g. to the left, it goes to the left but it doesn't swing back. If the player isn't attached the rope swings.

Last points:

I made the player a dynamic body with a density of 1. Is it better, if the player body does not have a density set?
If the chain is to "light" (lower density) the player can torn it apart if he is attached to the rope. If I connect the last link with the first link of the chain with a RopeJoint the last and the first link stay at the same distance but for some reason, the links between still get torn apart. Question is, should I make my rope only of RopeJoins?

I know there are some tutorials out there with some instructions but some of them use a special class which is not available to me and other simply construct a rope and use a MouseJoint. Again in this scenario my rope thing looks good the problem that when the player body is attached to it it behaves a little bit strange. I know there are also similar posts to mine but since I have some sort of a working solution there solution (if the have any) was not helpful.

Update

If I create the rope solely from RopeJoints I get a nice swinging rope. It behaves exaclty as I woulrd expect. If I then a RevoluteJoint with a density (my player body fixture also has a density) the rope does no longer swing.


texts: Conveying a claustrophobic atmosphere in cavalier oblique projection

texts:
I need your collaborative knowledge in finding the best way to graphically represent a scene in a manner that would suit a SNES-era rôle-playing game. I've chosen to represent the game in what I'm informed is called "cavalier oblique" projection, which is the same sort of perspective employed in titles like EarthBound:

Wherein articles' fronts and one side are shown, but characters face the camera head-on. For as much reason as anything, this is to avoid the "top-down" view employed by 300% of RPG Maker titles. I don't want to look like a "me-too" player.

The scenario

In the title, the player character has their return path blocked off, with the only path to progression being one leading through a series of very tight-fitting caves. The claustrophobia of the area is  very important, as it's one of the main sources of suspense to which the player is subjected.

The problem

I can't think of a single way to display claustrophobic, branching caves with dead-ends and very tight holes in the projection I've displayed above. There are a few works-around I can think of that revolve around changing the projection (either to a first-person view, which will be immensely difficult to navigate, or to a side-on view like Dig Dug, which is more intended to show branching paths across a y axis as opposed to an x axis) - doing this risks appearing jarring to the player, however, and I'm aiming for immersion above all else.

I ask you, GD - can you think of any such scenarios from your favourite retro games, and how did they display them to the player? Any reference I can get for a successful execution will be immensely appreciated.


texts: Determine whether a shape formed from a series of other shapes is 'unbroken'

texts:
I have a grid of tiles in a game and each tile can have a certain simple shape on it.

I want to be able to determine whether the combined shape from any given arrangement of these tiles results in an 'unbroken' or 'broken' larger shape.

For example; this is an example of an 'unbroken' shape...

And this is an example of an 'broken' shape...

I'll be able to write the necessary code once I figure out the logic of this problem, but so far I've been struggling.

I've tried data tables associated to each tile that describe it's edges, for example :

var edges = {
    top : false,
    right : true,
    bottom : true,
    left : false
}

And from this I can determine whether each tile is 'connected' to it's neighbours. But this doesn't help for all situations.

EDIT 1:
Multiple clusters of isolated 'unbroken' shapes would be considered a 'broken' shape...

EDIT 2:

Also, an 'unbroken' shape can be achieved if a shape tile's edge is not connected to every neighbouring tile, it can be just one connection. For example I would consider this to be 'unbroken' ...

Anyone got any ideas on this?


texts: Animation imported from Maya has interpolation issues

texts:
I have imported animation from Maya (.fbx) and the curves for the animation in Unity are very different than in Maya. I can clearly notice a flicker for few seconds when I am scaling the object (0 to 1) in loop. The curve for scaling is shown below.
The rest in the animation work fine except for the scale. The problem is that Unity adds interpolation automatically to these curves which is why it creates an issue. I have selected the keys in the curves for the scale attribute and "Both Tangets -> Constant", but it did not have any effect.
How can I fix this?


texts:
I have found a 3D sphere in a closed-source game engine that I really like the look of and would like to have something similar in my own 3D engine.

This is how the sphere looks like when it is created in the game engine, at program/game start:

At program start, a function named CreateSphere is called and the user has the option to choose a 3D position and a radius of the sphere. That's all I know about the function since the engine is closed source.

Anyone have any idea of how this sphere might be generated programmatically?
I have checked other posts/sites discussing spheres but none of them has the look of the sphere in the image.

Edit: removed some unnecessary information to get to the point of what I need help with.


texts:
A vertex shader is basically a transformation function that converts a vertex in your world space to a space that can be rendered on screen.

Since the screen is a 2 dimensional surface whats the purpose of the intermediate clip space? Why not have the vertex shader directly transform a 3d vertex to a 2d point on the raster surface?


texts: How can I read an image from a binary file?

texts:
I'm trying to put all the assets inside a binary file and then trying to read them from the file itself, without scattering all them around in separate folders to let them exposed. What I'm trying to achieve is something like the way that RPG Maker and Wolf Editor use to join all the images / sounds of the game into a single customized format file (e.g. Data.wolf).

It's a very simple security's method but is enough for what I'm planning.

For now, I have the following code for reading a PNG file inside the binary, that always prints an error's message when it trys to create a new surface from IMG_LoadPNG_RW, saying "Error reading the PNG file."

tString sResult{};
cFile_Manager::tRead_File oRead(sDir, std::ios::binary);

if(oRead.is_open()) {
    tString sLine{};
    while(getline(oRead, sLine)) sResult += sLine + "\n";
    oRead.close();
}else {
    throw cLog("\n\n[ERROR] Wrong dir passed.\n\nDIR: %s\n\n", sDir);
}

SDL_RWops* aRW{};
aRW = SDL_RWFromConstMem(&sResult, sizeof(sResult));

if(!aRW) // Error message

SDL_Surface* aSurface{};
aSurface = IMG_LoadPNG_RW(aRW);

if(!aSurface) // This is where SDL shows "Error reading the PNG file."

EDIT: Omg I made some mistakes, now this is the correctly code. Now it gives a different error: "PNG file corrupted by ASCII conversion"

    char* sBuffer{};
    if(oRead.is_open()) {
        oRead >> std::noskipws;
        oRead.seekg(0, oRead.end);
        int iLength = oRead.tellg();
        sBuffer = new char[iLength];
        oRead.seekg(0, oRead.beg);
        oRead.read(sBuffer, iLength);
        oRead.close();
    }else {
        throw cLog("\n\n[ERROR] Wrong dir passed.\n\nDIR: %s\n\n", sDir);
    }

    SDL_RWops* aRW{};
    aRW = SDL_RWFromConstMem(sBuffer, sizeof(sBuffer));


texts: Reduce Blur and headache during gameplay

texts:
I am implementing a browser based Javascript game here.

On tougher levels when the speed of the game increases, what we observe is that the user will experience headaches and the view will start to blur when the user stares at the screen for some reason.

How can we find the reason for this reaction in the user and avoid it?

How to simulate the problem -

Go the link
Click on Play
Play the third level for 5 - 10 seconds


texts: I recently found Jump Point Search and it seems like a really interesting algorithm. But I wonder about what its performance is like when your grid is of infinite size. When searching diagonally, is it not possible that the orthogonal rays being sent out can go on for an arbitrarily long amount of time on an infinite grid even if the place you want to pathfind to is just a few steps away? Is JPS feasible in general for such grids?


texts:
I'm trying to play sounds in a Java game with the following code:

AudioStream audioStream = new AudioStream(stream);
AudioPlayer.player.start(audioStream);

The stream variable is just an InputStream to the resource. By the first time this code is called, the sound is played as expected, but by the second time the program just hangs, not even an exception is thrown.

I don't know what's going on or how to prevent this. If I try closing either stream or audioStream after the above code, the program doesn't hang, but no sound is ever played at all.

Any tips are welcome, thanks.


texts: How much extra power is required for a stereoscopic 3D game?

texts: If we use Cryengine 3 for game development and make the game 3D compatible. Because 3D sends out two pictures, will this mean that you need a computer with twice the "power"? So if you get 30 fps when playing normal you will need 60 fps for playing with 3D?


texts: How can I display triangle faces (not quads) in Cinema4D?

texts:
I started to learn Cinema 4D. I've noticed it's really easy to use for motion graphics, but I want to use it for modeling for games/realtime 3d engines.

Before I used 3dsmax and it was easy to estimate how a model would look/behave in a 3d engine. The two main things I did was displaying Polygon triangles and displaying the Polygon Count.

I've found the Total Polygons tick in HUD settings in Cinema 4D, but I can't find any display mode that will show triangles.

Is there there a way to display triangle faces/not quads in Cinema4D ? If so how ?

There is a Triangulate function, but I'd rather not Triangulate/Untriangulate all the time, especially since it's converting back and forth between the two doesn't always produce the same result.

I imagine I'm asking for old school techniques, but I plan to use these to make low poly models for web(canvas/webGL) and mobile.


texts: Is it legal to use the game mechanics of risk if I don't use their name?

texts: I'm currently developing an idea for a conquest-style board game similar to Risk. I was wondering if I would be legally entitles to use some game mechanics that appear in that game so long as I don't use Risk's title or logo or anything.


texts:
I have a Array data structure right now, which contains 10  soldiers in my army.

They can setup initially in various formations  -
e.g.

 o  o  o
 o  o  o
o  o  o  o

The user can move one of the soldier(currently selected) with the joystick.

 o  o  o
 o  o  o
o  o  o
         o

When he moves I want to automatically adjust the rest of the soldiers position so that they occupy equal areas in the scene, as well as still follow their orignal formation to some extent.

Somehow like this http://arborjs.org/halfviz/#/Mzg

How do I do this? What kind of algorithms should I look at?
How should store my soldiers? which data structure?


texts:
when i turn the camera with

var tspeed:float=2.0;

function Start () {

}

function Update () {
if(Input.GetButtonDown("tleft")){
transform.Rotate(0, tspeed* Time.deltaTime, 0);
}
if(Input.GetButtonDown("tright")){
transform.Rotate(0, -tspeed* Time.deltaTime, 0);
}

}

it works when pressing the button once but when i hold it it dosnt turn any more and i have to press the button again.how to make it turn when i hold the key?

im using javascript.


texts:
Using LWJGL what is the easiest way to load a 3D model to be drawn on screen?

I know LWJGL doesn't have built in loading support so I am looking for a small library that would help to load specifically .blend files.


texts: How to draw circular sectors on polar grid only within bounding rectangle

texts:
I'm attempting to optimize a game map by only drawing circular & annular sectors within the current viewable rectangle bounds.

The solution should cover both cases in the example graphic (Figs 1 & 2). I have a version of Figure 1 working which converts the rectangle vertices to polar coordinates and calculates start/end angles and inner & outer radii to draw within, however this does not work when the rect overlaps the centre of the circle (Fig 2).

Drawing is currently being done with JavaScript & SVG, so an example using those would be ideal (or just the maths portion in JS). Also, each of the 'wedges' in the grid should be drawn separately, as they each need to be referenced as discrete objects by the engine.


texts: Libgdx Box2D and Screen Viewport Scaling

texts:
I am currently having problems getting an easy to manage system of scaling my units for use with box2D. Normally I would create virtual units to go along with me viewport and camera but since I am using a screen viewport this is not as easy as it seems. I have tried scaling my viewport by setting the units per pixel to 1/100 which will then scales my world by 100 times. Then I set set my sprite batch projection to be 1/100 as well as my tiles map renderer scale to be 1/100 this led to my box2D elements of size .64 to be 64 pixels large which leads to a good looking simulation as well as a good size. The only problem is then any sprite I use must also be scaled with a scale of 1/100. Also my scene 2d HUD must also be scaled. This works but it is confusing to manage and very time consuming to write out all the scaling etc. I am looking to see if there is a way to use world units where 1 world unit is 100 pixels to make my box2D elements and use screen coordinates for the rest of my drawing etc. Also if there is an easier way to do this that I am not thinking of please let me know. I will try to post code later tonight when I am back at my computer.

EDIT:
I created a test project to work on just the scaling factor of my game and here is my test code.

@Override
public void create () {
    camera = new OrthographicCamera();
    camera.translate(new Vector3(camera.viewportWidth / 2, camera.viewportHeight / 2, 0));
    vp = new ScreenViewport(camera);
    vp.setUnitsPerPixel(1/100f);

    batch = new SpriteBatch();
    img = new Texture("badlogic.jpg");
    sprite = new Sprite(img);
    sprite.setScale(1/100f);

    world = new World(new Vector2(0, (float) -9.8), true);
    BodyDef bdef = new BodyDef();
    bdef.type = BodyType.DynamicBody;
    bdef.position.set(1, 1);
    body = world.createBody(bdef);
    FixtureDef fdef = new FixtureDef();
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(1, 1);
    fdef.shape = shape;
    body.createFixture(fdef);

    dr = new Box2DDebugRenderer();

    map = new TmxMapLoader().load("Levels/bricksTest.tmx");
    mapRenderer = new OrthogonalTiledMapRenderer(map, 1 / 100f);
}

@Override
public void render () {
    camera.update();
    sprite.setX(body.getPosition().x - sprite.getWidth() / 2);
    sprite.setY(body.getPosition().y - sprite.getHeight() / 2);
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    mapRenderer.setView(camera);
    mapRenderer.render();
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    sprite.draw(batch);
    batch.end();
    world.step(Gdx.graphics.getDeltaTime(), 6, 2);
    dr.render(world, camera.combined);
}

@Override
public void resize(int width, int height) {
    vp.update(width, height, true);
}

This code runs and produces the expected results, but I feel there has to be some easier way. Also ignore any of the size numbers/horrible sloppiness of this code because this is only a test project and is not from my actual game.

This is a picture of the final result. Note: The box2D box is not the same size as the image because I wanted the box to be about the size of a character from my game for this test. I also moved the position of the box to x = 5 and y = 5 so it is easier to see.


texts: How to read the binary file generated by the Unity profiler?

texts: I'd like to know how can I read the binary file generated by profiling Unity game and how can I save it on external hard disk.


texts:
i am currently trying to dive into 2D programming with DirectX, especially bulding a tile based sidescroller. I have worked with some chapters from a book (Advanced 2D Game Development) but always tried to create something on my own (to get the most out of it - because you never will learn anything if you are not doing it yourself).
But now i am kinda stuck with the camera work in 2D.
I do realize that there different matrices to tranform the objects to world space, then the world space to view space and then to projection (camera) space. Do i really need all of those for a 2D game?

I have a camera class (out of the book) and was trying to use it to "roam" around with the camera (i am currently drawing a grid, with D3DXLine - bigger than the screen - and i would like to float over it with my camera):

Camera::Camera()
{
    p_position = D3DXVECTOR3(0.0f, 0.0f, 10.0f);
    p_upDir = D3DXVECTOR3(0.0f, 1.0f, 0.0f);

    float aspectRatio = (float)g_engine->getWindowWidth() / (float)g_engine->getWindowHeight();

    this->setPerspective(3.14159f / 4, aspectRatio, 1.0f, 2000.0f);
}

Camera::~Camera() { }

void Camera::setPerspective(float fov, float aspectRatio, float nearPlane, float farPlane)
{
    this->setFOV(fov);
    this->setAspectRatio(aspectRatio);
    this->setNearPlane(nearPlane);
    this->setFarPlane(farPlane);
}

void Camera::setPosition(float x, float y, float z)
{
    this->p_position.x = x;
    this->p_position.y = y;
    this->p_position.z = z;
}

void Camera::Update()
{
    D3DXMatrixPerspectiveFovLH(&this->p_matrixProj, this->getFOV(), this->getAspectRatio(), this->getNearPlane(), this->getFarPlane());
    g_engine->getDevice()->SetTransform(D3DTS_PROJECTION, &this->p_matrixProj);

    D3DXMatrixLookAtLH(&this->p_matrixView, &this->p_position, &this->p_target, &this->p_upDir);
    g_engine->getDevice()->SetTransform(D3DTS_VIEW, &this->p_matrixView);
}

I am calling the Update() in every game_update()

Now i am wondering why there is no SetTransform(D3DTS_WORLD, ...) according to the camera movement. Is it just missing and i would have to implement it by myself, or do i need to set it elsewhere? I am kinda lost of how the "normal" set up would be to implement such a thing, and maybe a camera following the player (i guess i would have to the the World Transform according to the player position, am i right)?

Maybe someone can give me some clearance, or just a little tutorial

EDIT: Forgot to mention that it is not working right. I am currently Drawing two things: one Sprite with the D3DXSprite and the grid the D3DXLine.

EDIT2: Here is how i transform my sprites and set the world Matrix. It is still not working though :(. Any ideas?

void Sprite::transform()
    {
        D3DXMATRIX mat;
        D3DXVECTOR2 scale((float)this->_scaling, (float)this->_scaling);
        D3DXVECTOR2 center((float)(this->_width*this->_scaling)/2, (float)(this->_height*this->_scaling)/2);
        D3DXVECTOR2 trans((float)this->getX(), (float)this->getY());
        D3DXMatrixTransformation2D(&mat, NULL, 0, &scale, &center, (float)this->_rotation, &trans);
        g_engine->getSpriteHandler()->SetTransform(&mat);
    }

If you need any more code, please let me know!
Thanks a lot!


texts: What is the best approach to resource management in game design?

texts:
I studied computer engineering before but have been lagging in the technical aspects as of late.

Seeing as I think it would be to my advantage as a designer to understand how resources are used and calculated. I would like to ask if people here know of methods to compute to a certain degree how much power/resource a design would entail? (i.e. how many polygons per scene, how many AI running, how many physics components, particles etc.)?


texts:
I'm in the process of learning Open GL and am having issues with lighting on my Terrian, I don't know if the issue is related to how I calculate my normals or the shader itself (I am using the shader from the Open GL wikibook - Lighting Arc tutorial 1). I calculate the normals like this:

void Terrian::construct_normals()  {
    terrian_normals.reserve(width * height);

    for (int i = 0; i < terrian_elements.size() / 3; i++)  {
         int index1 = terrian_elements.at(i * 3);
         int index2 = terrian_elements.at(i * 3 + 1);
         int index3 = terrian_elements.at(i * 3 + 2);

         glm::vec3 side1 = terrian_vertices.at(index1) - terrian_vertices.at(index3);
         glm::vec3 side2 = terrian_vertices.at(index1) - terrian_vertices.at(index2);
         glm::vec3 normal = glm::cross(side1, side2);
         normal = glm::normalize(normal);

         terrian_normals.emplace_back(normal);
         terrian_normals.emplace_back(normal);
         terrian_normals.emplace_back(normal);
    }

    std::cout << "Terrian Vertices: " << terrian_vertices.size() << "\nTerrian Normals: " << terrian_normals.size();
}

And the vertex shader can be viewed here:

http://pastebin.com/3vU8SHvK

Here's what the terrain looks like:

If you would like me to post any more of my code I would be happy to do so.

Edit:

Vertices:

void Terrian::construct_vertices()  {
    terrian_vertices.reserve(width * height);
    terrian_colors.reserve(width * height);

    std::cout << "Generating data\n";

    for (int y = 0; y < height; y++)  {
        for (int x = 0; x < width; x++)  {
            int i = x + y * width;

            terrian_vertices.emplace_back(glm::vec3(x, terrian_heightmap[y][x], -y));
            terrian_colors.emplace_back(Color(0.0, 1.0, 0.0, true));
        }
    }
}

and elements:

void Terrian::construct_elements()  {
    terrian_elements.reserve((width - 1) * (height - 1) * 6);

    for (int y = 0; y < height - 1; y++)  {
        for (int x = 0; x < width - 1; x++)  {
            GLushort bottom_left = x + y * width;
            GLushort bottom_right = (x + 1) + y * width;
            GLushort top_left = x + (y + 1) * width;
            GLushort top_right = (x + 1) + (y + 1) * width;

            terrian_elements.emplace_back(top_left);
            terrian_elements.emplace_back(bottom_right);
            terrian_elements.emplace_back(bottom_left);

            terrian_elements.emplace_back(top_left);
            terrian_elements.emplace_back(top_right);
            terrian_elements.emplace_back(bottom_right);
        }
    }
}


texts: I know how to make the effect of moving an object on the z axis, and strafing, but how do you make the effect of the view turning, I don't use any 3d libraries or engine


texts: Why is permadeath essential to a roguelike design?

texts:
Roguelikes and roguelike-likes (Spelunky, The Binding of Isaac) tend to share a number of game design elements:

Procedurally generated worlds
Character growth by way of new abilities and powers
Permanent death

I can understand why starting with permadeath as a premise would lead you to the other ideas: if you're going to be starting over a lot, you'll want variety in your experiences. But why do the first two elements imply a permadeath approach?


texts: How to generate Normal Maps from Lighting Profiles?

texts:
How might I go about generating a normal map from a lighting profile(light map)? I saw "Sprite Lamp" however, if possible, if there is some sort of math I can do myself to convert a lighting profile to a normal map, how might I go about doing that? Or convert multiple lighting profiles to one normal map, how would I do that?

I don't have $35 to shell out currently, so I'd like to generate the normal maps myself. If you don't know what Sprite Lamp is, check out this link: http://steamcommunity.com/sharedfiles/filedetails/?id=193335844


texts: Is Edge by Mobigames 3D or isometric 2D?

texts: I'm trying to make a similar to http://www.cultofmac.com/edge-for-iphone-controversy-rumbles-on-game-again-pulled-from-app-store/13115, but I'm not sure if it's real-time 3D or just really good 2D. Any thoughts?


texts: Simple 3D particle gravity in javascript?

texts:
I'm trying to do some simple gravity handling in my 3D environment (I'm using three.js). I've got some code, but it doesn't work. I'm hoping it's just a silly bug somewhere. Note: This is a cross-question from stack overflow since I've got no responses

function handleGravity() {
    for(var j = 0; j < spheres.length; j++) {

        for(var i = 0; i < spheres.length; i++) {

            var r1 = new Array( spheres[j].position.x, spheres[j].position.y, spheres[j].position.z);
            var r2 = new Array( spheres[i].position.x, spheres[i].position.y, spheres[i].position.z);
            var r12 = new Array(r2[0]-r1[0], r2[1]-r1[1], r2[2]-r1[2]);
            var r12UnitVector = new Array( r12[0]/Math.abs(r12[0]), r12[1]/Math.abs(r12[1]),r12[2]/Math.abs(r12[2]) );

            var m1 = masses[j];
            var m2 = masses[i];
            var r12Squared = r12[0]*r12[0] + r12[1]*r12[1] + r12[2]*r12[2];
            var a12 = new Array( -(gravConst*m2/r12Squared)*r12UnitVector[0], -(gravConst*m2/r12Squared)*r12UnitVector[1], -(gravConst*m2/r12Squared)*r12UnitVector[2]);

            velocities[j][0] += a12[0]*timePassed;
            velocities[j][1] += a12[1]*timePassed;
            velocities[j][2] += a12[2]*timePassed;
        }

    }
}

If you can see anything wrong with it, or give me any tips on using JavaScript to simulate many particles in a 3D environment most efficiently (I'm very new to physics + simulation), that would be awesome!


texts: Update animation based on distance traveled instead of elapsed time?

texts:
2D sprite Animation is supposed to be based on the elapsed time from the previous update so that it runs (and looks the same) no matter the speed of the machine/device it's running on.

The method that moves my game objects already takes into account the elapsed time.  The distance the object moves during updates is the elapsed time (delta) * the objects velocity.

Because the object's location changes based on the elapsed time, would it look (/run the same on all machines) passing the "distance delta" to my Animation update method instead of the delta time?  The distance delta would be a number of pixels.  Using the distance would ensure my frame animation lines up with how far the object has traveled.


texts:
I've been reading today about normal mapping. Up to now, the only normal mapping I encountered was with maps already in world space so I just extracted the info from the texture and transformed them with the normal matrix.

Now I wanted to try to use a normal map that is in tangent space, but I immediately became really confused.

What I've in my code up-to-now is

Vertex Shader

 ...
passedPosition = modelViewMatrix*vec4(vertexPosition,1.0);
 ...

Fragment Shader

 vec3 V = normalize(-passedPosition .xyz);   // Eye vector
 ...
 vec3 L_dir = passedPosition .xyz - lights[i].lightPosition.xyz;
 vec3 L = normalize(L_dir);
 ...

And then proceed with my lighting calculations.

All the tutorial I came across change all the light directions and the view vector into tangent space (in the vertex shader) and then extract the normal from the texture and keep going (in fragment).
My issue here is that I'd like to avoid to access all my lights informations in the vertex shader, so my questions are:

Does make sense to pass to the fragment shader the t,b,n vectors so that I transform the light directions there? Should I consider access all my lighting informations in vertex shader (I have an array of Light struct which has more than just the position) and then passed them on to the fragment shader? Is something I'd like to avoid, but if is much better I can think of it.
There is a way to perform normal mapping that is  more compatible with what I've now (snippets above posted).
Should I consider change my calculations from view space to world space? In that case, how can I perform normal mapping?

Thanks


texts:
I'm trying to create a little 2D-Zombie-Shoot game. I'm pretty much at the beginning of programming. At least, I can create a player that is moving with arrow keys and stuff. My question is: How do I spawn a Zombie on a button-press? I've already tried it, but with no good results. Here's the code:

//A variable, for the amount of zombies spawned
public int zombie = 0;

 public void tick() {
 //The rest of the code is irrelevant
 ...........

    if (mouse1.isPressed()) {
        zombie++;
    }

}

public void render() {
    //The rest of the code is irrelevant
    ...........

    //Player
    g.drawImage(playerImage, x, y, null);

    //Check how many zombies should be created
    if (zombie > 0) {
        g.drawImage(zombieImage, zX, zY, null);
    }
    ...........


texts:
I have decided that since my game world is mostly flat I don't need better shadows than geometric projections - at least for now.

The only problem is I don't even know how to do those properly - that is to produce a 4x4 matrix which would render shadows for my objects (that is, I guess, project them on a horizontal XZ plane).

I would like a light source at infinity (e.g., the sun at some point in the sky) and thus parallel projection.

My current code does something that looks almost right for small flying objects, but actually is a very rude approximation, as it doesn't project the objects onto the ground, but simply moves them there (I think). Also it always wrongly assumes the sun is always on the zenith (projecting straight down).

    Gdx.gl20.glEnable(GL10.GL_BLEND);
    Gdx.gl20.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

//shells

    shellTexture.bind();
    shader.begin();
    for (ShellState state : shellStates.values()) {
        transform.set(camera.combined);
        transform.mul(state.transform);

        shader.setUniformMatrix("u_worldView", transform);
        shader.setUniformi("u_texture", 0);

        shellMesh.render(shader, GL10.GL_TRIANGLES);
    }
    shader.end();

// shadows
    shader.begin();
    for (ShellState state : shellStates.values()) {
        transform.set(camera.combined);
        m4.set(state.transform);

        state.transform.getTranslation(v3);
        m4.translate(0, -v3.y + 0.5f, 0); // TODO HACK: + 0.5f is a hack to ensure the shadow appears above the ground; this is overall a hack as we are just moving the shell to the surface instead of projecting it on the surface!
        transform.mul(m4);

        shader.setUniformMatrix("u_worldView", transform);
        shader.setUniformi("u_texture", 0); // TODO: make shadow black somehow

        shellMesh.render(shader, GL10.GL_TRIANGLES);
    }
    shader.end();

    Gdx.gl.glDisable(GL10.GL_BLEND);

So my questions are:

a) What is the proper way to produce a Matrix4 to pass to openGL which would render the shadows for my objects?

b) I am supposed to use another fragment shader for the shadows which would paint them in semi-transparent grey, correct?

c) The limitation of this simplistic approach is that whenever there is some object on the ground (it is not flat) the shadows will not be drawn, correct?

d) Do I need to add something very small to the y (up) coordinate to avoid z-fighting with ground textures? Or is the fact they will be semi-transparent enough to resolve that problem?


texts: Instantiate the same gameobject multiple times at once

texts:
So i am trying to create code where by when I shoot, bullets will shoot out of my gun at the same time, from 3 different positions. If I do a singular instantiate, it works fine, like below:

   IEnumerator ShotgunCoolDown()
    {
        PistolGunEffect.SetActive(false);
        canShoot = true;
        yield return new WaitForSeconds(0.45f);
        GetComponent<AudioSource>().PlayOneShot(PistolGunSound);
        canShoot = false;
        StartCoroutine(COPlayOneShot("Fire"));
        RifleGunEffect.GetComponent<ParticleSystem>().Play();
        (Instantiate(PistolBullet, ShotgunPoint.transform.position, transform.root.rotation) as GameObject).GetComponent<BulletScript>().Activate();
        yield return new WaitForSeconds(0.25f);
    }

However if i add multiple instantiates with different positionings, it will spawn the bullet for a millisecond before disappearing:

     IEnumerator ShotgunCoolDown()
        {
            PistolGunEffect.SetActive(false);
            canShoot = true;
            yield return new WaitForSeconds(0.45f);
            GetComponent<AudioSource>().PlayOneShot(PistolGunSound);
            canShoot = false;
            StartCoroutine(COPlayOneShot("Fire"));
            RifleGunEffect.GetComponent<ParticleSystem>().Play();
            (Instantiate(PistolBullet, ShotgunPoint.transform.position, transform.root.rotation) as GameObject).GetComponent<BulletScript>().Activate();
            (Instantiate(PistolBullet, ShotgunPoint1.transform.position, transform.root.rotation) as GameObject).GetComponent<BulletScript>().Activate();
            (Instantiate(PistolBullet, ShotgunPoint2.transform.position, transform.root.rotation) as GameObject).GetComponent<BulletScript>().Activate();
yield return new WaitForSeconds(0.25f);
 }

Any ideas how to address this?


texts: BasicEffect and SkinnedEffect treating WorldViewProj differently?

texts:
I made a ModelBatch class that batches and draw rigged/unanimated and skinned/animated models. For now, BasicEffect is assigned to rigged models (XNA Model Processor) and SkinnedEffect is assigned to skinned models (Based on Microsoft's Skinned Model Sample). The problem occurs when setting the shaders parameters. In the RenderBatch() method, I wrote:

...
foreach (Effect effect in mesh.Effects)
{
    if (effect is BasicEffect) // if it's a rigged model.
    {
        effect.Parameters["WorldViewProj"].SetValue(modelInfo.world * viewProjection);
    }

    else // it's a skinned model.
    {
        effect.Parameters["WorldViewProj"].SetValue(viewProjection);
        effect.Parameters["Bones"].SetValue(modelInfo.boneTransforms);
    }
}
...

When running the game, the rigged model's position is locked to the camera position for the first few frames. Afterwards, everything works perfectly (the rigged model position's is correct). The skinned model doesn't have that position displacement problem at runtime even if I only set the "WorldViewProj" parameter (so it's not because of the "Bones" parameter).

In order to work perfectly, I had to changed the rigged model part to:

    if (effect is BasicEffect) // if it's a rigged model.
    {
        BasicEffect basicEffect = effect as BasicEffect;

        basicEffect.World = modelInfo.world;
        basicEffect.View = this.camera.View;
        basicEffect.Projection = this.camera.Projection;
    }

This way, the rigged model is instantly placed at the right place, but I don't like it. Also, what is really stange is that if I do not set any view or projection for the rigged model, like this:

    if (effect is BasicEffect) // if it's a rigged model.
    {
        // do nothing.
    }

I will still see the rigged model locked to the camera's position. Anyone knows why setting "WorldViewProj" parameter of a SkinnedEffect works perfectly, but not for a BasicEffect?

I hope there's enough informations and thank you for answering!

* EDIT  ANSWERED **

I found the source of the problem. The scale and rotation of the rigged model were changed in the content processor options, so the model was modified at runtime. I changed those options back to their default values and set the rotation and scale in the code instead (Matrix.CreateScale and Matrix.CreateRotationX) and the model was at the right place. Hence, I think that changing the model world information at runtime created the displacement lag.


texts:
Using perlin noise to create a procedural island for a tile-based game. My map is stored in a 2d array, with each tile having a type (deep water, shallow water, beach, grass, forest, hill, mountain).

What would be the most efficient way to go through my map, after it's generated, and smooth out the edges of the terrain? Using a tileset, we run into issues with a 1x1 tile that sticks out by itself.


texts: Generating Formulas for glDrawElements with Tile Grids

texts:
glDrawElements can be used to save you from uploading a lot of vertices to the GPU.

Many 2D games use tiles, which are rendered in grids.

I have done some experimenting with the indices array. For a 3x3 grid of tiles, the indices for glDrawElements are as follows:

0 1 2 2 1 3 -|- 2 3 4 4 3 5 -|- 4 5 6 6 5 7
1 8 3 3 8 9 -|- 3 9 5 5 9 10 -|- 5 10 7 7 10 11
8 12 9 9 12 13 -|- 9 13 10 10 13 14 -|- 10 14 11 11 14 15

Already, calculating this is incredibly tedious and the grid is only a 3x3 one.

The proportion of vertices used with glDrawElements for power of two grids is (s + 1)^2 / s^2 * 6, where s is the grid width or height. Here are some grid sizes and savings:

10x10 : <0.2
30x20 : <0.18
50x50 : >0.17
100x100 : 0.17

How could one generate an array of indices in the correct order for a grid of tiles, of either width w and height h (or size s for power of two grids if that's more simple)?


texts: UDK : UTWeap_RocketLauncher gift CreateInventory: Any idea why this does not work properly?

texts:
I am giving the player an instanced class of UTWeap_RocketLauncher in an instance of UTGame.

PlayerPawn.CreateInventory(class'FobikRocketLauncher',false); // Does not work
PlayerPawn.CreateInventory(class'FobikLinkGun',false); // Works

Even if I give the original class (eg. UTWeap_RocketLauncher) it does not actually show up. However if I do a "GiveWeapons" cheat, I get it just fine. It also works if I had code it into the map. - But UTWeap_LinkGun works fine either way.

Any ideas? It shows the default ammo amount, and the icon on the HUD.


texts: Fatal error in Game Maker: variable not set before reading it

texts:
I have been following the tutorial videos on game maker, and I am at the part where he explains how to get the bullet under the character. I thought I did everything right. He then tested the game, and it worked. But when I played, and tried to shoot, this message appeared:

#

FATAL ERROR in
action number 1
of  Step Event0
for object obj_player:

Variable obj_player.layer_bullet(100002, -2147483648) not set before reading it.
 at gml_Object_obj_player_Step_0 (line 30) -        instance_create_layer(x, y, layer_bullet, obj_bullet);

#


texts: unable to map one object position to another object over network

texts:
objective: I have a player which instantiate by network manager class. I want to map/sync its position/rotation to another object which is also instantiate by my player object.

(what it i have tried)
Below code is attached to my network player which instantiating another object (mimic object)

         void Start() {
                if (isLocalPlayer)
                {
                    CmdInstantiate();
    }

         [Command]
            void CmdInstantiate()
            {
                // This [Command] code is run on the server!
                mimic = (GameObject)Instantiate(
                     mimicObject);
                // spawn the bullet on the clients
                NetworkServer.Spawn(mimic);
            }

void Update()
    {
        if (!isLocalPlayer) {

            return;
        }
        CmdMimicObjectPosSync();//updating position on server
    }

   [Command]
    void CmdMimicObjectPosSync()
    {//position sync method
        mimic.transform.position = this.transform.position;
        mimic.transform.GetChild(0).position = this.transform.GetChild(0).position;
        mimic.transform.GetChild(1).position = this.transform.GetChild(1).position;
        mimic.transform.GetChild(2).position = this.transform.GetChild(2).position;
    }

it is working fine on the player side but another player who has joined the network unable to see it although mimic object has instantiated but its value remains same (no change). Mimic object has attached network identity and network transform.


texts:
I making graphics viewer, and I want to use "arcball" to manipulate object.
I using OpenGL + CML ( for math ). My arcball don't want work, it is skewing not rotating :/ And I don't know why, I use formulas from http://www.csi.ucd.ie/staff/hcarr/home/teaching/comp4004/slides/05_arcball.pdf .

My code:
cml::vector3f u,v;

u[0] = 2.0 - prevX/(0.5f * width());
u[1] = 2.0 - prevY/(0.5f * height());
u[2] = sqrt(u[0]*u[0] + u[1]*u[1]);

v[0] = 2.0 - currentX/(0.5f * width());
v[1] = 2.0 - currentY/(0.5f * height());
v[2] = sqrt(v[0]*v[0] * v[1]*v[1]);

cml::quaternionf qu,qv,q;

qu[0] = 0;
qu[1] = u[0];
qu[2] = u[1];
qu[3] = u[2];

qv[0] = 0;
qv[1] = v[0];
qv[2] = v[1];
qv[3] = v[2];

q = qv * ( qu.inverse());

cml::matrix44f matrix;

matrix.identity();

cml::matrix_rotation_quaternion(matrix,q);

//Drawing

glLoadIdentity();
qlTranslate(0,0,-zoom);
qlMultMatrixf(matrix.data());


texts: Unity - Moving X amount of units to destination, RTS style movement

texts:
I have a reached a point now where I can select X amount of units, and move them to where I click. My problem is, they all try to get to the same point.

I use Unity's own Navmesh + agent.

I set destination like so:

public bool MoveToPoint(Vector3 point)
    {
        if (SamplePosition(point))
        {
            agent.SetDestination(point);
            return true;
        }

        return false;
    }

I tried a system where I send an event when ANY agent reaches the point, then all agents stop, but realised quickly that will never work well.

I've read the material I can find through Google but nothing really helps me get started.

If I have a List of units, all with an attached agent, how can I move these to a point while keeping some sort of logical formation, no matter how far apart they started?

It does not have to be very fancy, I just want them to stop bumping into each other and doing that weird "Spassing out" thing they do when they can't reach their destination cus they are in each others way.


texts: How do I interpret the dot product of non-normalized vectors?

texts:
I know that if you take the dot-product of two normalized vectors, you get the cosine of the angle between them.

But if I take the dot-product of two non-normalized vectors (or one normalized, one not), how can I interpret the resulting scalar?


texts: How do I make multiple instances of an object?

texts:
In a game I am working on, I am having an issue with making the player's ship shoot multiple bullets. The bullets have individual X and Y coordinates and velocity for X and Y. When I press "SPACE" to shoot the bullet, only one comes out, and when I release the space bar, the bullet disappears. I want to make multiple bullets without having to make an array since the amount of shots would be limited to the array size.

How do I make multiple instances of an object with data without using an array?


texts:
Google's new Go language is still in its infancy, and it has yet to find widespread real-world use or support.  Even so, it seems like a promising experiment, and I wonder if it could have a future in game development.  I haven't been able to find much game-specific discussion of Go elsewhere, and figured a CW discussion may be appropriate.

Some thoughts:

According to golang.org, Go programs "run nearly as quickly as comparable C or C++ code"--quick enough?
Is Go's garbage collection well suited for games?
How much mental re-tooling is necessary to create games in the land of concurrent goroutines?
Go is frequently called a "systems"-level language, with server software given as an example.  It's hard not to think of multiplayer game servers when hearing this.

Your thoughts?


texts: Which SceneGraph is optimal to begin with for small game programming?

texts:
I am a Java web application developer (mostly server side) since 7 years who recently got interested in game development (i dont know why, maybe i am bored). Today I was looking for frameworks. I read about a few scene graphs and took a look at jMonkeyEngine. It was recommended here and here.

My first goal was to create a simple plane and a sphere which could be moved around using the keyboard. Well, as I mentioned I am a web developer and never programmed anything else so I started with the tutorials of jMonkey. But I wasn't able to get them working. I took a look at the wiki but I noticed that the documentation seems to be very poor, at least compared to what I am used to. I then took a look at a few other scene graph's (also for C++) but they also seem to have an outdated, incomplete poor documentation.

Can someone recommend me a scene graph which is well documented with working samples? Or is there something like the "ultimate guide" to get into this topic? Do I first need to know how to develop my own scene graph to get it working or is it possible to just understand the abstract principles and use it from a higher point of view?

Somehow I have the feeling I need to understand the deep insides of a scene graph to use it well (like it's the case for ORM tools in web dev, you can't use them well if you don't understand databases)

I'm sorry if this question is too 'noobish', but I just want to get on my feet and do my first steps.


texts: How to use the actions of the actors in libgdx?

texts: I'd like to know if someone has already used Actions in the actors, and how to use them. I don't know how. I want to rotate an Actor.


texts:
I am setting up a grid of tiles (2d sprites) in Unity with this code:

public class Grid : MonoBehaviour {

public GameObject slot;
public int gridW = 9;
public int gridH = 9;

private GameObject [,] grid = new GameObject[9, 9];

void Awake(){

    for(int y=0; y<gridW; y++)
    {
        for(int x=0; x<gridH; x++)
        {
            GameObject gridSlot = (GameObject)Instantiate(slot, new Vector3(x, y, 0), Quaternion.identity);
            gridSlot.transform.parent = transform;
            grid[x,y]=gridSlot;
        }
    }

}

I then would like to have printed on the console the x,y coordinates of an individual tile when clicked on it. This is the script attached to the tile prefab:

public class Tile : MonoBehaviour {

void Start () {

}

void Update () {

    if(Input.GetMouseButtonDown(0))
        Debug.Log(transform.position.x + " " + transform.position.y);
}

Yet when I click on a tile I get printed the coordinates for ALL of the tiles on the grid. Why is this happening? Is there something very basic I am missing...?

Thanks!


texts:
When I got back to Google Admob Console I received this announcement:

"Beginning on 23 Jan 2018, Google Mobile Ads SDK versions older than 7.0.0 for Android and 7.0.0 for iOS will no longer be supported. Publishers with these older versions will not be able to serve ads in their apps(s). Please ensure that you have upgraded to the latest version of the Google Mobile Ads SDK."

I am concerned about whether the Unity game I released eight months ago will continue to serve Admob ads.

I think this pertains to many Unity developers. It seems that the Google Mobile Ads for Unity uses a different versioning system. Its current version is version v3.10.0.

So what is the latest version of Admob Unity Plugin that will be affected by this? Will we be affected at all?


texts: How would you implement and differentiate between input actions and input states?

texts:
Im currently trying to setup my game and Ive started to implement input. It works like this:

I have an Input class who notifies the InputMapper whenever some key is pressed (or released or whatever). This InputMapper gets the keys pressed and returns an Action or a State depending on the current InputContext (Action and State are enums) (I used this article to get idea of how it should work).

Action here represents one-time actions like Jump while State represents continuous things like move_right.

I now attach an InputListenerto the InputMapper, which gets the Action or State whenever pressed.

In the game I use an entity-component-system. I have a ControlComponent, which should have variables that dictate what an entity should do and a KeyBoardSystem, which should set these variables. ControlComponent is then used by things like WalkSystem or JumpSystem.

My question now is: How would you implement these States and Actions in an entity-component-system? I know that States could be represented by booleans in the ControlComponent, but Actions? They could be events, but the ControlComponent doesnt (shouldnt?) have any method or know about the systems that use it.

Any help is appreciated.


texts: Randomly instantiate avoiding overlapping in Unity 5

texts:
I'm starting a 2D game where I want all the letters A-Z displayed in a random position and, then, the player collects them all in the correct order.
I need to randomly instantiate the letters without overlapping. I use C#.


texts: game maker place_meeting multiple objects

texts:
I am working on a simple game that contains two objects the player and the ground, and I used place_meeting to make the player walk on the ground object and it works fine but when I try to add another object to make the player walk on it, it didn't work and the game freeze, here is my code:

// vertical collision
if place_meeting(x,y+vsp,ground1) or place_meeting(x,y+vsp,ground2)
{
while ((!place_meeting(x,y+sign(vsp),ground1 )) or (!place_meeting(x,y+sign(vsp),oground1=2 )))

 y+=sign(vsp);

    if (sign(vsp) ==1)
    {
    grounded = 1;
    }

    vsp =0;

 }
else
{
grounded = 0;
}
y+= vsp;


texts: Creating a toggle button in unity3d Scene vs Scripting

texts:
I am making my first GUI in unity, and I am not sure if should create the toggle buttons in the game scene by creating new UI elements or by scripting.

Creating them in the game scene gives me more options but I have trouble to manipulate the input.

Because of this I am scripting them in the monodeveloper but it seems more difficult to work the visual side (I am using a texture but can't get rid of the little box (that shows f the button is clicked or not).

How do you make your toggle buttons and how do you develop your GUI?

Any help appreciated.


texts: Why doesn't my pygame window close on MacOS?

texts:
I am trying to create a window and then close the window. Everything runs smoothly until I click the red X. When I click it, the window doesn't close and all that happens is that the colourful red beach ball thing shows up whenever I hover my mouse over the Pygame window and the window just does not respond.

It seems like the pygame.quit() or pygame.display.quit() functions do not work for some reason.

import pygame
pygame.init()
Window=pygame.display.set_mode((250, 250))
run=True
while run:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            run=False
pygame.quit()
pygame.display.quit()


texts:
Overview
The game is a multiplayer simple real time strategy housed in a Flash application.  Players run the Flash client, and are connected to a server written in another language (the language is irrelevant).  Players compete against one another in games of 2~8 players.
My aim is create some way for people to create an AI agent to play in the same realm against human players, or other AI agents.  Akin to the Broodwar AI competitions, but in a much simpler game.

The current model
has players logging in to the lobby. Games seeking players are listed in the lobby.  Once the game acquires the amount of players required to start (defined by the host at game room creation time), the players are then pushed into a game, and leave the lobby.  Games then run through to completion; players who disconnect are left stagnant until destroyed or they login again and are reconnected to the game.

In a perfect world
the flash client (Using an MVC type model) would be able to interface in some way with the users AI agent, handing data to the agent, and receiving commands from the agent.  In this way the user could observe the game in the flash client while in play, as well as choose games for the agent to participate in.  This model would be ideal for debugging purposes, as to not interrupt play on crash, and since commands can only be sent (with malformed commands being ignored, with an error callback) users could pick out major bugs quickly.

However
flash is a prissy little nitwit when it comes to communicating client side to client side.  The only realistic options I can see would be to create a second client interface in another language (say .Net) that would be used to interface the AI agent, the player would then login to the flash client and enter games/observe in the above mentioned manner.  OR the flash client would create a second socket pointed at the local host.  A suitable API would be created to manage the communication protocol (as a DLL or similair) that would handle all data values of the game, and sending commands.  This API would be extended by the users AI agent, and the player would login to the flash client and join/observe games.

The Big Question:
From experience or observations, what would be the most suitable model for this type of a system?  I have no qualms with either, but due to the long timeframe of implementing each system (I work alone) I'd rather start off on the right path, and end up with an easy to use model.  Any suggestions at all are very welcome!


texts:
I had to port a project from Unity to Unreal which relied mostly on baked lighting.

When I baked the light (StaticMeshActor set to Static), the 3D model in the map turned black.

Without bake (dynamic lighting):

After baking the light:


texts:
I have a randomly generated set of tiles, and I am trying to select neighboring x or y tiles to perform functions on them based on if they are a certain value of tile, like so:

var IsometricMap = new Object();

      IsometricMap.tiles = [
        // "images/dirt.png",
        "images/dirtHigh.png",      // 0
        "images/grass.png",         // 1
        "images/water.png",         // 2
        "images/waterBeachCornerEast.png",  // 3
        "images/waterBeachCornerNorth.png", // 4
        "images/waterBeachCornerSouth.png", // 5
        "images/waterBeachCornerWest.png",  // 6
        "images/waterBeachEast.png",    // 7
        "images/waterBeachNorth.png",   // 8
        "images/waterBeachSouth.png",   // 9
        "images/waterBeachWest.png"]

var blockcount = 10;

    let generate_row = _=> Array(blockcount).fill().map(_=>Math.floor(Math.random()*3));
     IsometricMap.map = Array(blockcount).fill().map(generate_row);

    console.log(IsometricMap.map);

    for(let x = 0; x < IsometricMap.map.length; x++){

        for(let y = 0; y < IsometricMap.map.length; y++){

            if ((IsometricMap.map[x-1][y]) == 2) {
            //IF THE TILE IS WATER, DO ALL THIS:

            alert("SUCCESSFULLY SELECTED THE " + IsometricMap.map[x-1][y] + " TILE");

            //DONE WITH WATER TILES
            }

        }

    }

So far this is not yielding any results, its as if it cant find the tile I am trying to specify. Is there something wrong with my scope here?


texts: How does game asset file encryption work?

texts:
How does file encryption in game assets work, for example the unreal engine has a .assest extension, or I also see a .dta extension in another game, are these .zip type packages which have a custom encryption algorithm set by the developer or how does it work?

Is it as simple as coming up with your own encrytion algorithm then extracting all the file such as in a .pk3 file?


texts: Stopping Actor tap/click event from propagating

texts:
I've been struggling with this for hours now and have read posts, docs and libgdx sources to better understand what's happening, but I still can't make any sense of this.

I want to accomplish something very simple: stopping a tap on an Actor from propagating through the stage.

The setup is as follows:

GameStage defines a gesture listener (for map panning and propagating taps in the map to the Player actor so it can move around)
Player has a child actor which can receive clicks

It is on that last child actor that I want to detect clicks, but then not have them propagate to any other actors or be handled by the stage. I define the click handler as follows:

// in child actor:
addListener(new ClickListener() {
   void clicked(...)
});

Nothing surprising here.

The problem is: since the actor is physically located outside the Player parent actor, any clicks on it get picked up by the stage's map gesture handler which then propagates these taps back to the player which makes it move around. I don't want that; this click listener is supposed to handle and swallow the event.

However, none of the following calls I make inside clicked actually cancel the event:

event.handle()
event.stop()
event.cancel()

The only way I could make the event stop from propagating is to use Stage#cancelTouchFocus. However, this has the side effect of dispatching a touchUp event on the stage (why?), which ends up in my gesture listener and gets interpreted as a longPress! Probably because it is paired up with the wrong touchDown...

What am I missing? It can't be that complicated to stop an event from propagating given all the supposed options?

UPDATE:
I believe the problem lies in Stage:
https://github.com/libgdx/libgdx/blob/2bd1557bc293cb8c2348374771aad832befbe26f/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java#L348

It walks over all the listeners that have touch focus, and let's them handle the event. However, it does not break out of the loop as soon as a listener has handled it, thus propagating it further. Is that just a bug?


texts: What exactly is a lobby in technical terms?

texts:
I've searched afar in google but it seems to have different technical meaning for different games and game engines.

what I know is a lobby is a space where people come together and then when certain requirements are met they start playing.

now that is just the theory, I want to know the functional design or architecture so this will be a few small questions:

Where is the lobby hosted? (A dedicated lobby server or client machine?)
Is there's a host who owns the lobby?
Do you need multiple free running servers to serve the lobbies?
Ex. lobby A is ready,server 1 is free so assign it server1 , lobby B becomes ready search a free server for it and assign it to it.

Am I even understanding the concept of lobby correctly?


texts: How do I change a value gradually over time?

texts:
I'm using Unity3D 5-point-something, and I'm planning on making a game where the player travels through a hot, dry desert, and so the heat causes the player's energy to deplete.  The object of the game is to reach a certain point before the player's stamina runs out.

What I was planning on doing is having different landmarks in the game world that the player can visit, and these will help replenish their Health or Stamina.


texts:
The SaveSystem class :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public static class SaveSystem
{
    public static void SavePlayer(Player player)
    {
        BinaryFormatter formatter = new BinaryFormatter();

        string path = Application.persistentDataPath + "/player.bin";
        FileStream stream = new FileStream(path, FileMode.Create);

        PlayerData data = new PlayerData(player);

        formatter.Serialize(stream, data);
        stream.Close();
    }

    public static PlayerData LoadPlayer()
    {
        string path = Application.persistentDataPath + "/player.bin";
        if(File.Exists(path))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(path, FileMode.Open);

            PlayerData data = formatter.Deserialize(stream) as PlayerData;
            stream.Close();

            return data;
        }
        else
        {
            Debug.LogError("Save file not found in " + path);

            return null;
        }
    }
}

The Player class :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public void SavePlayer()
    {
        SaveSystem.SavePlayer(this);
    }

    public void LoadPlayer()
    {
        PlayerData data = SaveSystem.LoadPlayer();

        Vector3 position;
        position.x = data.position[0];
        position.y = data.position[1];
        position.z = data.position[2];
        transform.position = position;

        Quaternion rotation;
        rotation.x = data.rotation[0];
        rotation.y = data.rotation[1];
        rotation.z = data.rotation[2];
        rotation.w = data.rotation[3];
        transform.rotation = rotation;
    }
}

The PlayerData :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class PlayerData
{
    public float[] position;
    public float[] rotation;

    public PlayerData(Player player)
    {
        position = new float[3];
        position[0] = player.transform.position.x;
        position[1] = player.transform.position.y;
        position[2] = player.transform.position.z;

        rotation = new float[4];
        rotation[0] = player.transform.rotation.x;
        rotation[1] = player.transform.rotation.y;
        rotation[2] = player.transform.rotation.z;
        rotation[3] = player.transform.rotation.w;
    }
}

And using the Saving in a script at some point :
IEnumerator SaveAfterSomeTime()
    {
        yield return new WaitForSeconds(15f);

        player.GetComponent<Player>().SavePlayer();
        StartCoroutine(fadeInOutSaveGame.OverAllTime(5f));
    }

And loading back from the main menu button click event :
public void ClickLoadGameDialog(string ButtonType)
        {
            if (ButtonType == "Yes")
            {
                loading = true;
                newGameDialog.SetActive(false);
                StartCoroutine(sceneFader.FadeAndLoadScene(SceneFader.FadeDirection.In, _newGameButtonLevel));
            }

            if (ButtonType == "No")
            {
                GoBackToMainMenu();
            }
        }

When I'm saving I see it's creating a bin file on the hard disk.
When loading I see it's getting other values of the position of the player.
But still it's loading and the player is in the default position and rotation and not when where it was when saving.
The script Player is attached to my Player for testing I just added a 3D Cube and attached the script Player to the Cube but same thing.  I changed the cube position saved but when loading the cube is starting from it's original position and not from where it was when saving.
Something wrong with the SavePlayer method ? Or when loading ?


texts: How can I tell a fragment shader to not write a particular pixel?

texts:
In a WebGL I'd like to send a screen space quad through that gets processed by a fragment shader, but have the fragment shader only write out a pixel under certain conditions (say... that it was within a circle, or that the pixel belonged to the positive side of a halfspace defined by a curve equation or something).

Is it possible within a fragment shader to say "don't write a pixel"?

I know this could be accomplished using various other methods like alpha blending, rendering this first and having it put the background color where it doesn't want to draw a pixel, or maybe doing some trick with the depth or stencil buffers.  I also know i could create a bunch of geometry to match what it is that I want to render.

Is there a way though to make the fragment shader choose not to write a pixel at all?


texts: Application toolkits like QT versus traditional game/multimedia libraries like SFML

texts:
I currently intend to use SFML for my next game project.  I'll need a substantial GUI though (RPG/strategy-type) so I'll either have to implement my own or try to find an appropriate third party library, which seem to boil down to CEGUI, libRocket, and GWEN.  At the same time, I do not anticipate doing that many advanced graphical effects.  My game will be 2D and primarily sprite-based with some sprite animations.

I've recently discovered that QT applications can have their appearance styled so that they don't have to look like plain OS apps.  Given that, I am beginning to consider QT a valid alternative to SFML.  I wouldn't have to implement the GUI functionality I'd need, and I may not be taking advantage of SFML's lower-level access anyway.  The only drawbacks I can think of immediately are the learning curve for QT and figuring out how to fit game logic inside such a framework after getting used to the input/update/render loop of traditional game libraries.

When would an application toolkit like QT be more appropriate for a game than a traditional game or multimedia library like SFML?


texts: How do I reference a particular UI Image or Sprite in my assets folder?

texts:
I have an Item class, and I want to associate an Image class with it. How do I get a reference to the intended Image, from my assets folder, in order to provide it as a reference to a constructor for Item?

Here is my code:

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ItemData : MonoBehaviour
{
    private List<Item> items;

    void Start()
    {
        items = new List<Item>();

        Item sword = new Item(0, "Sword", /*What goes here?*/);
        items.Add(sword);

        Item hammer = new Item(0, "Hammer", /*What goes here?*/);
        items.Add(hammer);
    }
}

public class Item
{
    public int itemID;
    public string itemName;
    public Image itemImage;

    public Item(int newItemID, string newItemName, Image newItemImage)
    {
        itemID = newItemID;
        itemName = newItemName;
        itemImage = newItemImage;
    }
}


texts: Unity3D - Smooth rotation for seek steering behavior

texts:
I am trying to implement Reynolds' seek steering behaviour, but I am having problems on the rotation part. This is what I have:

void FixedUpdate()
{
// get position of current waypoint
        Vector3 targetPos = new Vector3(path[currentWaypoint].x, transform.position.y, path[currentWaypoint].z);

        // velocity vector towards target
        Vector3 desiredVelocity = targetPos - transform.position;

        // calculate the steerforce required for the desired velocity based on current velocity
        Vector3 steerForce = desiredVelocity - currentVelocity;
        steerForce = new Vector3(steerForce.x, 0, steerForce.z);
        steerForce = Vector3.ClampMagnitude(steerForce, maxSteer);

        // create a move vector to be added to agent's current position
        // Then normalize it so it can be scaled according to the agent's max speed
        Vector3 moveVector = steerForce.normalized * moveSpeed * Time.fixedDeltaTime;
        transform.Translate(moveVector);
}

How would I do it so my agent will be rotated smoothly based only on the code above? I tried rotating based on the current velocity, but the agents is rapidly rotated in one frame towards the target waypoint. I am not working with rigidbodies.

Am I doing something wrong? What am I missing?

Thanks,
Jack


texts: Finding when shapes overlap and lines intersect but exclude points/edges

texts:
I've been looking for a c# algorithm to help determine if shapes and lines intersect but want to exclude boundary overlaps. Here's an example:

My true problem is finding if polygons intersect but exclude boundary overlaps. I broke down the problem to look at the individual lines of that polygon and check each line segment from the shape1 against each line segment from shape2.

A: Is this an efficient/correct way to do the checking?

B: How do I ignore when they are on the boundary as illustrated above?

Here's some code I found here - I've been testing for line segments but it fails on fig 2, when the end point of the 2nd line segment finishes on the end point of the 1st segment.

private bool DoesLineIntersect(Vector2 start1, Vector2 end1, Vector2 start2, Vector2 end2)
{
    float denom = ((end1.x - start1.x) * (end2.y - start2.y)) - ((end1.y - start1.y) * (end2.x - start2.x));

    //  AB & CD are parallel
    if (denom == 0)
        return false;

    float numer = ((start1.y - start2.y) * (end2.x - start2.x)) - ((start1.x - start2.x) * (end2.y - start2.y));

    float r = numer / denom;

    float numer2 = ((start1.y - start2.y) * (end1.x - start1.x)) - ((start1.x - start2.x) * (end1.y - start1.y));

    float s = numer2 / denom;

    if ((r < 0 || r > 1) || (s < 0 || s > 1))
        return false;

    return true;
}


texts: How can I create a lighting engine for BSP geometry in OpenGL?

texts:
I am trying to figure out the best way to go about creating a lighting engine for an old game format with BSP based geometry. I have all the relevant information about the light, R/G/B/brightness/radius all that sort. I want to go for per pixel lighting. How can I go about doing this? I have seen tutorials for simple examples like one light revolving around an object but wondered if the same concept applies when having numerous lights illuminating a level.

Also, the BSP geometry does not use lightmaps so that is out of the question.

Also, I am interested in using normal/specular and diffuse maps I generate with Crazybump if that helps influence your advice.


texts: Pathfinding to find the route to nearest resource in 2D grid

texts:
The setting is a game in a 2D gridlike labyrinth/maze. I'm looking at pathfinding algorithms such as A* and Dijkstra.
I can't figure out how to have my game characters find the nearest resources. All the info I found regarding pathfinding deal with reaching a goal node. However, there are many potential goals so how do I find the path to the nearest resource? At first I thought running pathfinding for each potential goal, but that seems too time consuming (for 4-5 characters with 50 resource nodes). The characters are all competing for the resources so getting there fast is priority.

I understand that Dijkstra solves the distances to all nodes in the grid- so I think the solution lies there, but still the examples I found still require a goal node. So I'm confused how to distill paths from the node calculation.

Can someone explain how to handle pathfinding where finding the nearest goalnode is part of the problem?

Edit:

The solution I ended up using is this:
As mentioned by ali ahmadi in the comments below, it proved quick enough to do a distance search on the potential goals and then do a A* pathfinding to that goal.

It does not answer the question exactly, but the AI players mimic the human player behaviour close enough which is fine for my game.
I might get back to this when I need the AI to be more brutal...


texts: How would you define this mechanic in narrative based games?

texts:
I'm a researching a certain game mechanic that seems very commonplace in modern narrative-based games. The mechanic is defined (by me) as a user action that the player can take while in a dialogue or a cutscene, which affects the course of the narrative (and sometimes has a long lasting impact on the game progression in general).

The interaction can be of several types - press a button\click a character\hit a sequence of keys\button mashing.

Here's an example from Game of Thrones

https://www.youtube.com/watch?v=ykq213pPD6Q&feature=youtu.be&t=181

In Mass Effect it is referred to as an interrupt

https://www.youtube.com/watch?v=9TgTLJXoD_o

Here's one from King's Quest:

https://www.youtube.com/watch?v=KhOkqn6qE2g

I'm looking for more info on this type of mechanic. Specifically -

Is there an accepted name for it?
What other games have this mechanic, and use it in an interesting way? (I would appreciate links to videos demonstrating it)
What types of interactions (such as the ones I've described) have you seen implemented in this mechanic?

Thanks :)

(BTW if you think this game-design related question is more suitable for StackExchange's Arqade do let me know and I'll ask to move it there)


texts:
So, this is the code I have right now:

if (keysPressed.Count() > 0)
        {
            switch (keysPressed[0])
            {
                case Keys.W:
                    {
                        characterStats.Velocity.Y += velocityCahge*(-1);
                        break;
                    }
            }
        }

        for (int i = 0; i < 2; i++)
        {
            if (Rectangle.Intersects(anotherRectangle))
            {
                characterStats.Velocity.X *= -1;
                characterStats.Velocity.Y *= -1;
            }
        }

       characterStats.position.X += Velocity.X;
       characterStats.position.Y += Velocity.Y;

The problem with this, is that sometimes, after collision, when pressing button to go in opposite direction from the collided sprite, the character starts going inside the sprite, in the opposite direction to where the button should move him. I know, that it happens cause of that *= -1, but how do i prevent that?


texts:
I'm writing a game in Java for Android using LibGDX, and I connected my phone so I can test it on it.

I know that LibGDX's render system works different than regular Java systems since the 0,0 coordinate is in the lower-left corner, while in java it usually is in the upper-left corner.

But now I use the touchDown method out of the GestureListener class, it's like the regular Java rendering system: when I obviously tap in the left down corner of my screen, I debug-messaged the coordinates and it says it's Y-coordinate is 475, while I render the object at 0,0.

Is there a way to fix this easily?


texts:
I'm trying to create a basic post-processing shader, like I did many times before but somehow today it's just not working, I guess it's something basic that I missed.

Anyway my setup:

I have 3 render targets rts[0], rts1, and rts[2], I draw a simple model in each one of them. I then draw the render targets to the screen using the following code:

GraphicsDevice.SetRenderTarget(null);
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null);

spriteBatch.Draw(rts[0], new Rectangle(0, 0, GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2), Color.White);
spriteBatch.Draw(rts[1], new Rectangle(GraphicsDevice.Viewport.Width / 2, 0, GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2), Color.White);
spriteBatch.Draw(rts[2], new Rectangle(0, GraphicsDevice.Viewport.Height / 2, GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2), Color.White);

spriteBatch.End();

This gives me the following picture:

Which is exactly what I expect it to be :)

Now I feed these 3 render targets as textures to my shader like this: (shaderTexture is a black 1x1 texture)

cutAwayEffect.Parameters["lowTexture"].SetValue(rts[0]);
cutAwayEffect.Parameters["highTexture"].SetValue(rts[1]);
cutAwayEffect.Parameters["cutTexture"].SetValue(rts[2]);

spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, null, null, null, cutAwayEffect);

spriteBatch.Draw(shaderTexture, new Rectangle(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2, GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2), Color.White);

spriteBatch.End();

And the shader:

texture lowTexture;
sampler lowSampler = sampler_state
{
    Texture = (lowTexture);
};

texture highTexture;
sampler highSampler = sampler_state
{
    Texture = (highTexture);
};

texture cutTexture;
sampler cutSampler = sampler_state
{
    Texture = (cutTexture);
};

float4 PixelShaderFunction(float2 texCoord: TEXCOORD0) : COLOR0
{
    float4 baseColour = tex2D(lowSampler, texCoord).rgba;
    float4 highColour = tex2D(highSampler, texCoord).rgba;
    float4 cutColour = tex2D(cutSampler, texCoord).rgba;
    float4 finalColour = baseColour + highColour * cutColour;

    return finalColour;
}

technique CutAway
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

Now I would expect to see a combination of all 3 render targets in the bottom right corner, however I don't see any data from baseColour. When I change finalColour to just baseColour I only see black, same goes for just highColour and just cutColour. Even finalColour = highColourcutColour only gives me black while finalColour = baseColour + highColourcutColour; does give me something.

The shader does seem to be working, changing final Colour to float4(1,0,1,1) gives me the expected pink square. There seems to be a problem reading the data from the textures, but I've got no clue why.


texts:
Im making a Breakout clone game and im stuck with deleting objects after they are hit. There are 3 rows. Each contains 12 blocks.

I'm trying to delete a pair in the array of pairs. The array contains coordinates of an object (texture) displayed, and if that object is hit with a ball I want to delete it and then my ball changes direction.

for each(pair<int, int> par in koordinateBlokova) {

    if (provjeraKolizijeBloka(par.first, par.second, rectLoptica) == true) {
        lopticaTrenutniY = -lopticaTrenutniY;

    }
}

Array and SDL_Rects are defined like:

pair<int, int> koordinateBlokova[36];
SDL_Rect rectBlock01;
SDL_Rect rectBlock02;
SDL_Rect rectBlock03;

Their definition is:

for (int j = 0; j < brojBlokovaRed; j++) {

    rectBlock01 = initRectBlock(j*sirinaBloka + j*razmakRedova, gornjiOdstoj, sirinaBloka, visinaBloka);
    rectBlock02 = initRectBlock(j*sirinaBloka + j*razmakRedova, gornjiOdstoj + visinaBloka + razmakStupaca, sirinaBloka, visinaBloka);
    rectBlock03 = initRectBlock(j*sirinaBloka + j*razmakRedova, gornjiOdstoj + 2 * visinaBloka + 2 * razmakStupaca, sirinaBloka, visinaBloka);

    SDL_RenderCopy(renderer, block01, NULL, &rectBlock01);
    SDL_SetRenderTarget(renderer, block01);
    koordinateBlokova[j] = make_pair(rectBlock01.x, rectBlock01.y);

    if ((j + 1) % 3 == 0) { // if its 3rd block, make it a impenetrable (not implemented yet, just drawn)
        SDL_RenderCopy(renderer, blockNeprobojni, NULL, &rectBlock02);
        SDL_SetRenderTarget(renderer, blockNeprobojni);
        koordinateBlokova[j+12] = make_pair(rectBlock02.x, rectBlock02.y);
    }
    else {
        SDL_RenderCopy(renderer, block02, NULL, &rectBlock02);
        SDL_SetRenderTarget(renderer, block02);
        koordinateBlokova[j+12] = make_pair(rectBlock02.x, rectBlock02.y);
    }

    SDL_RenderCopy(renderer, block01, NULL, &rectBlock03);
    SDL_SetRenderTarget(renderer, block01);
    koordinateBlokova[j+24] = make_pair(rectBlock03.x, rectBlock03.y);
}
SDL_SetRenderTarget(renderer, NULL);
SDL_RenderPresent(renderer);

To make it easier to understand:

brojBlokovaRed = number of blocks in a row
sirinaBloka= block width
visinaBloka= block height
razmakRedova = space between rows
razmakStupaca = space between columns
gornjiOdstoj = space from top of the screen to first row of blocks

My question is how to delete that current pair from array?


texts: Events and objects being skipped in GameMaker

texts:
Update: Turns out it's not an issue with this code (or at least not entirely). Somehow the objects I use for keylogging and player automation (basic ai that plays the game) are being 'skipped' or not loaded about half the time. These are invisible objects in a room that have basic effects such are simulating button presses, or logging them.

I don't know how to better explain this problem without putting up all my code, so unless someone has heard of this issue I guess I'll be banging my head against the desk for a bit
/Update

I've been continuing work on modifying Spelunky, but I've run into a pretty major issue with GameMaker, which I hope is me just doing something wrong.

I have the code below, which is supposed to write log files named sequentially. It's placed in a End Room event such that when a player finishes a level, it'll write all their keypress's to file. The problem is that it randomly skips files, and when it reaches about 30 logs it stops creating any new files.

var file_name;
file_count = 4;
file_name = file_find_first("logs/*.txt", 0);
while (file_name != "") {
    file_count += 1;
    file_name = file_find_next();
}
file_find_close();

file = file_text_open_write("logs/log" + string(file_count) + ".txt");
for(i = 0; i < ds_list_size(keyCodes); i += 1)
{

    file_text_write_string(file, string(ds_list_find_value(keyCodes, i)));
    file_text_write_string(file, " ");
    file_text_write_string(file, string(ds_list_find_value(keyTimes, i)));
    file_text_writeln(file);

}
file_text_close(file);

My best guess is that the first counting loop is taking too long and the whole thing is getting dropped?

Also, if anyone can tell me of a better way to have sequentially numbered log files that would also be great. Log files have to continue counting over multiple start/stops of the game.