title: Restricting my horizontal slash attack

text:
# Question
Title: Restricting my horizontal slash attack
I've been working on making this slash attack for my character in the unity engine. The whole point to this script is to put the damage range in sync with the slashing animation. The slash is completely horizontal and is scripted out make enemies bounce back. I have most of that but what I really need to restrict it on x axis. If I haven't explained it enough let me give you an example of what its doing. When an enemies in front of me but above the area my swing attack shouldn't be able to reach. I use my swing attack and it still does damage anyways. what I need is a way is restrict my hit detection range between two angles rolling around the x axis. I'm sorry if I didn't explain this so well just tell me if I need to make something more clear.

this is the code I've come up with what I've got it doings is it applies damage it can tell if an enemy is in front of it (uses the dot product for that) it can even knock said enemy backwards

```
void Knockback(){

     Vector3 grenadeOrigin = transform.position; // I'm building this controller using explode for knock back
// and this stuff was based off of a grenade script
     Collider[] colliders = Physics.OverlapSphere (grenadeOrigin, radius);
     foreach (Collider hit in colliders){
         Rigidbody rb = hit.GetComponent<Rigidbody>();
         if (rb){
             Vector3 dir = (rb.transform.position - transform.position).normalized;
             float direction = Vector3.Dot(dir, transform.forward);
             Debug.Log(direction);
             if (direction >0.1){// this is where i tell if something is in front of me
                 rb.AddExplosionForce(power, grenadeOrigin, radius, 0);
                 //This is where we apply force to our enemy and various other rigid bodies
                 hit.gameObject.SendMessage("Damager", Damage, SendMessageOptions.DontRequireReceiver);
                 //This is where we apply damage to the enemy
             }
         }
     }
 }

```

# Answer
My solution to this problem would be to simply use OnColliderEnter:

```
private void OnColliderEnter(Collision collision)
{
    collision.rigidbody.AddExplosionForce(power, transform.position, radius, 0);
    collision.gameObject.SendMessage("Damager", Damage, SendMessageOptions.DontRequireReceiver);
}

```

This problem solution assumes that the slash execution is accomplished with an animated GameObject.

And also I'd advise you to access MonoBehaviours using GetComponent because of better performance and readability:

```
collision.gameObject.GetComponent<YourDamageScript>().Damager(damage);

```
> 0 votes

---
Tags: unity, c#, game-mechanics, platformer
---


# Question
Title: Using Java on mobile, should I avoid object construction to reduce GC overhead?
I new to both Java and game development and working on my first LibGDX game targeting mobile systems.

How problematic is the garbage collector in a mobile environment? Should I try to reuse as many class instances as possible (e.g. with the object pool pattern), or only do it for the classes that I use most (like projectiles)?

How what instantiation rate warrants this optimisation? Or is the compiler “sufficiently smart” to effectively nullify this problem?

# Answer
> 2 votes
A class is a chunk of code that can be reused as an object. An object is a single instance of something that can have certain properties (e.g. an integer representing a characters intelligence or money amount). Now that we have that settled...

Going light on object creation and heavy on object reuse is generally better. It uses significantly less RAM to stuff your 50 objects into an array and spit them out and recycle them when needed than it does to create a new instance of said object. Every single object uses RAM (albeit, usually small chunks, but Android devices dont have much to begin with) and the more seperate instances you have the more lag appears.

OpenGL based game engines (libGdx, anyone?) are generally pretty good on memory management, but abuse of object creation will still trigger the garbage collector. If you are using the Android Canvas class with bitmaps to make your game, you have to be extremely careful on how you use available memory.

Your typical song can be 20 mb. Some of the lower end phones have 50 mb of memory available to each app. Creating 50 instances of a song will cause an out of memory exception(OOE). Creating 50 instances of a object with a 1 mb image file will also cause this exception.

I suggest that you check out the "For Dummies" series of books. This is not an insult, as some would take it if I left it at that, but these books are generally very descriptive and you will have the basics of Java down in no time.

1.) Java for Dummies

2.)Java Game Programming for Dummies

3.) Android Application Development for Dummies

4.) Android Game Programming for Dummies

5.) Beginning Android Games

After you have read these books (in the order given if you have any hope of understanding more advanced concepts) you are ready to either make your own game from nothing or to use a game engine. After reading these I believe you will be better suited for learning libGdx game development since the last book essentially shows you how it operates under the hood. After that read these tutorials and your good to go!

---
Tags: java, performance, optimization, mobile
---


title: How to fetch unit coordinates for AI?

text:
# Question
Title: How to fetch unit coordinates for AI?
I have been designing a simple turn based Civ-like game over the last two days with libGDX to test myself. I have a units class that can be extended to make unit types and I have my game board set up. Everything is almost done... except for the AI, specifically the unit AI. I want to collect all active units into two seperate arrays (the libGDX array), one for the human player and one for the AI units. I will not be using diplomacy for the sake of simplicity.

I first tried `Array<Unit> playerUnits = new Array<Units>();` and calling the `playerUnits.get(index)` method to return the unit. My thought process seems to not be logical, though, as I found there was no way to get the `x` and `y` coordinates of units that do not yet exist (all units have to be built in factories in game). Next, I tried to store `x` and `y` coords in an XYCoords method, however there was no built in way to add units to the array later.

I have my pathfinder implemented (with a few minor bugs that cause units to flicker once moved) and now need to simply add the reaction to units. I have no idea how to do this and as you have probably guessed by now I have never had to implement a more complex AI than one that follows the player mindlessly. Has anyone had a similar problem that could somehow help me?

# Answer
I think problem is that you are using the `size` variable instead of the `current count` of the items that the array contains, in your for-loop. Example for-loop you should use: `for(int i = 0 ; i < count ; i++) playerUnits.get(i).doSomething();`. When you create an array, its default `size` is 16, even though it contains 0 items. As seen from the Array source code. The default constructor is `public Array() {true, 16);}`. Where `16` is the `size`.

You can use a different syntax for your for-loop like this: `for(Unit u : playerUnits) {u.doSomething();}`, which does the same thing as the first for-loop, but doesn't use a `count` variable, as I don't think that the `Array` class has a `count` variable. The second for-loop is called a `foreach` statement.
> 1 votes

---
Tags: java, libgdx, ai
---


# Question
Title: How to put the “camera” inside a cube in OpenGL
I'm really new to OpenGL and can't seem to figure out how to put the "camera" inside the cube I've created so that I can move in an FPS-like style. I tried to use gluLookAt and gluPerspective but I'm clearly missing some steps. What should I do before gluLookAt? Here's the code written so far:

```
    int rotate_Y; //used to rotate the cube about the Y-axis
    int rotate_X; //used to rotate the cube about the X-axis

//the display function draws the scene and redraws it
void display(){

    //clear the screen and the z-buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glLoadIdentity(); //resets the transformations

    glRotatef(rotate_X, 1.0, 0.0, 0.0);
    glRotatef(rotate_Y, 0.0, 1.0, 0.0);

    //Front Face of the cube - vertex definition
    glBegin(GL_POLYGON);
    glColor3f(0.0, 1.0, 0.0);
    glVertex3f(-0.5f, -0.5f, -0.5f);
    glVertex3f(-0.5f, 0.5f, -0.5f);
    glVertex3f(0.5f, 0.5f, -0.5f);
    glVertex3f(0.5f, -0.5f, -0.5f);
    glEnd();

    //Back Face of the cube - vertex definition
    glBegin(GL_POLYGON);
    glColor3f(1.0, 0.0, 0.0);
    glVertex3f(-0.5f, -0.5f, 0.5f);
    glVertex3f(-0.5f, 0.5f, 0.5f);
    glVertex3f(0.5f, 0.5f, 0.5f);
    glVertex3f(0.5f, -0.5f, 0.5f);
    glEnd();

    //Right Face of the cube - vertex definition
    glBegin(GL_POLYGON);
    glColor3f(1.0, 0.0, 1.0);
    glVertex3f(0.5f, -0.5f, 0.5f);
    glVertex3f(0.5f, 0.5f, 0.5f);
    glVertex3f(0.5f, 0.5f, -0.5f);
    glVertex3f(0.5f, -0.5f, -0.5f);
    glEnd();

    //Left Face of the cube - vertex definition
    glBegin(GL_POLYGON);
    glColor3f(0.7, 0.7, 0.0);
    glVertex3f(-0.5f, -0.5f, -0.5f);
    glVertex3f(-0.5f, 0.5f, -0.5f);
    glVertex3f(-0.5f, 0.5f, 0.5f);
    glVertex3f(-0.5f, -0.5f, 0.5f);
    glEnd();

    //Upper Face of the cube - vertex definition
    glBegin(GL_POLYGON);
    glColor3f(0.7, 0.7, 0.3);
    glVertex3f(-0.5f, 0.5f, 0.5f);
    glVertex3f(-0.5f, 0.5f, -0.5f);
    glVertex3f(0.5f, 0.5f, -0.5f);
    glVertex3f(0.5f, 0.5f, 0.5f);
    glEnd();

    //Bottom Face of the cube - vertex definition
    glBegin(GL_POLYGON);
    glColor3f(0.2, 0.2, 0.8);
    glVertex3f(-0.5f, -0.5f, -0.5f);
    glVertex3f(-0.5f, -0.5f, 0.5f);
    glVertex3f(0.5f, -0.5f, 0.5f);
    glVertex3f(0.5f, -0.5f, -0.5f);
    glEnd();

    glFlush();
    glutSwapBuffers(); //send image to the screen
}

int main(int argc, char*argv[]){

    //initialize GLUT
    glutInit(&argc, argv);

    //request double buffering, RGB colors window and a z-buffer
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);

    //create a window
    glutInitWindowSize(600, 600);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("Space");

    //enable depth
    glEnable(GL_DEPTH_TEST);

    //callback functions
    glutDisplayFunc(display); //display - redraws the scene
    glutSpecialFunc(specialKeys); //special - allows interaction with specialkeys

    //pass control to GLUT for events
    glutMainLoop();

    return 0; //this line is never reached
}

```

Feel free to ask more about what I'm trying to achieve if I wasn't clear enough. Thanks for your help.

# Answer
> 1 votes
The reason for you getting a black screen when you put the camera inside the cube is most likely back face culling.

Try calling:

```
glDisable(GL_CULL_FACE);

```

In the beginning of your display function or in main (after enabling depth test) to disable back face culling.

If that is helpful you can either change the winding order of your polygons or change what is considered a "back face" (using glCullFace(GL\_FRONT)) since you probably will want to have back face culling enabled for performance reasons.

---
Tags: opengl, c++, camera, glut
---


# Question
Title: XNA: How to capture precise time of button press?
I'm guessing the default XNA model encourages checking for button presses in Update(). However, I am developing a game-like application for research and need to measure reaction times as quickly as possible. If I only check button presses in Update(), this constrains me to the refresh rate of the application. For example, if Update() runs 60 times per second, button capture times could be off by up to 16.6ms (1/60) if they happen soon after the thread goes to sleep. Is there another way to design my application to catch button presses as soon as possible?

Should I run a separate thread that polls the game controller and runs faster than the regular application's 60 Hz, say 120 Hz?

Or should I run a thread that gets a hardware interrupt when a button is pressed and store the time?

Other ideas?

(I know this sounds excessive when we are talking about button pressing and 20ms or less, but there are a number of scientific applications out there that advertise millisecond level timing precision. I am just wondering if I might be able to get something reasonably close with XNA.)

# Answer
Rather than polling for events, where the only option for higher precision is to poll faster, you could try listening for the events directly.

You can attach an event listener to the windows event queue like so:

```
// Define a message filter which all messages will pass through
private class Filter : IMessageFilter
{
    public bool PreFilterMessage(ref Message m)
    {
        //Do your stuff here!
        //e.g. note down the exact system time.
        Stuff(ref m);

        //Returning false allows the message to continue to the next filter or control.
        return false;
    }
}

// Do this somewhere to begin listening
void AttachMessageListener()
{
    Application.AddMessageFilter(new Filter());
}

```

This gets you a stream of Message structures to handle. If you're trying to read a specific keyboard key you could do something like this:

```
void Stuff(ref Message msg)
{
    if (msg.Msg != 0x0102) //0x0102 == WM
        return;

    char c = (char)msg.WParam;

    //the char in c was pressed, do something!
    DoStuffWithChar(DateTime.Now, c);
}

```
> 1 votes

# Answer
Expanding Shiro's comment: You could increase the speed the game updates to a higher fixed rate (as long as you know beforehand it can handle that FPS). While this isn't really SOLVING your problem it will at least reduce it's effect.

You could either set the FPS to a specific amount:

```
this.TargetElapsedTime = TimeSpan.FromSeconds(1.0f / 200.0f);
//Where 100.0f is how many updates per second

```

Or you could set the FPS to unlimited so it runs as fast as possible:

```
this.IsFixedTimeStep = false;
graphics.SynchronizeWithVerticalRetrace = false;

```

Again: this depends on hardware and the performance of your application, but in simple cases it will be more than fast enough for your precision. Just get the amount of time elapsed from the start of your application (or a separate TimeSpan) whenever a button is pressed and compare it.
> 0 votes

---
Tags: xna, performance, controllers
---


title: How do I make the host work in UNet?

text:
# Question
Title: How do I make the host work in UNet?
According to the "High Level API" documentation, unless I misread something, a Host "just" runs both as a Server and as a Client, so much that it would require no special support, i.e. it should run out of the box.

When the Server and Client are in separate processes, both work correctly. When a host acts as both the server and client, this is not the case.

When `OnServerReady` gets called on the Host, the `NetworkConnection conn` parameter has `.hostId==-1`, and if I try to call on `NetworkServer.AddPlayerForConnection` I'll get a warning and an error.

```
ClientScene::InternalAddPlayer: playerControllerId higher than expected: 0
UnityEngine.Networking.NetworkServer:AddPlayerForConnection(NetworkConnection, GameObject, Int16)
[...]

NullReferenceException: Object reference not set to an instance of an object
UnityEngine.Networking.ClientScene.InternalAddPlayer (UnityEngine.Networking.NetworkIdentity view, Int16 playerControllerId) (at /Users/builduser/buildslave/unity/build/Extensions/Networking/Runtime/ClientScene.cs:90)
[...]

```

If I refrain from calling `AddPlayerForConnection`, then I'll encounter a warning (and no result) as soon as the Host calls a `Command`:

```
Trying to send command for non-local player.
UnityEngine.Networking.NetworkBehaviour:SendCommandInternal(NetworkWriter, Int32, String)
[...]

```

In fact, `isLocalPlayer` is `false`.

Am I doing something wrong, is the documentation wrong, or is this a bug?

---

As requested, some piece of code:

```
public override void OnServerReady (NetworkConnection conn)
{
    base.OnServerReady(conn);

    Transform spawnPoint = FindObjectOfType<SpawnPoints>().getNextSpawnLocation();

    GameObject controllerGO = instancedElements.SpawnObjectFree(playerPrefab,spawnPoint); // this is basically an Instantiate
    GameObject playerGO = instancedElements.SpawnObjectFree(playerCreaturePrefab,spawnPoint);
    [...]
    NetworkServer.AddPlayerForConnection(conn,controllerGO,0);
    NetworkServer.Spawn(playerGO);
    [...]
}

```

*(I've trimmed it down to remove the non-relevant parts)*

# Answer
> 1 votes
In the `OnServerReady` callback the connectionID is passed as -1 to indicate a no connection between server to server. In the connectionID parameter you should pass the connection between the localClient and server using `NetworkServer.localConnections`. If localConnections return only -1, then it means that you are not connected as localClient. Refer unity docs and look for the word host

---
Tags: unity, networking, unity-networking
---


# Question
Title: Blender UV unwrapping causes texture to repeat in UDK material
I've made pillow kinda thing, unwrapped it in Blender and then I imported my mesh to UDK, applied a material:

The material splits, but I don't want that to happen, I want to cover the mesh with only big texture, like this one for example:

How do I do that?

# Answer
> -1 votes
This appears to be a problem in UDK not in blender:

You need to set `Texture X/Y` to `Wrap` rather than `Clamp`. This is in `Advanced Texture Settings` (click the little eye in the upper right corner of the texture details panel)

---
Tags: udk, mesh, materials
---


# Question
Title: Cocos2D V3 Blur effect performance test without iOS device
I am testing the blur effect (`CCEffectBlur`) in Cocos 2D V3 and I found that when I add an effect to an `EffectNode` it takes up to 5 seconds to appear in the IOS Simulator screen. (I know that the IOS Simulator is not to test performance)

When I run the same code in my device (iPhone 6), it appears almost instant.

My problem is to test the performance in old devices like iPhone 4S or iPhone 5 but, unfortunately, I don't have those devices to do some tests.

Is there any way to check my game's performance on those devices without the devices?

This is what I am testing.

* I have a hierarchy with an `EffectNode` as a root node.
* I am using a code like the following to add the effect
`effectNode.effect = [CCEffectBlur effectWithBlurRadius:10];`

# Answer
As you have discovered, the iOS simulator is not for testing performance, so unfortunately there is no way of testing you app at a lower performance level.

I would recommend finding an iPhone 4S/5 on eBay ($140 and $200 respectively) or finding a friend with one of these phones. (or just make sure that your app can achieve very high performance on your iPhone 6 and hope it will run on a 4S (5-10x less powerful))

'Very high performance' here depends on what you are testing. Since you want to test the Blur effect (ie: graphical) performance, all you can do is ensure you have a very high FPS or very low delay between graphical updates.

Keep your app to less than 512MB of RAM (or less, the 4S only has 512 and some might be used by the system/other apps), and grab a good system load app from the store and make sure your app only uses a small fraction of resources. Take a look at some benchmarks and comparisons to compare performance.
> 1 votes

---
Tags: ios, cocos2d-iphone, graphic-effects
---


title: Egg splatter effect

text:
# Question
Title: Egg splatter effect
We are working on game where player will throw eggs at each other, I would like to know how can we implement Egg splatter effect after egg hit other player?

Thanks.

# Answer
> 0 votes
On a 3D perspective a decal would be the choice here. The splatter effect of the egg would be a transparent texture you put in a decal script which layers this egg splatter effect over the player/ground textures. Search in the assetstore for a decal system, i think the Unity forums also contains some threads on how to create such scripts.

My 2D approach would be to simply use a sprite prefab with the splatter effect that gets instantiated and then animated + applied to the target.

---
Tags: unity
---


# Question
Title: My game is mostly complete, how do I find a publisher?
I've been working for quite a while on a game.

I'm mostly done with it.

Simply finishing the project, adding banners and just publishing it on google play / appstore probably won't bring in any money, at least without firstly investing some in promotion...

How do I go about finding companies that might be interested in either promoting or maybe even fully buying out such a product?

# Answer
The first step, is of course, **finishing your game**. The publisher rejection rate is high enough for even established professional game developers, *with complete projects*. Sloperama Lesson 11, Section V

You want to essentially do everything in your power to be as noticed as possible. Publishing is very risky, even when your game is complete, and you want to have everything done so that your potential publisher won't feel like their money isn't wasted.

Following that of course, you just need to prepare your pitch, and then get in touch.Tom Sloper has an excellent article here about the game submission process.
> 11 votes

# Answer
Another option depending on the scope of your game is to skip the publishers and instead try to reach out to review sites and try to have an article written about your game. This is usually very hard for small phone games, but even if it won't work for this one its an important strategy to have knowledge of.
> 0 votes

---
Tags: android, ios, marketing, appstore
---


# Question
Title: An object reference is required to access non-static member UnityEngine.Material.GetTextureOffset(string)
I am watching a tutorial where it seem to work. But in my case, I am getting this error. I get it that non-static members have to have an object. But, I don't know much about how to fix this error.

```
using UnityEngine;
using System.Collections;

public class AnimatedTexture : MonoBehaviour {

    public Vector2 speed = Vector2.zero;

    private Vector2 offset = Vector2.zero;
    private Material material;

    void Start(){
        material = GetComponent<Renderer> ().material;

        offset = Material.GetTextureOffset ("_MainTex");
    }

    void Update(){
        offset += speed * Time.deltaTime;

        material.SetTextureOffset ("_MainTex", offset);
    }
}

```

# Answer
> 1 votes
You wrote `Material.GetTextureOffset ("_MainTex");` in the `Start()` method. It should be `material.GetTextureOffset ("_MainTex");`.

---
Tags: unity, c#
---


# Question
Title: How do I have different colliders against different objects? Unity
Say for example I have a ball, I want the sphere collider to be a certain radius when it comes into contact with one material (material A in diagram) and a different size when it comes into contact with another material (material C in diagram). How would I go about doing this? (Diagram attached)

# Answer
You need to create two empty child GameObjects of material C that work in different layers. One child has a sphere collider with a radius of e.g. 5, reacting to colliders in the layer "One" and one child using a sphere collider with the radius of 10 working in layer "Two". The colliders that react only to the collider with the radius 5 just only react to the layer "One". With layer "Two" the same.

Now uncheck the interaction between "One" and "Two" in the physics manager:

Now for material A set the layer you want to use with the colliders and the problem is solved.
> 3 votes

---
Tags: collision-detection, unityscript, unity
---


# Question
Title: What is wrong with my 2D orbit calculation?
I am working on a 2D game, and I am working on adding some space physics, so I need to find a way to create a circular orbit.

I want to make my game object move on a circular way around a planet. I'm starting with the old famous formula:

```
V = sqrt(G * ((m1 + m2 ) / r))

```

This formula is the classic real world one, V is the velocity of the game object.

Once I code it, it doesn't move on a circular way, it just being attracted by the planet, like normal gravity. Here's my code (I'm using Unity):

```
dist = new Vector2(
  Planet.renderer.bounds.center.x - renderer.bounds.center.x,
  Planet.renderer.bounds.center.y - renderer.bounds.center.y
);
r = dist.magnitude;
rigidbody2D.velocity = dist.normalized * (Mathf.Sqrt (0.5f * ((mBody + mPlanet) / r)));

```

Dist is a 2D vector and r is a float, The G value is 0.5 (I used this one because 6.673E-11 is very small and it's not what I want)

So the question is is how can I make my GameObject move on a circular orbit like a satellite around earth ?

One thing to note, is that my GameObject is kicked by the player, so it get a speed of 12. (I am using addForce()).

# Answer
> 3 votes
From what it seems, you are approaching your problem backwards :)

The first problem you are facing is that you try to give an physics object, that is kicked by something else, a hard-coded trajectory, which means exterior influences (the kick) will not make it move.

Instead, you could implement the gravity simulation from the second problem first. Then, if you give the body the correct initial velocity (the one you calculated with `V = sqrt(G * ((m1 + m2 ) / r))`), it will follow an orbit trajectory (and since the masses of satellites are usually very small compared to that of the planet, you can even remove mBody from the formula).

The second problem should then be easy to solve. If nothing else than gravity is applied, the satellite will stay in its orbit. If you want it to decay slowly in a spiral, you could slow it down each frame. Just multiply the velocity vector by something smaller than 1, or apply a small force opposed to the speed.

The code called each frame would then look like this:

```
void update() // called before each frame is rendered
{
    // Simulate gravity around a point
    float r = distance.magnitude;
    float force = 0.5f * mPlanet / (r*r);
    satellite.addForce(distance.normalized * force);

    // brake the satellite slightly to make it spiral towards the planet
    float brakeFactor = 0.01f; // example, you will have to fiddle with that
    Vector2 satSpeed = satellite.velocity; // get the velocity vector
    satellite.addForce(-satSpeed.normalized * brakeFactor) // apply the braking force, opposed to speed
}

```

Hope it's clear enough, ask any questions you have otherwise! :)

---
Tags: unity, 2d, physics, orbit
---


# Question
Title: Java - Trouble with recursion and rectangle placement
I am using Android API's and using the RectF class for rectangles. I have a list of blocks that are on the screen at one time. Each block is given a random position, and then I go through all of the tiles previous, to check if there is an intersection. If there is, it recursively calls the method again to get a new random position and check it against all the other tiles.

I feel like this should work perfectly, except for one thing that may be affecting it. Since recursion opens up so many instances of a method, it needs to finish them off, so I don't know if the rectangle is just being drawn at the initial position, and the rest of the calls are doing nothing?

I have tried quite a few different methods and this seems to be the closest, but something weird is happening and I cant figure it out.

Start method:

```
    private void start() {

    timerTask = new TimerTask() {
        @Override
        public void run() {

            if(Game.STATE == Game.State.Playing) {
                removeFailedTiles();

                Random deathRate = new Random();
                int i = deathRate.nextInt(100);
                if(i % 10 == 0) {
                    System.out.println("Death tile");
                    activeDeathTiles.add(new DeathTile(getRandomPosition()));
                    //System.out.println(activeDeathTiles.toString());
                } else {
                    System.out.println("Normal Tile");
                    activeTiles.add(new Tile(tileLifetime, getRandomPosition()));
                }

            }

            if(Game.STATE == Game.State.Lost) {
                timerTask.cancel();
                timer.cancel();
            }
        }
    };

    timer.schedule(timerTask, 1000, tileDelay);

}

```

Get Random Position method:

```
private RectF getRandomPosition() {
    int screenWidth = (int) Game.SCREEN_WIDTH;
    int screenHeight = (int) Game.SCREEN_HEIGHT;

    RectF pos = new RectF();

    Random random = new Random();
    int maxX = (int) (screenWidth - (Tile.TILE_WIDTH * 1.5f)), minX = (int) (Tile.TILE_WIDTH / 1.5f);
    int maxY = (int) (screenHeight - (Tile.TILE_HEIGHT * 1.5f)), minY = (int) (Tile.TILE_HEIGHT / 1.5f);

    pos.top = random.nextInt(maxY - minY) + minY;
    pos.left = random.nextInt(maxX - minX) + minX;
    pos.bottom = pos.top + Tile.TILE_HEIGHT;
    pos.right = pos.left + Tile.TILE_HEIGHT;

    if(isOverlap(pos)) {
        return getRandomPosition();
    } else {
        return pos;
    }
}

```

Helper methods:

```
private List<RectF> getAllTiles() {
    List<RectF> allTiles = new ArrayList<RectF>();

    for(RectF t : activeDeathTiles)
        allTiles.add(t);
    for(RectF t : activeTiles)
        allTiles.add(t);

    return allTiles;
}

private boolean isOverlap(RectF position) {

    for(RectF r : getAllTiles()) {
        if(RectF.intersects(position, r)) {
            return true;
        }
    }

    return false;
}

```

If someone could please help me figure out what is going wrong here that would be stellar!

# Answer
> 1 votes
All of your code seems fine exept for this typo on `getRandomPosition()`:

```
pos.right = pos.left + Tile.TILE_HEIGHT;

```

which should be

```
pos.right = pos.left + Tile.TILE_WIDTH;

```

I'm not sure if that can be the root cause of the problem, but there's always the option of not using recursion and use a loop, should be easier to debug:

```
private RectF getRandomPosition() {
    RectF pos = new RectF();

    int screenWidth = (int) Game.SCREEN_WIDTH;
    int screenHeight = (int) Game.SCREEN_HEIGHT;

    Random random = new Random();
    int maxX = (int) (screenWidth - (Tile.TILE_WIDTH * 1.5f)), minX = (int) (Tile.TILE_WIDTH / 1.5f);
    int maxY = (int) (screenHeight - (Tile.TILE_HEIGHT * 1.5f)), minY = (int) (Tile.TILE_HEIGHT / 1.5f);

    do {
        pos.top = random.nextInt(maxY - minY) + minY;
        pos.left = random.nextInt(maxX - minX) + minX;
        pos.bottom = pos.top + Tile.TILE_HEIGHT;
        pos.right = pos.left + Tile.TILE_WIDTH;
    }
    while(isOverlap(pos));

    return pos;
}

```

Bear in mind that if the screen gets too full the loop may not be able to finish. To fix it, something like a maximum number of loops before giving up can be added.

---
Tags: java, android, recursion
---


title: XNA Rotating a Rectangle?

text:
# Question
Title: XNA Rotating a Rectangle?
I am in the process of making a giant shooter game and I have got to the point where I needed to use rectangles to detect bullets and giants hitting the player. I did that however, if you look at this image:

It shows the giant and the players rectangle, as you can see they are not rotating with the player, any idea how to fix this? Also yes I know they are no the same size as the sprites, that is because I set the size as they were to big before.

Thanks for any help :)

# Answer
You might be able to side-step using rectangles altogether. For a top-down shooter you could use bounding circles instead of boxes. Checking collision between circles is much easier and faster than checking collision between non-axis-aligned bounding boxes (just check if the distance squared is less than the sum of the radii squared) and you don't need to bother with rotations.
> 1 votes

# Answer
I assume your rectangle exist out of a X,Y,Width and Height.

First, Create 4 Vector2 for your rectangle:

```
Vector2 v1 = new Vector2(x,y);
Vector2 v2 = new Vector2(x+width,y);
Vector2 v3 = new Vector2(x,y+height);
Vector2 v4 = new Vector2(x+width,y+height);

```

These points are the 4 corners of your rectangle. Next apply some simple transformation on the vectors:

```
v = Vector2.Transform(v, Matrix.CreateRotationZ(MathHelper.ToRadians(30)));//rotates 30 degrees

```

Edit: CreateRotationZ might be CreateRotationX or CreateRotationY.
> 0 votes

---
Tags: rotation
---


# Question
Title: Performance overhead on Non-POT Texture in POT Atlas
Using atlas, we can reduce memory and draw call. And the atlas is usally POT(Power of Two) Texture.

And I know non-POT texture have a lot of GPU and memory performance overhead. (link)

I have many rendering objects and they have also their non-POT textures.
And I packed the images into one 1024\*1024 POT atlas and applied them to the objects.
(each textures is non-pot, and the atlas is pot texture)

In this case, Can I avoid non-pot texture overhead?
Are they treated as non-pot texture or not internally?

# Answer
I can't speak specifically for Unity, as I don't use it, but based on my understanding of graphics hardware (I have written a multi-platform 2D rendering engine or two), there will be no performance overhead using non-pot sections of a pot texture.

I can think of no reason why this would be any different for Unity. The overhead is purely hardware based.
> 2 votes

---
Tags: unity, opengl, graphics, mobile
---


title: Basic Node Based Pathfinding

text:
# Question
Title: Basic Node Based Pathfinding
I am new to pathfinding but i have read and watched through some articles, blogs and videos about Pathfinding.

Since those that i have read and watched from are mainly for RTS Games, Grid Based Pathfinding.

I couldnt find any tutorials where it explains in details of how you can make your own Node Based Pathfinding System.

So i hope, you guys could give me some insightful information to enlight me or even provide useful links which can help me.

I just want to make a very Basic Node Based Pathfinding system, and from that i hope to work from it to make it into a Pathfinding System suitable for my game.

# Answer
Many moons ago when I first dabbled in pathfinding algorithms I used the following site to help me to first understand the basic fundamentals of how a simple pathfinder is meant to work, and what it's trying to achieve. Here is an example for A\*.

The A\* algorithm is quite popular and suitable for most pathfinding needs in gaming. A\* will efficiently navigate just about any node graph when provided with a suitable rule set for finding neighbours for each node.

The question you need to ask yourself is whether or not you actually want to implement your own pathfinder from scratch; or do you instead actually want to create a game. If you're actually leaning towards the latter then there is no point reinventing the wheel and you should instead just cannibalize an existing C# pathfinder for Unity, or just use the inbuilt Unity Pathfinder which should be sufficient and easy to use for most Unity games.

Additionally this Unity plugin is also quite popular and very easy to use.

Pathfinding is a fairly complex and can be quite a deep rabbit-hole. It'll be very time consuming for you to learn, create, fix, refine and then optimize your own pathfinder - especially when others have already spent the time doing the above tasks at length(and probably doing a much better job than you! :) )

Anyway, the whole point of Unity in my opinion is to help you to bypass the need to develop your own game engine and having to write your own systems from scratch. It's done all that work so that you can just jump straight into developing games.
> 1 votes

# Answer
Here is my unity path finding using waypoints (nodes linked each others), recursion and linq: ...

```
using System.Collections;
using System.Collections.Generic;
using System.Linq;

```

...

```
public List<Waypoint> aStar( Waypoint goal,Waypoint nx, List<Waypoint> visited){
        if( visited.Contains(nx)){
            return null;
        } else {
            visited.Add(nx);
            if (nx==goal){
                List<Waypoint> TmpL = new List<Waypoint>();
                TmpL.Add(nx);
                return TmpL;
            }
            else {
                //I use LINQ
                var tmp =  nx.reachs
                    .Where (c => !visited.Contains(c) )
                .OrderBy(t => {
                return (t.transform.position-goal.transform.position).sqrMagnitude;
                }).ToList();
                if (tmp != null){
                 foreach (Waypoint ww in tmp){
                    List<Waypoint> TmpR =  new List<Waypoint>();
                    TmpR=aStar(goal,ww, visited);
                    if (TmpR!= null) {
                        TmpR.Add(nx);
                        return TmpR;
                    }
                 }
                }
                return null;
            }
        }
}

```
> 0 votes

---
Tags: c#, unity, path-finding
---


# Question
Title: Only send moves for P2P 2 player LAN game?
I am making a 2D network game. The concept is simple, a player have to shoot the other player to win. I'd like to improve this game ( add a map, items, monsters, w/e ), but later.

This is my first network programming experience. I have little theorical knowledges about packets, sockets, client/server side, what is dangerous to do client sided, but I've never really used them.

Goals set :

* This is a 2 players LAN game, no more no less.
* No server. Player 1 starts the game waiting for player 2...
* ... which leads the game open for reverse engineering or packet editing, but w/e, for this kind of game I prefer simplicity over security.

Pretty basic. For a first network game that will never be shared, I take off problems and will see later.

This is where I am : each player is a square that can move in four directions. The approach :

* TCP Packets.
* Each movement ( each frame a key is pressed to be accurate ), a packet is sent to the other player with his position.
* Packets are received each frames before drawing and updating game elements, in the same thread, with a non-blocking receive() function.

And that's it.

My questions :

* Is sending a packet for each moves overkill? Will I have problems with this later?
* What kind of problem can I meet? mono-thread + non blocking function will be a problem later, assuming the goals I've set?

# Answer
Let me answer your question with another question. Assuming your game is checking for input every frame, you'll be reading input from the user about 30-60 times a second; which means you would be sending about 30-60 packets every second. That's a fair amount of packets to send every second, you might want to consider something more like 1 every 10 frames.

Realistically, the player isn't going to move very far every frame, so its ok to have some room for buffer. Usually games get around this by doing some predictions of where the player will end up based on where they were last and their general direction/velocity. Then they simply compensate for the actual position with every new packet.

Since you're doing TCP, there's a stronger focus on ensuring high reliability of packets. This means things are going to take a bit longer when transporting. I would suggest looking into doing UDP instead, as it has more of a fire-and-forget mentality. Not every packet will make it to the other end, but this goes back to the point that most games just help compensate for this by making approximations and correcting them.

I'm not very experienced with networked games, but this is just knowledge that I've acquired over the years when talking to people. Hopefully others can go into more detail, if needed.
> 2 votes

# Answer
It appears what you are going after is called the **Peer-to-Peer Lockstep** model, according to the relevant article in Gaffer on Games. That is:

* Each peer runs a separate game simulation
* Peers share their own player's moves to all other peers (that's the peer-to-peer part)
* Peers simulate the same game using the same set of inputs, and don't proceed until being acknowledged by all other peers (that's the lockstep part)

This is a very simple model which suits LAN play very well, and is used by Doom and many RTS games since it's the cheapest way to share the state of many thousands of game entities. For reasons that don't apply to you, most games that require network play over the internet have moved on to client-server and other advanced models.

It does come with some hefty requirements, so beware:

* You need to judiciously remove all **non-determinism** in your game. If you use an RNG, you'll need to make sure that it's the same RNG, all clients seed it the same way, and then you can't allow mid-game joins. Also watch out for the effect of non-standard floating point numbers on non-determinism. But really, as long as you are running on the same CPU architecture and compiled using the same compiler, you'll be ok.
* A suitable game loop. Variable-length game loops are out, since your peers will drift out of sync rather quickly if the length of their (game) frames are different.

To answer your question, yes this is feasible, and is probably the simplest way to bolt networking on to an existing game that wasn't architected for it.
> 2 votes

# Answer
Maps, items, monsters, etc. gives you many factors that can be tipped out of balance by 1 small difference in a floating point operation. A character moves a little bit more to the right, he bumps into another character 1 frame early, then suddenly the whole world implodes and monsters die on some clients but not others.

You'll have a much easier life replicating properties. If you don't care about hackers (and why should you?), let players simulate their character's movement, rotation, and bullets then distribute that information to everyone. Note that, as SaviorXTanren mentioned, 30-60 packets per second is a lot for a video game, even a lockstep one that doesn't pack much into the packets. I mean, 30p/s over TCP results in 3,120 bytes of overhead. This issue is made even worse because with p2p, each client has to have a line of communication with every other client. Players can't influence the world at such a high frequency so much of the data sent will be useless.

Instead, shoot for 10-20. Planetside 2 does it with 5. And replicate properties unless your game is big enough and designed to generate a large community of hardcore players. With p2p replication, 2-4 players should be fine. If you're replicating properties, UDP would be better than TCP because data quickly becomes outdated after a new update arrives so there's no need to guarantee that data arrives.
> 2 votes

---
Tags: networking
---


# Question
Title: Transition between normal and slow motion
I have a game (C++) in which I want to transition between two speeds of motion. For illustration, the player raises their weapon to aim, and whilst this is in progress over a known duration, time should slow down incrementally until it reaches the target rate.

Slowing it down linearly is easy. We have a start speed (e.g. 1.0), an end speed (e.g. 0.2), and can determine where we are in the fixed-length transition (e.g. 2000ms)

However if I slow it down linearly, the look and feel is just wrong. I suspect that to feel 'right', it should slow down quickly early in the transition, and then at a decreasing rate towards the end.

My maths is less than brilliant; it's been a long time since I graphed a function, and I rarely if ever introduce this kind of stuff into code. At a guess, using part of a 1/x or x^2 curve might give me what I want, but I'd still have to parametrise it to suit.

This or something like it must be a regularly-solved problem, so what's the simplest approach I can use here?

# Answer
> 2 votes
Here's a function that interpolates between Start and End quadratically by T.

```
float Qerp (float Start, float End, T)
{
    //The quadratic stuff
    T = 1 - T;
    T = 1 - (T * T);

    float Difference = End - Start;

    return (Start + (Difference * T));
}

```

I.e.:

```
float Elapsed = 0;
const float Length = 2.5f;
while (true)
{
    Time.timeScale = Qerp (1f,.2f,Elapsed / Length);

    Elapsed += Time.deltaTime;
    if (Elapsed > 1) break;
    yield return null;
}

```

This sets Time.timeScale from 1 to .2 over the course of 2.5 seconds. As the elapsed time of this process increases, the amount at which Time.timeScale changes decreases.

---
Tags: c++, mathematics, time-travel
---


title: Box2d Body to follow mouse movement

text:
# Question
Title: Box2d Body to follow mouse movement
I am trying a box2d body to rotate following the mouse. Here's an image to clarify what I mean.

The red and blue circles are current point of the mouse and the body (of corresponding color) moving/rotating to follow it. Basically the rectangle should rotate with its one end pointed towards where the mouse pointer is.

Here's my code so far,

```
 World world;
    Body body, bullet;
    Box2DDebugRenderer debugRenderer;
    OrthographicCamera camera;

    @Override
    public void create() {

        world = new World(new Vector2(0, 0f), true);
        debugRenderer = new Box2DDebugRenderer();
        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();

        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.DynamicBody;
        bodyDef.position.set(10, 10);
        body = world.createBody(bodyDef);

        PolygonShape shape = new PolygonShape();
        shape.setAsBox(2, 5);
        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = shape;
        fixtureDef.density = 1f;
        Fixture fixture = body.createFixture(fixtureDef);

        shape.dispose();

        Gdx.input.setInputProcessor(this);

        camera = new OrthographicCamera(200, 100 * (h / w));
        camera.position.set(camera.viewportWidth / 2f, camera.viewportHeight / 2f, 0);
        camera.update();

    }
 @Override
    public void render() {

        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        world.step(Gdx.graphics.getDeltaTime(), 6, 2);
        camera.update();
        debugRenderer.render(world, camera.combined);
    }

  @Override
    public boolean mouseMoved(int screenX, int screenY) {
        int mouseX = screenX;
        int mouseY = Gdx.graphics.getHeight() - screenY;
        float rotateAngle = MathUtils.radiansToDegrees * MathUtils.atan2((float) mouseY - (float) body.getPosition().y, (float) mouseX - (float) body.getPosition().x);
        body.setTransform(body.getPosition(), rotateAngle / 57.2957795f);
        return true;
    }

```

And here's a gif of how it appears now.

as you can see the body gets skewed and also doesn't rotate properly. What am I missing?

# Answer
The skewing is because of how the viewport is setup, try changing it to something like this;

```
@Override
public void create() {
  ...

  bodyDef.position.set(0, 0); // Let this be at origin for now, it's easier to debug

  ...

  camera = new OrthographicCamera(200, 200 * ((float)Gdx.graphics.getHeight()/(float)Gdx.graphics.getWidth());
  camera.position.set(0, 0, 0); // easier to just center on origin for now

  ...
}

```

Also, the rotation is wrong because you're trying to use screen coordinates, you need to unporject them from screen space into camera space;

```
@Override
public boolean mouseMoved(int screenX, int screenY) {
  Vector3 sp3 = camera.unproject(new Vector3(screenX, screenY, 0));
  Vector2 sp2 = new Vector2(sp3.x, sp3.y);

  // Take the vector that goes from body origin to mouse in camera space
  Vector2 a = body.getPosition();
  Vector2 d = sp.sub(a);

  // Now you can set the angle;
  body.setTransform(body.getPosition(), d.angleRad());

  // You might have to do some work on d.angleRad if you find your angles are flipping as the appraoch PI/2.
}

```

As a side note, be careful about rotating bodies like this, `setTransform` on `Body` is intended for body setup, not during the simulation and I think you might run into some interesting behavior when this body collides with other bodies.
> 2 votes

---
Tags: physics, libgdx, box2d
---


# Question
Title: How can an asset bundle's resources be destroyed after destroying the compressed bundle data?
Using:

```
AssetBundle.Unload( false );

```

Will clear the compressed asset bundle data. This, unfortunately, destroys the bundle object as well, which means nothing is keeping track of the loaded resources.

Using:

```
AssetBundle.Unload( true );

```

Will clear all resources correctly. However, it may be desirable to load the required resources, free the compressed data, and then free the loaded resources at a later time. How can this be done?

# Answer
> 2 votes
Unity Documentation: **AssetBundle.Unload**

When **unloadAllLoadedObjects** is *false*, compressed file data for assets inside the bundle will be unloaded, but any actual objects already loaded from this bundle will be kept intact. Of course you won't be able to load any more objects from this bundle.

When **unloadAllLoadedObjects** is *true*, all objects that were loaded from this bundle will be destroyed as well. If there are game objects in your scene referencing those assets, the references to them will become missing.

---

In your case, you want to use

```
AssetBundle.Unload(false)

```

This will destroy the loaded assets, but keep intact the already created GameObjects.

These being just GameObjects, you can destroy them at any later time using **Object.Destroy**.

```
public static void Destroy(Object obj, float t = 0.0F);

```

---

PS: You should take a look at **Resources.UnloadUnusedAssets** too.

As the function name implies, it Unloads assets that are not used.

An asset is deemed to be unused if it isn't reached after walking the whole game object hierarchy, including script components. Static variables are also examined.

---
Tags: unity, resource-management
---


# Question
Title: 2D Collision response - rotating, moving polygon hitting a wall
I'm trying to bounce a polygon that has both velocity and angular velocity off a (immovable) wall when one of the vertices collides with it. I can detect the collision, and I've worked out how to calculate the inputs and know what outputs I need, but haven't been able to find or work out an implementation for the response. Any help would be greatly appreciated.

```
function collisionResponse(
    c, // object center of mass position
    v, // velocity of object
    a, // the angular velocity of the object
    p, // point of contact with line
    n  // normalized normal of line
) {
    //  Make a vector from center mass to contact point
    cp = p - c;

    //  Total velocity at contact point (add angular effect)
    pv.x = v.x - cp.y * a;
    pv.y = v.y + cp.x * a;

    //  Reflect point of contact velocity off the line (wall)
    rv = reflect( pv, n );

    // magic happens..

    result.v = ?? // resulting object velocity
    result.a = ?? // resulting object angular velocity
    return result;
}

```

# Answer
> 3 votes
You've got the moving part right but the rotating adds a significant amount of complexity to the problem. Luckily, you can hack in rotational velocity with a formula mentioned here. It approximates rotational velocity based on the distance from the center of mass to the point of contact, and the positional velocity.

Here's an implementation:

```
a = (cp.x * v.y - cp.y * v.x) / (cp.x * cp.x + cp.y * cp.y);

```

Or:

```
a = Vector.Cross (cp, v) / cp.sqrMagnitude;

```

Most of the time, you can stop here and not consider the transfer of energy between rotational and positional velocity because then you would have to get into surface friction and other scary things. For something like a boulder rolling off a mountain or a stick thrown against a wall, this would work perfectly. For a more physicsy game though, you might have to pick up a physics textbook and learn the subject inside-out - or just port an existing physics engine to your liking.

---
Tags: 2d, physics, collision-resolution
---


# Question
Title: Why is Unity 2D Alpha-Blurring my pixel sprite?
So I have just brought in a place holder block for the ground in unity 2D, and it's 16 by 16 pixel image, and for some reason unity is automatically blurring the image. So I was wondering if there was any way to stop unity from automatically blurring the image. I would really appreciate if someone could tell me how to stop the image form being blurred. Also sorry if this is, just something that is incredibly simple to fix, I just started using unity 2D instead of 3D so it's different for me.

Thanks, Nova

# Answer
> 3 votes
The default sprite filter mode in Unity is set to Bilinear.

If you change it to Point, it will retain the pixel crisp.

http://docs.unity3d.com/ScriptReference/FilterMode.html

---
Tags: unity, 2d
---


title: Why can't CSS Sprites handle vectors?

text:
# Question
Title: Why can't CSS Sprites handle vectors?
Almost all the documentation available either says that "sprites are bitmaps" or that "css sprites must be bitmaps". Is there a specific reason for this? Is it, in fact possible to create a css sprite sheet with .SVGs? If it is possible is it a good idea, and is the SVG format supported on all browsers?

I'm creating a HTML5 game with a strong minimalist art style, using elements of European folklore. I don't *need* vector images per se, but I'd prefer the game was as responsive as possible to improve UX and to allow gameplay across different devices.

An example character. As you can see, there is no fine detail that would be better represented with a raster image.

# Answer
If you’re familiar with CSS spriting,it can be done the same way with SVGs. Unlike the icon fonts technique, you’re not bound to one color.

You can use gradients, clipping masks, and transparencies while still keeping your mark-up and CSS clean.

Chrome supports SVG with a few minor bugs and so does the latest Mozilla browser these are the ones that most people generally use.

SVG sprite sheets can be used as background for CSS and to use it is a pretty good idea. You will find many websites and blogs that show you how to exactly use it that way.
> 2 votes

---
Tags: html5, vector, html-canvas, svg, vector-art
---


# Question
Title: 3D Studio MAX dxf model to OpenGL and DirectX
**Main Question**

I saw this Loading and Animating MD5 Models with OpenGL an old post explaining .md5mesh .md5anim files. Is there any similar alternate mechanisms?

**Additional Questions**

1.) Is there an open source tool or a Plug in for 3ds max to convert a .DXF file to such files which can be used in 3D OpenGL+DirectX game programming.

2.) If I am developing a game in this approach how to make these model files encrypted and make big single file which contains all this file, so that the user cannot crack/hack it?

3.) If I am providing an update via an online gaming server, then how to I update this models and keep it encrypted again?

# Answer
> 2 votes
To answer the first question there is an open source library Assimp which can read such model file, but it comes with an extensive 40+ file types as a generic library which could be a bit bigger in size when you compile. Also it is distributed under 3-clause BSD-License.

If you are creating your own gaming engine, then think about creating your own model design which cannot be parsed by any of the existing library, so it will take time for the hacker to understand it.

Regarding the security concern, I can go with Viklund statement, we can say atleast all security is broken when the games runs in the palyers computer memory.

But think about a non standard public key algorithm which could be a combination of key generated and jumbled with no standard offsets at client machine everytime while user logs in and server provides the current key for decryption which will change next time, So atleast the hacker will take time to decrypt it, and before that you introduce another mechanism and keep changing it.

I would also recomend you change the security key everytime the user enters a map in your game.

---
Tags: opengl, directx, 3dsmax
---


title: roll over camera!

text:
# Question
Title: roll over camera!
I'm making a prototype. I used the Unity RollerBall, prefab, but I need to be able to attach a camera to it and keep it steady. I need to have it follow the ball as it rolls, but have the camera roll with it. Any ideas?

# Answer
You need to work with the basic Transform methods. At first you need the target position to know from where to start the calculation. Then you substract the direction vector to receive a new position for the camera. To set the camera view to the target transform use `transform.LookAt`.

```
public Transform targetTransform;
public float distanceToTarget;

void Update ()
{
    transform.position = targetTransform.position -
        (Vector3.forward * distanceToTarget);

    transform.LookAt(targetTransform);
}

```

Attach this script to the camera. To set the perspective of the viewer to the target transform you need to tweak the `Vector3.forward` value.
> 0 votes

---
Tags: unity
---


# Question
Title: Rorschach ink blot (aka Psychology test pictures) shader
<sub>(source: bonnefil.com)</sub>

I want this magnificent pattern to be in my game. So far I have figured out...

1. Draw one side, then render it twice left and right.
2. How do I render this pattern on one side? hmm...
3. I need help.

I need some insight on writing shader for this.

If you think is not shader fitting task, then let me know, hopefully with an alternative solution!

However I see no possible approach to achieve this without gpu. (unless you suggest to store bunch of prepared pictures of rorscach pic)

# Answer
> 15 votes
To get that authentic inky look, your best bet is probably to assemble a library of images of ink splats, streaks, and dribbles.

Then you can randomly select some number of them to position & rotate randomly over one-half the image. (With a bias toward the seam edge so the middle of the Rorschach test is densest. You might be able to use a particle system to do this scattering)

Render that to a texture with wrap-mode set to mirror, and now you have a symmetrical ink blot you can display without any custom shaders.

Here's an example of the kind of result you can get doing it this way:

If you don't care about those signature inky shapes, you can also do this with a shader that thresholds two noise patterns scrolling past each other. That gets a symmetrical irregular shape, which can be made to change continuously over time if you like, but it won't look quite like ink.

This is the method that dnk drone.vs.drones suggests in another answer, and it can give results similar to this:

**Edit:** here's a breakdown of how the noise-based approach works...

First we start with some noise. 1/f noise, often called turbulence, works pretty well. You can bake tiling noise into a texture and then sum one or more samples from it, changing their offsets/rotations to vary the shapes you get.

If we threshold this directly, we get an image like the one at the right. The shapes are about correct, but to look like a Rorschach test it should be densest near the middle and thin out toward the edges.

We can make this work by adding a gradient over top (contrast exaggerated here for clarity)

Then threshold it by taking `(sum - blackLevel) * contrast`

(Here `blackLevel` is a parameter that controls how speckly vs blobby the result is - higher values mean more solid black - and `contrast` controls how sharp the edges are)

Mirroring this image will give you the Rorschach example above.

# Answer
> 8 votes
You can try perlin noise (using a proper black/white gradient) , and then apply the right/left mirroring

---
Tags: shaders, post-processing
---


title: How to debug a GLSL shader?

text:
# Question
Title: How to debug a GLSL shader?
I cannot find any tutorial in Google and Youtube. I have a C++ program that uses OpenGL ES 2.0 API to render something on the screen. How can I debug my shaders? Any step-by-step guide? What is the easiest way to at least print variable values?

# Answer
> -2 votes
In general, you can't. The typical development environments only give you visibility on the C/C++ side.

So, I say "you can't" but that's obviously not exactly true. You can't step through the shader and print variables, but still we all develop and debug shaders. But it's a lot of intuiting indirectly what's going on, by repeated runs. Some of the things I do is:

* Have a simplified version of my app that only draws 1 or 2 things, so try/edit/retry goes faster
* Have a few fallback shaders that I *know* work, and swap them in when I'm doubting my own sanity...
* Use revision control, of course
* Always print out all the error messages from compiling with `glGetShaderInfoLog()`

In some game engine environments, you author shaders at a higher level, using flow diagrams and such, and the engine generates GLSL (or HLSL &c) on the fly, which is a whole different debug experience.

Hope that helps!

---
Tags: opengl, c++, shaders, opengl-es2, debugging
---


# Question
Title: Keyboard.GetState() only work first time, and Memory increase (not Disposing)
**EDIT UPDATE 3** I been searching the web for a solution and found several people struggling with Memoryleak using MonoGame while trying to dispose objects. It could be the case that MonoGame should be started and then closed as a own process, not from another program which are my case. When I click on the button, a new thread is created and the MonoGame application is started:

```
 viThread = new Thread(startDemo);
 viThread.Priority = ThreadPriority.Highest;
 viThread.Start();

 private void startDemo()
 {
        using (Demo d = new Demo())
            d.Run();
 }

```

The "Demo" is closed by a Game.Exit command and i have also tried with Disposed(true) without any success. Next time I launch the MonoGame is Keyboard.GetsState() always empty and the memory is incresed. I made a loop where I started and closed the application 100times and it are eating my memory. I have seen lots of discussion about SharpDX not working correcly with dispsing resources. So here I am, stuck. Just want to point out that this worked fine for XNA but not now when changed to MonoGame. And again, thanks for all comments I got so far.

I have uploaded a project where you can see the issue by yourself. The second time dosn't the keyboard input work but mouseinput does and the memory is increasing for each time:

Donwload sln project

**EDIT UPDATE 4**

It is SharpDX which increase the memory, I perform following line before i exit:

```
SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects().Length

```

And its increasing all the time. So I guess it isnt released. Someone know how to do that?

# Answer
You are forgetting to dispose your game object.

```
[STAThread]
static void Main()
{
    using (Game1 game = new Game1())
        game.Run();
    using (Game1 game = new Game1())
        game.Run();
}

```
> 0 votes

---
Tags: xna, c#, monogame, sharpdx
---


title: Optimal trajectory of area exploration

text:
# Question
Title: Optimal trajectory of area exploration
I've got next problem. There is three objects:

1. first one, with next characteristics: circular area of view, speed, drag coefficient;
2. wind (or water current, doesn't matter; some sort of resistance) with some strength and direction;
3. polygon, concave (in general case).

I need to build path of first object inside this polygon, which will:

1. cover whole polygon by view area;
2. be optimal by travel time;
3. takes into account wind direction and strength.

In other words, I need to carry out exploration in a given area on optimal trajectory while scout can be drift away.

# Answer
With **r** being the circular area view radius;

1. Make a mesh that covers the polygon where the nodes are at most 2**r** apart and connect the nodes with neighbours.
2. Based on the distance and wind/water current between each node, add a difficulty value to progress through the arcs; arcs are bi-directional and don't have the same value (for instance for node A to B -\> cost is 10, but for B to A -\> cost is 20 because of the wind), you'll get a directed graph.
3. Apply a greedy algorithm to explore all the nodes in the graph.

From the description of your issue, the speed and drag coefficient of 1. are irrelevant as they'll be the same throughout the whole path-finding process.

**Note**:
You **will not** find the *optimal* trajectory with this. You will find a *good* or *okay* trajectory, but unless you want to throw in optimization and meta-heuristics, that's all you're going to get.

---

Optionally, you could try and 'merge' the arcs going from the start of a current to it's end, removing the nodes along the way. This will leave you the optimal path *for this spot*.
> 0 votes

---
Tags: 2d, algorithm, path-finding
---


title: Libgdx Scene2d and Box2d light

text:
# Question
Title: Libgdx Scene2d and Box2d light
Currently I am using scene2d and I want to implement shadows using Box2d light. I want shadows under characters but when I draw something after render() , it draws nothing. For example, in draw() method of an actor,

```
    public void draw(Batch batch, float delta){
        super.draw(batch,delta);
        ray_handler.render();
        batch.draw(Something......)
    }

```

But when draw before render, it shows no problem.

```
    public void draw(Batch batch, float delta){
        super.draw(batch,delta);
        batch.draw(Something......)
        ray_handler.render();
    }

```

How can I solve this problem?

# Answer
> 1 votes
The render() methods of ray handler should not in the batch.begin() and batch.end() methods.

```
public void draw(Batch batch, float delta){
    super.draw(batch,delta);
    batch.end();
    ray_handler.render();
    batch.begin();
    batch.draw(Something......)
}

```

Above codes are working properly. The Result looks like this

---
Tags: libgdx, box2d, scene2d
---


# Question
Title: In XNA, how do I make a sprite move towards another?
I am making a shoot-em-up with a player-controlled sprite with a gun:

I have most of the game working, but I have gotten to the point where I need to load in the enemy characters and make them move towards and follow the player.

I know it starts with getting the players position and working out the difference between the player and an enemy, then moving them. I have tried to search the web for this, but they don't really explain it very well and I would rather someone who knows what they are talking about explain it or at least show me how it might work.

# Answer
Looks like you want to implement stteringbehaviours. Take a look a chapter 3 of this book. I think it would make your game look more natural if you implement it this way.
> -1 votes

# Answer
if you haven't already gotten this figured out, a simple way to do it without complicated path-finding is to check the position of all of the enemies vs yours. If the enemies are below you position, move them up. If they are too far to the left, move them right. It's as simple as that.

Example:

```
foreach (Enemy enemy in enemies)
    if(enemy.x > player.x)
        enemy.x -= enemy.speed;
    if(enemy.x < player.x)
        enemy.x += enemy.speed;
    if(enemy.y > player.y)
        enemy.y -= enemy.speed;
    if(enemy.y < player.y)
        enemy.y += enemy.speed;

```
> -1 votes

---
Tags: xna, c#, ai, vector, direction
---


# Question
Title: Camera rolls instead of looking up and down
I got a small script from the official Unity forum which is:

```
public class MouseRotationUpDown : MonoBehaviour {
    public float RotationSpeed = 5;

    void Update ()
    {
        transform.Rotate(Input.GetAxis("Mouse Y") * RotationSpeed,0, 0 /** Time.deltaTime*/, Space.World);
    }
}

```

This script should rotate (as in looking up and down) the camera, based on my mouse movement. But instead of just rotating the camera over the X axis (up & down) it rotates the camera over all three axis at once.

This is the only script attached right now.

# Answer
> 1 votes
DMGregory posted this and I'm just copying his comment to be able to close this question with an answer.

> You're rotating with respect to Space.World. So if your camera's z-axis is pointing along the world x-axis, then what you're applying as a pitch (world x-axist rotation) will be observed as a roll (local z-axis rotation). Does the problem persist if you try Space.Self, or play with different starting orientations for the camera? – DMGregory

So I changed Space.World to Space.Self and the issue got fixed. Thanks everyone for leading to this answer.

---
Tags: unity, camera, mouse
---


title: Collision detection console log errors?

text:
# Question
Title: Collision detection console log errors?
So the code down below is supposed to load the next scene once the player touches the flag which the code is attached to. I've made sure that is trigger is checked and yet I'm still getting errors from the console log like `expecting '(' found 'OnCollisionEnter2D' and unexpected token: theCollision`. I really tried to solve the problem on my own and searched the web for an answer but failed. Thanks in advance.

```
#pragma strict

function Update () {
    function OnCollisionEnter2D(theCollision : Collider2D) {
        if (theCollision.gameObject.name == "Player") {
            Application.LoadLevel("scene2");
        }
    }
}

```

# Answer
> 3 votes
You've written your OnCollisionEnter2D function inside your Update function. You want it written after it:

```
function Update() {
 // Your update code goes here.
}

function OnCollisionEnter2D(collision : Collision2D)
{
 // Your collision response code goes here.
}

```

Also note that if you've marked the collider as a trigger, then it will never call OnCollisionEnter2D - for triggers you'll want OnTriggerEnter2D instead.

---
Tags: collision-detection, unityscript
---


# Question
Title: How should I send packets to multiple clients on UDP?
I'm developing a 2D action side-scroller shoot-em-up game and I recently implemented the multiplayer aspect.

When the server sends packets containing the game state (which are about 500-700 bytes) to a single client, the ping is around 32ms and it works smoothly, but the moment another client connects, both clients start to lag and the ping increases to 200ms and I am assuming that the problem lies with network congestion

*So my question is*, should the server automatically send data to all clients simultaneously OR should the client ask the server for an update on the game world OR is there another method I do not know about?

BTW I am using UDP protocol as I found TCP to be pretty slow after a certain amount of time in-game.

# Answer
> 1 votes
I think the main problem is that you try to send the whole game state every interval.

A better way would be to split the sync into *events* and *states*. Events are important things like a spell that gets casted or damage that is dealt. Events need to get send over *TCP* because such packages are reliable and sequenced. States are components like the position and rotation of entities. States are sent over *UDP* because the sequence or packet loss does not matter here, the UDP client sends every interval. Depending on the maximum player count you can use multicasting for the UDP client.

Example:

```
// Sent when an event was requested by a client
public struct ServerEvent
{
    public int affectedEntityId; // The entity that is affected by this event

    public int receiveDamageAmount;

    public int castedSpellId;
    public int castedSpellTargetEntityId;

    // ...
}

// Sent every interval (the Source engine uses 66.6ms)
public struct ServerState
{
    public int affectedEntityId;

    public float xPosition, yPosition;
    public float angle;

    // ...
}

```

Because you do not send the whole state of your game, you will need to identify content in your scene. Spells and items the players collect need to be synced so that when a client requests the casting of a spell, every other peer knows what happened. This is easily managable with IDs. Every time new content is added to the scene a new event gets spread over the network. Containing the resource itself and an ID you can easily address specific entities in the game. On the server, these resources can be stored in a *dictionary* that has a sample instance of every object. This gives you not only a *centralized management* of ingame content and versioning, you can also add new content to your project, without even *updating* the client application.

```
// Sent when a resource is instantiated
public struct ServerSpawn
{
    public object resourceState; // The serialized state
    public ResourceType type; // The type, identifiable with an enum
    public int resourceNetworkId;
}

```

To conclude, my approach on the problem would solve this issue by centralizing the data of your game and splitting the communication in this client/server model into *events* and *states*.

---
Tags: networking, socket
---


# Question
Title: How can I represent prerequisites of different type of game objects?
In a strategy game, I want to declare prerequisites for various types of game objects to limit when they can be acquired/executed: technologies, buildables, resources, actions, etc. Any of these types could have prerequisites from any other type.

Examples:

* Training unit U requires technology X to be known, a building Y present in the city, and a surplus of resource Z available.
* Starting research on technology T requires technologies A and B to be known, and a source of resource C available.
* Construction wonder W requires 5 instances of building D in that player's cities and no other instance of W in existence.

The difficulty here is that each type of object meets the prerequisite in a somewhat different way. Technologies are known to a player or not, while buildings may exist in a given city, and resources could be present but not exploited or already claimed.

Is there a way I can generically describe such a prerequisite feature that can include any combination of semantically different game objects? This structure would have to determine, given a context, whether all prerequisites are met, and if not what is missing.

# Answer
If you're looking for some magic pattern or data structure that deals with prerequisites, I don't think there is one, or rather, it's very simple: all you need is a simple way to **query the number of Xs in Y**, and a clear **hierarchy of ownership**.

That is, be able to query things like:

* Number of *buildings* of a certain *type* in a *city*
* Whether a specific *technology* is known by the player's *tech tree*

And so on, which naturally implies a hierarchy:

* Player
    + Tech tree
        - Technologies
    + Cities
        - Buildings
    + Access to resources (?)

Then you check whether an action (training, research) is possible by checking that all of its prerequisites are met. From your examples, you'll need some *aggregation* functions too.

> Examples:
>
> Training unit U requires technology X to be known, a building Y present in the city, and a surplus of resource Z available.

Becomes:

* Technology X exists in the tech tree
* Building Y exists in city
* *whatever owns resources* has at least some amount of resource Z

> Starting research on technology T requires technologies A and B to be known, and a source of resource C available.

Becomes:

* Technology A exists in the tech tree
* Technology B exists in the tech tree
* *whatever owns availability of resources* contains resource C

> Construction wonder W requires 5 instances of building D in that player's cities and no other instance of W in existence.

Becomes:

* The *sum* of buildings D in all cities is at least 5
* The *sum* of wonders W in all cities is 0

There are many ways you can implement these prerequisites. Consider preferring simple representations, because don't forget, the player also needs to know and track these prerequisites, so you don't want it to be too confusing.
> 1 votes

# Answer
Generalizing your problem, you have a pool of data (the player's state), and you need a way to represent a boolean expression over such data,

Before starting, you may want to sit down and decide:

* How many situations need prerequisites? 20? 10000?
* Which data sources are available for querying? Just technologies and resources? How about time since the game started? How about custom flags to restrict development? (think about the early missions in story mode where your tech tree is not completely available) How about magic spells to restrict the enemy's development?

The more data sources you have, the more complex the system will be
* What kind of operations do you want to perform on your data? available/not\_available, equals, unequals, greater\_than, lesser\_than, and so on

The more types of operations you have, the more complex the system will be
* How are different conditions related? Are all prerequisites just a large "and", so only one condition not being satisfied invalidates everything? Or will you also need "or" and other operators? How about grouping (parentheses)?

The more types of relationships, the more complex the system will be
* And finally, how easy do you want your system to be mofifiable? Can you get away by hardcoding it into your game source? Or do you have a group of game balancers that you want to be able to tweak these conditions without having to rebuild (or even restart) the game? Or do you want the game to be moddable, so end users can actually change the game conditions?

As a result, I can come up with three main ways to implement prerequsite systems like the one you need:

* Hardcoding into your game logic: This may leave a funny aftertaste, but do remember that it is the easiest to implement if the amount of situations is small. Also it is very flexible, as you have the entire power of your programming language to implement conditions as you see fit
* Making a database, where all these conditions are stored. As long as the relationships between different conditions are very simple (just a big "and"), this may be a CSV file, where you have conditions like SOURCE OPERATOR VALUE. This is relatively simple to implement, and doesn't require you to recompile whenever you make a change. I've used this type of database for representing pretty much everything in a game, so a team of game balancers can focus on their job
* Having your own language where your conditions are interpreted. This can either be a custom language (not recommended unless it is very simple), or a script language like lua. Conditions are stored as expressions in that language, and the parser/compiler makes sure they are correctly implemented. This is almost as flexible as hardcoding, but no recompiles are required. This is also very mod-friendly if you choose to add modding support for your game. However, remember the overhead you need to completely support a second programming language (if your game doesn't have any scripting capabilities yet), and the training needed to explain how the language works to other people if they are going to be helping you balance the system.

Be pragmatic though, and only implement the bare minimum to support what you need.
> 1 votes

---
Tags: architecture
---


title: How to use world coordinates

text:
# Question
Title: How to use world coordinates
I am quite new to game development (but not programming) so please forgive me if I am not correctly understanding certain concepts.

I am trying to figure out how to use world coordinates rather than pixel coordinates so that my game can work correctly at different resolutions. As I understand it, I need a viewport and I can use camera functions such as project() and unproject() to convert between the two coordinates. At the moment, I am just placing objects every 16 pixels as this is the size of objects and the objects cannot intersect.

For example:

The bottom left block is located at pixel (0, 0), the one to the right at (16, 0), to the right of that is (32, 0), and so on. However, I would like to be able to place them at (0,0), (1, 0), and (2, 0) with the same result so that it looks the same on different resolutions.

Basically, I'm asking how to set this up and have it work properly as world coordinates.

# Answer
> 0 votes
Here's what I would do in this situation.I'm not using libgdx myself, but I'll give you some pseudo pseudo code. If you haven't already, make a separate class called something like **TileMap** In that class, create the following variables.

* public int tileSize
* public int tilesX
* public int tilesY
* public int\[,\] map

The map variable is a two dimensional integer array, meaning that every tile type will be represented as an int. For example, a stone tile could be '3'

In the constructor of the **TileMap** you need to take in ( tileSize, tilesX, tilesY), and assign them to the local variables.In the bottom of the constructor you need to instantiate the map variable like shown in the example constructor below

```
public TileMap( tileSize, tilesX, tilesY ){
    this.tileSize = tileSize;    this.tilesX = tilesX;    this.tilesY = tilesY;
    this.map = new int[tilesX,tilesY]();    // not sure if you need the () at the end, since I'm writing this on my phone.
    }

```

Now you've got a TileMap setup, currently all the tiles should be 0 to my understanding, if they aren't you might have to make a nested for loop for the tilesX and tilesY variables. It's time to create the methods that will return the world position from given tile coordinates, and the method that will return a tile from the given world coordinates. To convert to world position, simply take the X and Y values and multiply them by the tileSize this will give you 0,0 at the tile 0,0 and 48,48 at the tile 2,2 *assuming you have tileSize set to 24* You can create a method that returns this easily.

To get the tile from world coordinates you need to do something like this *assuming you work with vectors*

```
public int getTileWorldPos(Vector2 worldPos){
float x = Math.floor(worldPos.x/tileSize);
float y = Math.floor(worldPos.y/tileSize);

return map[x,y];
}

```

This method will return the tile id at the given world coordinates

If you want to change the tile at a given world pos use this method

```
public void setTileWorldPos(Vector2 worldPos, int newtile){
float x = Math.floor(worldPos.x/tileSize);
float y = Math.floor(worldPos.y/tileSize);
map[x,y] = newtile;
return;
}

```

Now that you've got a TileMap class, you need to instantiate it in your main class. To do this, simply write

```
TileMap map = new TileMap (24, 10, 10);

```

In that case, I'm creating a 10 by 10 TileMap with a tileSize of 24

If you want to manually set a tile you can just do like this

```
map[6,3] = 3;

```

And to use the methods you created in the TileMap class, write

```
map.getTileWorldPos(new Vector2 (362, 49));

```

I've written all of this on my phone, so I haven't had any way to test my code, and syntax might not be perfect. But hopefully this will give you an idea on how to do this.

if I'm missing anything feel free to ask questions.

I hope this can help you achieve what you want :)

# Answer
> 0 votes
You are allready on the right path, `Viewport` and `Camera` are what you are looking for.
If you take a look at the different `Viewport`types, there are some, which support virtual screen sizes. That means, that you can say how big your `Viewport` is and `Libgdx` will "scale" it up to the Game-Window (or to the screen, if fullscreen).
So when creating a `Viewport`, all you have to think about is, how many units i want to see on screen at one time.
If you, for example, have a human-like character (about 2m tall), and you want him to use 1/10 of the screen-height, the your virtual screen height would be 20 (character-height/screen-height = 1/10).
Also think about the aspect ratio. Most PCs nowadays have a 16/9 aspect ratio, while mobile devices might have different aspect ratios.
There are different `Viewport`-types, with different solutions to this: \- `FitViewport` keeps aspect ratio, by showing black borders on the sides or on top and bottom, if aspect ratio is different.
\- `StretchViewport` stretches the frame to use up the whole screen, no black borders will be shown.

There might be other `Viewport` types with different solutions for this, but i guess those are the most important types.

The `Camera` instead is used to show different parts of the world, you can simply move it arround using world units.

And as you allready said, you can convert pixels to worldunits and vice versa, by using `viewport.project` and `viewport.unproject`. This is used for touchinputs for example, as they are given in screen coordinates.

---
Tags: libgdx
---


title: To FX or not to FX

text:
# Question
Title: To FX or not to FX
General confusion... I'm not using Effects11 yet.

**Regarding the sorting/grouping induced by filenames:**

Initially I had them grouped by shader type:
SomePurpose1.hlsli
SomePurpose1\_SubPurpose1.hlsli
VS\_SomePurpose1.hlsl
VS\_SomePurpose1\_SubPurpose1.hlsl
GS\_GenericPurpose1.hlsl
GS\_SomePurpose1.hlsl
PS\_SomePurpose1.hlsl
PS\_SomePurpose1\_SubPurpose1.hlsl

Different parts of one "effect" were separated, so I reorganized:
GS\_GenericPurpose1.hlsl
SomePurpose1\_VS.hlsl
SomePurpose1\_GS.hlsl
SomePurpose1\_PS.hlsl
SomePurpose1\_SubPurpose1\_VS.hlsl
SomePurpose1\_SubPurpose1\_PS.hlsl

**Regarding whether I need, "need", or even want to use Effects11:**

I'm going to have 100's of shader blob files by the end of it; is this the "line in the sand" that defines moving to "effects", rather than using the individual blobs?

It would be 1000X better as:
GS\_GenericPurpose1.hlsl
SomePurpose1.fxi
SomePurpose1.fx
SomePurpose1\_SubPurpose1.fx

I'm familiar with XNA Effects and I've, now, mastered manually juggling the blobs, states and buffers in C++ without Effects11. To cure the number-of-files bloating and to make it easier to manage, overall, I think I "need" to use Effects11. XNA let me produce results without understanding, or even knowing, what I was actually doing. Now that I know better, I want to make sure my basics are solid.

I'm using the DX ToolKit helpers which defines some common states:
Where applying DepthDefault fully configures the depth-stencil-state, I conceptualize Effects, in general, doing the same job, except that they fully configure the "shader-state", i.e. applying all of the individual shaders, shader resources, etc, etc, etc, all as a one-shot call to Apply().

1. Is that an accurate summation? If so, using Effects is just going to allow me to collect all of the individual state calls into fewer Effect calls.
2. The same amount of calls need to be made, regardless of how they're initiated, so I'm assuming an "Effect" doesn't really incur any performance penalties. Is there an increase/decrease in overhead using Effects11?
3. Are there any subtle or hidden benefits/caveats?

# Answer
> 3 votes
First, Effects 11 is deprecated, or rather the HLSL profile you need to use it (`fx_5_0`) is deprecated. You can use still it with the Windows 8.x SDK copy of D3DCompile, particularly if you are using the GitHub open source version of the FX11 library as long as you are comfortable with this caveat. You don't 'need' to use it, but some people have found it useful and there are many older books that make use of it.

The main value in the Effects library (FX9, FX10, FX11) is allowing you describe in the `.fx` file the combination of shader programs you want to use in a grouping (aka technique) along with some associated state. Without Effects, you just need to coordinate between your HLSL shaders, your content, and your C/C++ code that does the rendering.

The problem is that the FX solution doesn't really scale well, and it's generally better in large games and applications to have your own bespoke material and state management anyhow.

If you are using DirectX Tool Kit, you can get a long way just using the existing 'canned' shaders in `BasicEffect` et al, perhaps adding some custom pixel shader or vertex shader where the stock stuff doesn't do what you want. It's certainly enough to get you going while you learn all the other aspects of Direct3D 11 programming as well. See the DirectX Tool Kit tutorial Writing custom shaders.

You could also try using the built-in VS DGSL shader visual editor which DirectX Tool Kit supports with `DGSLEffect`. It's kind of 'toy' as well, but you can experiment with it and use it to learn HLSL by example. See DirectX Tool Kit tutorial Creating custom shaders with DGSL

---
Tags: shaders, directx
---


# Question
Title: Touchscript: multiple overlapping colliders
Im building a tower defense game on unity and would like to allow the player to pan the camera on a large map. I am using touchscript to handle the touches.

I made a testing project with the following hierarchy
Main Camera
Panning object
Sprite

I am using the pan gesture to move the panning object which then sets the main camera's position to negative of the panning object's corrds.

So far, the things that should work worked properly. There is however the issue that the sprite object is higher up the layer and thus take priority. This means that if the viewport is filled with the sprite object, you are no longer able to pan as you cant touch the panning object behind the sprite object.

So the question is,
1. How does touchscript handle layering?
2. How can one achieve a passthrough effect where the sprite would handle tap gestures and the panning object handles pan gestures?
3. Can anyone suggest a better touch system for what im trying to do other than touchscript?

Thanks

# Answer
By using raycast, you can accept touch gesture per layer (see unity Raycast documentation). I think it's better to put panning object and your sprite on different layer. Then you may check for raycast colliding with your panning object and sprite.

I think it's better to use different touch gesture, like tap for interacting with sprite and sliding fingers across screen to trigger pan (by checking touch.phase)
> 1 votes

---
Tags: unity, 2d, touch
---


# Question
Title: What do I need in order to receive payments from Valve?
I'm developer from Russia and I recently passed Steam Greenlight.

Now I'm stuck on the Valve program enrollment phase. From what I've seen in the Valve forms, it is not necessary to create a company, such as LLC, there is 'Sole proprietor' option here. So I decided to choose this.

The questions were easy, but then I bumped into two stoppers: information about my bank account and information related to taxes.

As for taxes, I think I understand what to do. I need to apply for EIN in IRS and then fill the form W-8BEN.

But bank account is the different beast. I cannot decide, which type of bank account to use. Will it be suffice to create simple bank account, like this you use in your everyday life? In which currency this account should be? In Russian roubles or in US dollars? Roubles are preferable to me, but it's not a problem to create USD bank account. I simply cannot decide which is better.

It will be great if some non-US (and maybe US too :) ) indie dev shared some knowledge about this. Again, my most important questions:

1) Are you using the 'Sole proprietor' option without creating any form of company? Is this indeed legal and acceptable?

2) Can you use ordinary bank account for the purpose of receiving payments from Valve? If yes, in which currency is this account of yours?

Please answer only if you are absolutely sure about it, e.g. you already using this scheme and received at least one payment from Valve.

Thanks in advance!

# Answer
> 8 votes
I am based in Japan, and I registered on Valve as a sole proprietor, with a secondary personal bank account (to keep the numbers separated), and with the default tax settings. I have not ran into any problems yet, but I'm not qualified to give legal or financial advice either in Japan, and much less in Russia. THIS IS NOT LEGAL ADVICE

To be honest with you, I don't know what you're going on about:

Is "Sole proprietor" legal? I am not qualified to answer this question. Ask a lawyer in your jurisdiction

Is "Sole proprietor" acceptable? If Valve lists it as an option, then I guess it's acceptable for them. I don't understand why they would provide such an option and not accept people who use it, but you should ask Valve instead

Can I use ordinary bank account? I don't know, ask your bank. You will need routing information, like bank name, account nummber, SWIFT code and so on. Double check what Valve asks you, and ask your bank if they can provide this information

What currency should I use? Supposing both options (USD and RUB) are available to you, you can legally use either, and you can provide routing information for either, then I guess that boils down to personal preference. What makes more sense for your needs? You may also want to ask your bank and a lawyer what is better for you

As you can see, none of the questions you asked can be answered by game developers. Ask Valve, ask a lawyer, ask your bank.

# Answer
> 3 votes
First, to get money legaly in Russia, you should registrate yourself as an Individual Entrepreneur. Under this procedure you will choose a Tax option and create a specific bank account. After this you close all your questions. And for currency - you can choose currency for your bank account, and if you choose roubles, income money will be changed to roubles by the course of the bank at the day of income. You should choose bank wisely if you are going to get income from foreign countries. It's better to consult with the lawyer (business consultant or financial consultant) from your city about this (please, be aware, lawyers (etc.) are just humans, and have different experience in each category of a field).

---
Tags: legal, steam
---


# Question
Title: What are the steps in creating app icon for ios?
I have completed developing my game (iOS) and now preparing it to submit to the appstore. However, i have some confusion regarding app icon.

1\>In Unity build-\>player settings, there are various sizes mentioned. Largest size is 180x180 px. But i read somewhere apple requires 512x512 px icon.

2\>Is the build--\>player settings the only place where i provide app icons or are there more steps involved in xcode? If there are, please provide link to some documentation.

Thanks.

# Answer
Here is an official tutorial by Unity http://m.youtube.com/watch?v=C3izqF6h\_aY
> 1 votes

---
Tags: unity
---


# Question
Title: Why does my ball always bounce perpendicular to walls?
I'm using Box2D.

I think it's something to do with wall's fixture definition, but when a ball goes toward a wall at a 45 degree angle, I would expect it to bounce off at 135 degrees, but it always goes 90 degrees against wall. Why would this be?

# Answer
> 4 votes
I was setting a large restitution value (greater than 1), that caused the problem.

# Answer
> 3 votes
I know this is an old question, but I've just come across this solution and found that making sure restitution is not above 1 is not enough. friction also caused differentiation in the angle of which it bounces off. so setting friction to 0 allowed me to bounce a ball up against a 45\* wall and get the expected perpendicular reaction.

---
Tags: physics, box2d
---


# Question
Title: What does D3DXOptimizeFaces function do?
I know that this function generates an optimized face remapping for a triangle list, but what actually this optimized remapping is? The triangle faces are remapped, but based on what?

# Answer
It reorganizes the mesh data to achieve a better vertex cache hit rate by trying to group adjacent faces together in the buffer. The specifics of the algorithm are probably intentionally vague, so as to provide the possibility for the algorithm to have been updated or tweaked over time.

I believe it is (or at one point was) based on the work presented in Hugues Hoppes' 1999 SIGGRAPH paper, "Optimization of mesh locality for transparent vertex caching", which

> \[presents\] two reordering techniques, a fast greedy strip-growing algorithm and a local optimization algorithm. The strip-growing algorithm performs lookahead simulations of the cache to adapt strip lengths to the cache capacity. The local optimization algorithm improves this initial result by exploring a set of perturbations to the face ordering.

The algorithm involves considering all mesh faces "unvisited," picking an initial face with the fewest neighbors, and trying to grow a triangle strip from that face. At each step, if there are adjacent faces, the algorithm runs a number of lookahead simulations to see how adding a face would impact the vertex cache (basically, if it would overflow the size of the cache). If possible it tries to grow the strip until it optimally fits in the vertex cache. If it would overflow or if there are no more adjacent faces, the algorithm restarts, choosing a new face. When possible new faces are chosen such that their vertices are already in the cache.

The second part of the algorithm involve perturbing the ordering of the face sequence and measuring the change in cost; the best perturbation for the vertex cache cost is chosen.

The related `ID3DXMesh::Optimize` function can perform other, more explicit optimizations to the mesh. `D3DXOptimizeFaces` is very similar to calling `Optimize` with the `D3DXMESHOPT_DEVICEINDEPENDENT` flag, which uses a vertex cache size assumption that works better on older hardware.
> 2 votes

# Answer
Disclaimer: This is speculative. The DX specification doesn't define what it does, so it could be doing just about anything.

That said The Wine implementation might provide some insight. That actual function implementation starts on line 7173, and I would like to note the text just below that:

> The face re-ordering does not use the vertex cache optimally.

One possible optimization that could be performed, highlighted by that, is grouping indices that use the same vertex. Your GPU, like most CPU's, probably has a catch on it's processor of data recently accessed from your VRAM. Reading from that catch is much faster than polling data from RAM.

So by grouping indices, you group all accesses to that part of RAM. So over the course of drawing a 2000 triangle mesh, you will only need the GPU to read each vertex from RAM a total of once. If it's unoptimized, you might need to read it once in the beginning, once in the middle, and once at the end. Coming to an unoptimized total of 3 times that you'd be polling the same data from VRAM.

*Bonus fun snippet (likely not implemented by DirectX)*

You could group triangles based on normal direction. By doing this, you could batch the back-face culling operation. That could save you from processing thousands of triangles that are likely facing away from the camera, and do it all with a single if statement.
> 3 votes

---
Tags: optimization
---