# Question
Title: Unity seperation of prefabs with two dimensional terrain generation
I have the following function:

```
public void Spawn ()
        {

                GameObject g = ((GameObject)Instantiate (hills [Random.Range (0, hills.Length)], new Vector3 (0.0f, transform.position.y, transform.position.z), Quaternion.identity));
                g.transform.position = new Vector3 ((subs [subs.Count - 1].transform.position.x + (g.renderer.bounds.size.x) + (subs [subs.Count - 1].renderer.bounds.size.x) / 2), transform.position.y, transform.position.z);
                g.transform.parent = this.transform;
                NonLoopingScrollScript nls = (NonLoopingScrollScript)g.GetComponent ("NonLoopingScrollScript");
                nls.Setup (movSpeed, 0.0f);
                subs.Add (g);

        }

```

Which is being used to spawn terrain, the way this works is I have an array(hills) which is composed of a bunch of prefabs which together will make up terrain in the background of the game. This function is what actually instantiates the next prefab when it is needed, this prefab is then added to a list (subs). My problem is simply the spacing between the prefabs as I would like there to be no space, yet sometimes the objects overlap or there is a gap between the prefabs.

Explanation of code: In the first line I instantiate a random prefab with the argument:

```
hills [Random.Range (0, hills.Length)]

```

The next argument is where I am having trouble, what I am currently doing is setting the x value of the new prefab to the x value of the transform plus half the x width of both the previous prefab, and the new prefab. This is the issue as the spacing is not as desired. Then i simply set the y and z value to that of the spawner object and the rest of the code is irrelevent, save for where at the end of the function I then add the new gameobject to the end of the list.

I hope this was clear, if not please do not hesitate to ask questions.

Edit: The seperation of the prefabs works fine when there is only one type of prefab, but when I have several it doesn't. Here is an image of what I mean:

# Answer
> 0 votes
I’ve been using tk2d so I might be missing something crucial, but it seems like you want:

```
g.transform.position = new Vector3 ((subs[subs.Count-1].renderer.bounds.max.x + g.renderer.bounds.extents.x),transform.position.y,transform.position.z);

```

`subs[subs.Count-1].renderer.bounds.max.x` should get you the right edge of the previous hill sprite, and `g.renderer.bounds.extents.x` will get you an offset half the width of the new hill sprite.

This assumes that your sprite prefabs are centered over the transform position. If they’re not you'll need to adjust the offset part. E.g., if the `g.transform.position.x` represents the left of the sprite, then you could just set the Vector3's x to `subs[subs.Count-1].renderer.bounds.max.x`

---
Tags: c#, 2d, unity, terrain, random
---


# Question
Title: Why does my PixelShader ignore color but respond to alpha changes?
I started teaching myself some DirectX a short time ago and found something I'm confused about. For some reason, I can only get the color of the model I'm drawing to vary between black and white, depending on the alpha that I set inside the shader.

This is my `PixelShader` (which compiles successfully during runtime):

```
float4 PS( VS_OUTPUT psInput ) : SV_Target
{
    return (1.0f, 0.0f, 0.0f, 1.0f);
}

```

Given the components are `r,g,b,a` and I'm giving them `1,0,0,1`, this should return bright red! Instead, it produces this white area:

I haven't set a blending state.

What am I missing?

# Answer
> 4 votes
You need to write:

```
return float4(1.0f, 0.0f, 0.0f, 1.0f);

```

The `float4` is necessary to construct a vector. The way you've written it currently, the compiler is interpreting it as the comma operator. The result is that you only return the last element (the alpha component), which then gets replicated to all four components of the result.

---
Tags: c++, shaders, hlsl, directx11, alpha-blending
---


# Question
Title: How can I GL_SELECT from a gluPerspective-transformed scene?
I'm using JOGL to access OpenGL-methods on an old OpenGL version, because of school.

I have written a method which is called before any objects are drawn. This method shows which object is picked.

Before I call my "picking" method, I draw a camera. This is where the problems begin: I can't click precisely on the objects, because they don't know they are transformed by the camera. I have tried to leave the projection matrix unchanged, but this leads to other problems...

I first draw the camera, then do picking, then draw the objects to screen.

What am I missing?

---

My camera:

```
public void draw(GL2 gl) {
    GLU glu = GLU.createGLU(gl);
    gl.glMatrixMode(GL2.GL_PROJECTION);
    gl.glLoadIdentity();

    glu.gluPerspective(viewingAngle, whRatio, 1, 1000);

    gl.glMatrixMode(GL2.GL_MODELVIEW);
    glu.gluLookAt(xPos, yPos, distance, 0, 0, 0, 0, 1, 0);
}

```

My picking method:

```
private void picking(GL2 gl) {
    if (currentClickPoint != null) {
        int buffSize = 512;
        int[] select = new int[buffSize];
        int viewport[] = new int[4];
        IntBuffer selectBuffer = newDirectIntBuffer(buffSize);

        gl.glGetIntegerv(GL2.GL_VIEWPORT, viewport, 0);

        gl.glSelectBuffer(buffSize, selectBuffer);
        //gl.glMatrixMode(GL2.GL_MODELVIEW);
        gl.glRenderMode(GL2.GL_SELECT);
        gl.glInitNames();
        //gl.glPushName(-1);

        gl.glMatrixMode(GL2.GL_PROJECTION);
        gl.glPushMatrix();
        gl.glLoadIdentity();

        glut.gluPickMatrix((double) currentClickPoint[0],
                (double) (viewport[3] - currentClickPoint[1]),
                10.0, 10.0, viewport, 0);

        //gl.glOrtho(0.0, 8.0, 0.0, 8.0, -0.5, 2.5);

        gl.glMatrixMode(GL2.GL_MODELVIEW);
        drawObjects(gl, GL2.GL_SELECT);

        gl.glMatrixMode(GL2.GL_PROJECTION);
        gl.glPopMatrix();
        gl.glMatrixMode(GL2.GL_MODELVIEW);
        gl.glFlush();

        selectBuffer.get(select);

        interpretClicks(select, gl.glRenderMode(GL2.GL_RENDER));

        resetClickPoint();
    }
}

```

# Answer
> 1 votes
According to the `gluPickMatrix` docs, this function is designed to be used in tandem with your normal projection matrix. In other words, it shouldn't *replace* the normal projection matrix as your code does, but be combined with it.

The docs suggest using the following sequence of calls to set up the picking matrix:

```
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
glut.gluPickMatrix(...);
glu.gluPerspective(...);

```

The `gluPerspective` call would have the same arguments as in your normal camera setup. The modelview matrix should also remain the same as in the normal camera setup.

---
Tags: opengl, transformation, picking
---


# Question
Title: When one should use events in Unity and how they impact performance?
let's say that inside an ***OnGUI()*** script we want to call a method from another script to handle a particular situation. From a prestational point of view, what's the difference between these 3 approaches?

1.

```
    public class SomeClass : MonoBehaviour{

        ...

        void OnGUI(){
            if(something)
                 otherClass.heavyWorkMethod();
            ...
        }
    }

```

2.

```
public class SomeClassCoroutine : MonoBehavior{

    ...

    void OnGUI(){
        if(something)
            StartCoroutine("someClassCoroutine");
        ...
    }

    IEnumerator someClassCoroutine(){
        otherClass.heavyWorkMethod();
        ...
    }
}

```

3.

```
public class SomeClassEvent : MonoBehavior{
    public delegate void SomeAction();
    public static event SomeAction OnEvent;
    ...

    void OnGUI(){
        if(something)
            OnEvent();
    }
}

```

Where in the third case, the ***heavyWorkMethod*** in ***OtherClass*** gets called when the event ***OnEvent*** is fired.

Thanks for your time. Looking forward to read your answers.

# Answer
> 2 votes
(1) is just a normal method call.

(2) is a Unity Coroutine. You should only use it when you need the special abilities that coroutines grant you *(basically, when you need the execution of a single method to last multiple frames)*

(3) is normal C# event. You can read about events in any book or tutorial on C#, but without getting into too much detail: they're used to signal that some event has occurred. This allows the users of your class to decide which events they care to handle, and which they don't. It's also a way to call methods higher up in the call-hierarchy.

*(Note that it's very unusual to have a static-event. In every case I can think of that you'd use a static event, using a service would be better design)*.

---

There is a fourth option you missed: Unity Messages. A message is similar to an event that all other `Component`s attached to that `GameObject` are automatically subscribed to. This allows your component to publish an event without other components having to explicitly subscribe to it. Functions like `Start()`, `Awake()`, `OnGui` etc. are all messages.

---
Tags: unity, performance, events
---


title: QuadTree treeNode design question

text:
# Question
Title: QuadTree treeNode design question
I'm a programming newbie.

I have a Quadtree. I created a TreeNode class that the Quadtree will use as nodes. I have spriteNode that inherits from TreeNode.

However, I also have several sprite types inheriting from a Sprite class that I use to instantiate specific sprites.

When I am creating spriteNodes for example I have to cast each specific sprite type to it's parent Sprite class. When I put spriteNode into the quadtree I have to cast the spriteNode to be of type TreeNode so I can generalize the quadtree as much as possible to take different types of data.

I'm not sure if this is a great way of storing all your sprite / map data inside a quadtree, because setting it up requires a lot of explicit casts (even though cast up a level are safe).

Is my OO design approach to storing sprite / map data inside the quadtree the correct way to handle a large quadtree of data? Or is there a better, more standard way of doing things?

# Answer
> 2 votes
I'm not really an expert in quadtrees, I only coded one in my life, so I may be wrong.

However, to do what you say, you could use an Interface like IWorldObject and assign it to every object you want to insert into the quadtree. This way you just need to keep a list of IWorldObject and need no casting (assuming you implement all the needed methods in the interface).

However, if every sprite class has unique methods that you need when taking out data off the quadtree, you will still need to cast to the appropriate type.

---
Tags: xna, game-design, monogame, oop
---


title: Adding an angle variance to a 3d vector

text:
# Question
Title: Adding an angle variance to a 3d vector
I am converting a particle emitter from 2d to 3d.

In the 2d system the original coder used a random angle variance and added it to the angle. So it would be something like:

```
thisAngle = emitterAngle + angleVariance * RANDOM_MINUS_1_TO_1();

```

I want to do the same thing in 3d using an emission vector (vec3) and again an angleVariance. My specific variance for this particle will still be angleVariance * RANDOM\_MINUS\_1\_TO\_1(). But how do I apply that angle a 3d vector so that the new vector could be any value X degrees off of center. So if the original vector is straight up (0,1,0) the new vector could be off in the X or the Z and still normalized to 1.

Any hints? I have all the matrix and vector functions at my disposal.

=====

Thanks to nathan I was able to write this code. Not sure if I've over complicated it somewhere. Once I test it I'll checkmark his answer:

```
    // first pick a random Z from [cos(angleVariance), 1]
    GLfloat varianceZ = [self randomFloatBetween:myCosf(angleVariance) andLargerFloat:1.0];
    // and a random angle for the azimuth
    GLfloat rndA = [self randomFloatBetween:0.0 andLargerFloat:360.0];

    // then calculate the X & Y to make this a vector off of the +Z axis with a max width of angleVariance
    GLfloat varianceX = sqrt(1 - varianceZ*varianceZ) * myCosf(rndA); // my functions input degrees not radians
    GLfloat varianceY = sqrt(1 - varianceZ*varianceZ) * mySinf(rndA);

```

Up to here the above code works. It makes a variance angle off center but it is aligned to the +z axis. The next part is supposed to rotate/transform the angle to my emissionVector angle so it's a variance off of that. But so far this part isn't working.

```
    // next find an axis to rotate the point around to put it in line with the emmissionVector
    vec3 rotationAxis = normalizeVec3(crossProduct(vec3Make(0.0, 0.0, 1.0), emissionVector));
    GLfloat rotationAngle = acos(degreesToRadians(emissionVector.z));

    // make a quaternion out of the rotation axis and angle
    vec4 q = quaternionVector(rotationAxis, rotationAngle);
    // turn the quaternion into a matrix
    mat4 rotMat4;
    mat3 rotMat3;
    matrixQuaternion(q, rotMat4);
    getMat3FromMat4(rotMat4, rotMat3);
    // multiply the variance vector by the matrix to get a resulting vector with the variance added
    vector = matrixTransformVec3(rotMat3, vec3Make(varianceX, varianceY, varianceZ));

```

=====

The above code doesn't appear to be correct. I'm still working on the solution and will fix the above code when I get it working.

# Answer
> 1 votes
There is a formula for picking a random point on a sphere which can be adapted for your purposes. Generating a random point on a sphere can be done by picking a z-coordinate *uniformly* at random in \[–1, 1\], then selecting a random angle θ in \[0, 2π\] and calculating:

```
x = sqrt(1 - z^2) * cos θ
y = sqrt(1 - z^2) * sin θ

```

This can be extended to pick a random point on a spherical cap with any angular width, by simply choosing z uniformly at random within \[`cos(angleVariance)`, 1\] instead of \[–1, 1\]. Then apply the preceding formulas for x and y as usual, and you'll end up with a random point distributed around the +Z axis but staying within `angleVariance` of it.

Finally, you can rotate the resulting point to align the +Z axis with your desired emission vector. To do this, you can rotate around the axis `normalize(cross(float3(0, 0, 1), emissionVector))` by the angle `acos(emissionVector.z)`.

# Answer
> 1 votes
In the 2D case your random values could be sampled from an arc/half a cricle and you have only a one degree of freedom. In the 3D case you can sample half a sphere, so in this case we need to use spherical coordinates.

Let's assume we have X,Y,Z in Cartesian coordinates, and r, theta, and alpha in spherical coordinates.

Recall that

* x = r * sin(theta)\*cos(alpha)
* y = r * sin(theta)\*sin(alpha)
* z = r * cos(theta)

Assuming r is 1 (unit sphere), now we have 2 variables we can choose randomly theta and alpha. According to mathworld it is incorrect to sample alpha and theta to be \[0,pi) and \[0,2pi) because the samples will bunched on the polars. so they suggest the following function, which guarantees every part of the sphere to be applicable,

* theta = 2 * pi\* u
* alpha = cos\_inv( 2\*v - 1)

Where u,v are chosen randomly between (0,1). Now inorder to limit the selection to the half of the sphere, you can simply drop 2 in the `theta = 2 * pi* u` to become `theta = pi* u`.

I also came by this interesting article which might be of use.

---
Tags: ios, vector, opengl-es2, particles
---


# Question
Title: Is there a way to make money from indie downloadable games?
It appears that there are ways to make money with flash games through portal and aggregator sites and embedded ads.

But I do my programming in C and C++. I've started a prototype which relies on a few existing C++ SDK's. The game would have to be downloadable. Is this just a labor of love, or are there any ways to make money from this type of game? Does anyone pay for shareware anymore? What other options are there?

# Answer
> 6 votes
There's a few choices that I can think of:

* Sell your game on a portal, such as bigfishgames.com. It's not for everyone - you lose a degree of control, and the content on these places is decidedly casual. However, they get a lot of traffic and take care of the business of selling.
* Sell your game on a console based portal, such as XBox Indie Games. The problem with this is you end up having to sell a lot of games at a very low price (usually around the $1 mark).
* Sell them yourself. This is probably the hardest, but is the best long-term strategy. A good example of this is Positech Games. Cliffski has been doing this for a long time, and has built up a following over the years. Spiderweb Software is another good example.

# Answer
> 5 votes
Make a really good game. Get it on Steam. Market it effectively (generate enough buzz on gaming websites/forums)

But the most important step is making a really good game.

Kind of surprising to see suggestions of 'go for mobile development', given how oversaturated with $0.99 titles the iPhone app store is these days? - might have been a great idea 2 years or so ago - but isn't that gold rush well and truly over? - or have the new Apple devices re-ignited it?

# Answer
> 3 votes
I imagine most people don't create indie games necessarily to make money. If they are thinking that way a lot of people might be thinking in long term monetary gains. IE they would rather put a game down on their resume that shows they have experience making a game which could possibly give them a leg up on others who don't. Then you can say you started to make money from your indie game when your employer tells you it was your game you listed on your resume/cover letter that set you apart from others.

You also got to consider the crowd that your game will be bought by. The most impressionable gamers are probably the younger ones who can't afford games right away and must wait for something like a BDay/XMas or beg their parents to buy it. More than likely the only games they will be subjected too will be the heavy marketed games by those who throw millions into it. That leaves you with a smaller crowd of people who are more curious about what could be fun on an XBox/Mobile device etc. rather than actively seeking out the best indie game ever made. You might even then be hard pressed getting someone to pay more than $5 for a game if they think they won't play it more than a couple of hours or while they are on a plane or something.

You also must consider that anyone you distribute your game through is probably going to take a cut of your profits as well. Someone may say they have the tools to advertise your game but they sure aren't going to let you use them for free when there are 100's of other good indie games out there that can be sold as well.

So all in all if you are trying to get into indie games for money you probably have the wrong idea. I think the best thing to do is put it down on a resume. If you think it gives you a leg up in the hiring process then it definitely has a positive expectation on your future monetary gains.

# Answer
> 3 votes
You could sell the game e.g. via

# Answer
> 2 votes
Apart from selling it, see:

Is there any way to earn money with an open source game?

I realize this isn't strictly an open source game but many of the concepts above apply.

# Answer
> 0 votes
The indie market isn't that great for game programming unless you do something that is not desktop specific (mobile is a good option).

The problem:

Think in the eyes of the user here. You have the option of getting a game from a well-known company or a some person you've never heard of before. Also, its just that one person vs. a team of people.

The answer:

You could go to a mobile device like iPhone or Android. They emphasize the fact (and even pushed it out to the non-programming world a little bit too) that indies can now make great programs to with their help (which is their APIs and Frameworks).

Also, for mobile development in particular, I know a lot of friends in high school that just think that phones can't really handle the power of really popular games (which is true) and therefore make the conclusion that you only need one or two people to make a very good game for that platform that they would buy.

So, I would just switch over to another thing like iPhone or Android and use their RAD (Rapid Application Development) technologies.

# Answer
> 0 votes
If you plan to work on it for some time you could also try "open development". Release an alpha version soon, and try to get some people to play the game - for free, at least in the beginning. After some iterations and updates you could go for a subscription service. Or maybe you even find people to work with, that way. If it doesn't pan out, you can still open source the game and make fame instead of money.

Check out Wolfire's Overgrowth to see an example for open development: http://www.wolfire.com/

You can follow the same model on iPhone/Android but I'd discourage you from going mobile in the moment. Just like bluescrn says in his post: the market is so saturated that it's close to impossible to make a splash nowadays.

Why I'm arguing that you should go this way is because I think it is very hard to get your first game right. And even harder when you work alone. You'll need feedback. And the best way to get that is to build a - real or virtual - community.

---
Tags: marketing, monetization
---


# Question
Title: How can I maintain saved game backward compatibility?
I have a complex sim game I want to add save game functionality to. I'll be updating it with new features continually after release.

How can I make sure my updates don't break existing save games? What sort of architecture should I follow to make this possible?

# Answer
One easy-ish approach is to keep old loading functions around. You need only a single save function that writes out only the latest version. The load function detects the correct versioned load function to invoke (usually by writing out a version number somewhere in the beginning of your save file format). Something like:

```
class GameState:
  loadV1(stream):
    // do stuff

  loadV2(stream):
    // do different stuff

  loadV3(stream):
    // yet other stuff

  save(stream):
    // note this is version 3
    stream.write(3)
    // write V3 data

  load(stream):
    version = stream.read()
    if version == 1: loadV1(stream)
    else if version == 2: loadV2(stream)
    else if version == 3: loadV3(stream)

```

You can do this for the whole file, for individual sections of the file, for individual game objects/components, etc. Exactly what split is best is going to depend on your game and the amount of state you're serializing.

Note that this only gets you so far. At some point you might change your game enough that the save data from earlier versions simply makes no sense. For instance an RPG might have different character classes the player can choose. If you remove a character class there's not a whole lot you can do with saves of characters that have that class. Maybe you could convert it to a similar class that still exists... maybe. Same goes if you change other parts of the game enough that it doesn't closely resemble the old versions.

Be aware that once you ship your game it's "done." You might release DLC or other updates over time but they're not going to be particularly big changes to the game itself. Take most MMOs for instance: WoW has been maintained for many years with new updates and changes but it still is more or less the same game it was when it first came out.

For early development I simply wouldn't worry about it. Saves are ephemeral in early testing. It's another story once you get to public beta, though.
> 9 votes

# Answer
A simple way to achieve a semblance of versioning is to make sense of the members of objects you are serializing. If your code has an understanding of the various types of data to be serialized you can get some robustness without doing too much work.

Say we have a serialized object that looks like this:

```
ObjectType
{
  m_name = "a string"
  m_size = { 1.2, 2.1 }
  m_someStruct = {
    m_deeperInteger = 5
    m_radians = 3.14
  }
}

```

It should be easy to see that the type `ObjectType` has data members called `m_name`, `m_size` and `m_someStruct`. If you can loop over or enumerate data members during run-time (somehow) then when reading this file you can read in a member name and match it up to an actual member within your object instance.

During this lookup phase if you don't find a matching data member you can safely ignore this portion of the save file. For example say version 1.0 of `SomeStruct` had a `m_name` data member. Then you patch and this data member was removed entirely. When loading your save file you will come across `m_name` and lookup a matching member and find no match. Your code can simply move on to the next member in the file without crashing. This lets you remove data members without any worries about breaking old save files.

Similarly if you add in a new type of data member and try to load from an old save file your code may just not initialize the new member. This can be utilized to an advantage: new data members can inserted into save files during patching manually, perhaps by introducing default values (or by more intelligent means).

This format also allows the save files to be easily manipulated or modified by hand; the order in which the data members doesn't really have much to do with the validity of the serialization routine. Each member is looked up and initialized independently. This might be a nicety that adds a little extra robustness.

All of this can be achieved through some form of type introspection. You'll want to be able to query a data member by string lookup, and be able to tell what the actual type of data the data member is. This can be achieved in C++ using a form of custom introspection, and other languages might have introspection facilities built in.
> 5 votes

# Answer
This is a problem that exists not only on games, but also on any file exchange application. Certainly, there are no perfect solutions, and trying to make a file format that will keep with any type of change is likely to be impossible, so it's probably a good idea to prepare for the type of changes you may be expecting.

Most of the times, you'll probably be just adding/removing fields and values, while keeping the general structure of your files untouched. In that case, you can simply write your code to ignore unknown fields, and use sensible defaults when a value can't be understood/parsed. Implementing this is quite straightforward, and I do it a lot.

However, sometimes you will want to change the structure of the file. Say from text-based to binary; or from fixed fields to size-value. In such case, you will most likely want to freeze the source of the old file reader, and create a new one for the new file type, like in Sean's solution. Make sure you isolate the entire legacy reader, or you may end up modifying something that affects it. I recommend this only for major file structure changes.

These two methods should work for most cases, but keep in mind that they are not the only possible changes you might encounter. I had a case in which I had to change the entire level loading code from whole-reading to streaming (for the mobile version of the game, which should work on devices with significantly reduced bandwidth and memory). A change like this is much deeper and will most likely require changes in many other parts of the game, some of which required changes in the structure of the file itself.
> 2 votes

# Answer
At a higher level: if you're adding new features to the game, have a "Guess New Values" function which can take the old features and guess what new ones' values will be.

An example might make this clearer. Suppose a game modelling cities, and that version 1.0 tracks the cities' overall level of development, while version 1.1 adds Civilization-like specific buildings. (Personally, I prefer tracking overall development, as being less unrealistic; but I digress.) GuessNewValues() for 1.1, given a 1.0 savefile, would begin with an old level-of-development figure, and guess, based on that, what buildings would have been built in the city -- perhaps looking at the city's culture, its geographic position, the focus of its development, that kind of thing.

I hope that this can be comprehensible in general -- that if you're adding new features to a game, loading a savefile that doesn't yet have those features requires making best guesses as to what the new data will be, and combining those with the data you loaded.

For the low-level side of things, I'd endorse Sean Middleditch's answer (which I've up-voted): keep the existing load logic, possibly even keeping around old versions of the relevant classes, and call first that, then a converter.
> 0 votes

# Answer
I would suggest going with something like XML (if you save files are very small) that way you only need 1 function to handle the markup no matter what you put in it. The root node of that document could declare the version that saved the game and allow you to write code to update the file to the latest version if need be.

```
<save version="1">
  <player name="foo" score="10" />
  <data>![CDATA[lksdf9owelkjlkdfjdfgdfg]]</data>
</save>

```

This also means you can apply a transform if you want to convert the data in to a "current version format" before loading the data so instead of having lots of versioned functions lying around you would simply have a set of xsl files that you choose from to do the conversion. This can be time consuming though if you are not familiar with xsl.

If your save files are massive xml could be a problem, typically i've save files work really well where you just dump key value pairs in to the file like this ...

```
version=1
player=foo
data=lksdf9owelkjlkdfjdfgdfg
score=10

```

Then when you read from this file you always write and read a variable in the same way, if you need a new variable you create a new function to write it and read it. you could just write a function for variable types so you would have a "string reader" and a "int reader", this would only fial if you changed a variables type between versions but you should never do that because the variable means something else at this point so you should create a new variable instead with a different name.

The other way of course is to use a database type format or something like a csv file, but it does depen on the data you are saving.
> 0 votes

---
Tags: simulations, savegame, compatibility, patching
---


title: Slow Update to improve performance?

text:
# Question
Title: Slow Update to improve performance?
For my enemy AI, I only need decision making to be done every second or every half second. Would it make a meaningful difference if I didn't run the analyzing method in the Update, but rather invoked a SlowUpdate every second?

# Answer
> 2 votes
First and foremost, use a profiler and check what are the processor hogs in your game. Otherwise you are spending time augmenting and optimizing something that will not necessarily improve game performance noticeably.

If you already checked and are sure you wish to optimize AI to run a few times per second then in the abstract theoretical sense, you probably want to allocate 1/30 processor time for the AI to run asynchronously instead of lending it 100% of the processor time for 1/60 of a second. In practice in the pragmatic sense I would consider running the AI of different units in random varying times or breaking down the AI process into chunks or enabling the process to run 1-2 milliseconds, stop and pick up again later. This could be done by checking a timer in some pre-determined checkpoints in the program and if the time is up, storing the current relevant data and returning back to the main loop.

i.e.:

```
ai_work(){
    load_current_progress_state();
    while(work_left){
        do_a_little_bit_of_work();
        if(check_time_spent() > allotted_time){
            save_current_progress_state();
            return;
        }
    }
    return;
}

```

Running the code only once every X milliseconds would not necessarily yield the benefit you want because it could theoretically cause spikes in frame times.

---
Tags: unity, ai, performance
---


title: JavaScript character direction delay

text:
# Question
Title: JavaScript character direction delay
I am developing a top down game and I'm having trouble with a delay in switching from one character walk direction to another, particularly if the previous direction key is still being pressed by the user.

Take the following user interaction:

* User presses up arrow;
* User presses right arrow (up arrow is still pressed);
* User releases up arrow (right arrow is still pressed).

The problem I am experiencing is that there is a delay in the character switching from the "walk up" movement to the "walk right" movement.

```
requestId: 0,
settimeoutID: 0,
counter: 0,

move: function(keyCode) {
  var _this = this;
  // Frame per seconds
  var fps = 60;

  if (this.requestId === 0) {
    (function animationLoop() {
      // Control the timing of an animation with requestAnimationFrame
      _this.settimeoutID = setTimeout(function() {
        _this.render();
        _this.requestId = requestAnimationFrame(animationLoop, _this.move);
      }, 1000 / fps);
    })();
  }
},

changeAnim: function() {
  if (this.counter % 10 === 0) {
    if (this.currentFrame > 1) {
      this.currentFrame = 0;
    } else {
      this.currentFrame++;
    }
  }
},

render: function() {
  // Add some drawing
  this.counter++;

  if (keyCode === config.PLAYER_DOWN) {
    this.action = 'Front';
    this.newPos.y += 1;
  } else if (keyCode === config.PLAYER_UP) {
    this.action = 'Back';
    this.newPos.y -= 1;
  }

  if (keyCode === config.PLAYER_RIGHT) {
    this.action = 'Right';
    this.newPos.x += 1;
  } else if (keyCode === config.PLAYER_LEFT) {
    this.action = 'Left';
    this.newPos.x -= 1;
  }
  this.changeAnim();
  // Draw player logic
  this.drawPlayer.reDraw(this.playerSprite[1].Walk[this.action][this.currentFrame], this.newPos);
},

onKeyUp: function() {
  // Cancel the animation request
  if (this.requestId) {
    clearTimeout(this.settimeoutID);
    cancelAnimationFrame(this.requestId);
  }
  // Allow a new request to be called
  this.requestId    = 0;
  this.counter      = 0;
  this.currentFrame = 0;
  this.drawPlayer.reDraw(this.playerSprite[1].Walk[this.action][this.currentFrame], this.newPos);
}

```

Note: The function move gets called every time a new key is being pressed.

# Answer
As provided in the comments, if this is an issue of repeat delay then all you have to do is simply change your code to more of a state kind of process.

It might be a bit more code but its how you get things running

It could look like so :

```
   //variables
   var up = false;
   var down = false;
   var left = false;
   var right = false;

    //in your update

   if (keyCode === config.PLAYER_DOWN) {
    down = true;
  } else if (keyCode === config.PLAYER_UP) {
    up = true;
  }

  if (keyCode === config.PLAYER_RIGHT) {
    left = true;
  } else if (keyCode === config.PLAYER_LEFT) {
    right = true;
  }

  if(left == true)
  {
     this.action = 'Left';
     this.changeAnim();
     this.newPos.x -= 1;
  }
 else if(right == true)
 {
     this.action = 'Right';
     this.changeAnim();
     this.newPos.x += 1;
 }
//etc

```

It might look the same but unlike your key presses booleans are checked constantly without any delay. You're basically turning on and off by ONE key press.

This is an extremely simple way of doing it. And it should suffice. If you need something more complex simply look up how movement is handled in general.

( don't forget to set the variables to false on key up );
> 0 votes

# Answer
Thanks Sidar, for your feedback (https://gamedev.stackexchange.com/a/70458/22406). It has been a while since I've created character movement and I think I've lost the basics. I was creating an 'update' function only when the user was pressing down a key. This function was getting remove straight after the user has release a key. The issue was then linked the this way of updating the movement. I've managed to make it work this way:

```
upPressed: 0,
downPressed: 0,
leftPressed: 0,
rightPressed: 0,
currentFrame: 0,

// Only called once
update: function() {
  var _this = this;

  (function animationLoop() {
    // Control the timing of an animation with requestAnimationFrame
    setTimeout(function() {
      _this.render();
      requestAnimationFrame(animationLoop, _this.update);
    }, 1000 / config.FPS);
  })();
},

// Call on press
onKeyDown: function(keyCode) {
  if (keyCode == config.PLAYER_UP)
    this.upPressed = 1;
  if (keyCode == config.PLAYER_DOWN)
    this.downPressed = 1;
  if (keyCode == config.PLAYER_LEFT)
    this.leftPressed = 1;
  if (keyCode == config.PLAYER_RIGHT)
    this.rightPressed = 1;
},

// Call on release
onKeyUp: function(keyCode) {
  if (keyCode == config.PLAYER_UP)
    this.upPressed = 0;
  if (keyCode == config.PLAYER_DOWN)
    this.downPressed = 0;
  if (keyCode == config.PLAYER_LEFT)
    this.leftPressed = 0;
  if (keyCode == config.PLAYER_RIGHT)
    this.rightPressed = 0;
},

changeAnim: function() {
  if (this.counter % 10 === 0) {
    if (this.currentFrame > 1) {
      this.currentFrame = 0;
    } else {
      this.currentFrame++;
    }
  }
},

render: function() {
  if (this.upPressed == 1) {
    this.action = 'Back';
    this.newPos.y -= 1;
  }
  else if (this.downPressed == 1) {
    this.action = 'Front';
    this.newPos.y += 1;
  }
  else if (this.rightPressed == 1) {
    this.action = 'Right';
    this.newPos.x += 1;
  }
  else if (this.leftPressed == 1) {
    this.action = 'Left';
    this.newPos.x -= 1;
  }

  if (this.upPressed == 1 || this.downPressed == 1 ||
    this.rightPressed == 1 || this.leftPressed == 1) {
    this.counter++;
    this.changeAnim();
    // Redraw the background
    mediator.call(mediatorEvent.REDRAW_PLAYERS);
    // Draw user input on the map
    this.drawPlayer.reDraw(this.playerSprite[1].Walk[this.action][this.currentFrame], this.newPos);
  }
}

```
> 0 votes

---
Tags: javascript, animation, html5
---


# Question
Title: Slick2D: Initializing graphics object before game loop
I'm using the Slick2D Java game library and I want to set the scale of the graphics object that gets passed to the render method in my game loop. I'd like to do this outside the render method, so that I would only have to call the `setScale()` method once. I am implementing my game as StateBasedGame, so I'd to like to initialize my graphics object in my StateBasedGame class. Where would be the appropriate place to do this?

# Answer
> 2 votes
First, are you really sure to understand the concept of `StateBasedGame` of Slick2D? If you are not sure about it, here is a good introduction.

From here i see two potential ways to load your assets before running your game.

1. You could do it in your `StateBasedGame` implementation. You just need to write a kind of `loadAssets` method that get called before entering any state.
2. Create a dedicated state that will be in charge of loading your game assets. I think this is a better approach because it will allow you to implement a kind of loading screen (with a progress bar or whatever). Once you are done with loading, you can simply enter your game state which will run your game loop.

From here you may wonder how to share your assets between states? I'm not quite sure but i don't think Slick2D comes with an out of the box solution for managing assets so i think you will have to write your own.

A possible solution could be a singleton class like:

```
public class AssetManager extends HashMap<String, Object> {
    private static AssetManager _instance = null;

    private AssetManager() {
    }

    public static AssetManager getManager() {
        if (_instance == null)
            _instance = new AssetManager();
        return _instance;
    }
}

```

So you can feed it with your assets in your loading state:

```
AssetManager.getManager().put("asset_key", ...);

```

And request for a particular asset:

```
AssetType = (AssetType) AssetManager.getManager().get("asset_key");

```

I think this is the easiest way for managing your assets and if you want to improve it, you can find inspiration from the libGDX's AssetLoader.

---
Tags: java, lwjgl, slick
---


# Question
Title: How to work with smaller intermediate textures in OpenGL and GLSL?
I'm working on a project rendering water simulated through smoothed-particle hydrodynamics (SPH) with a non-photorealistic look to use in games.

In the actual stage of the project everything about this rendering is done through OpenGL and GLSL in C++, with many shader steps that stores intermediate textures in FBOs, which are later used in a final shader that brings everything together.

Everything is working fine, except for the framerate, which lies below between 25 and 30 FPS in the better case, rendering everything, including the intermediate textures, in 1024x768 pixels. So, since some of these intermediate steps involve image smoothing algorithms that are time consuming, I thought of reducing the dimensions of the textures generated in intermediate steps to make them faster, trying to find a sweet spot between the level of reduction/performance (divided by 2, 4, 8...) and the rendering final visual.

My question lies precisely here: How can I work with smaller textures in intermediate steps and use them on a final shader step to render to a image in a bigger dimension?

# Answer
> 1 votes
All you have to do is create the FBOs textures with the desired width and height and adjust the viewport accordingly when rendering, as shown in this Shadow Map tutorial by Fabien Sanglard.

First create the FBO and it's textures with the desired dimensions. Here `fbo_intermediary_colortexture` is the FBO id, `window_width` and `window_height` are what the name implies and `intermediaryTextureSizeRatio` is a float that tells how much the FBO texture dimensions should be reduced:

```
void createFrameBuffer()
{
    // Color texture
    glGenTextures(1, &fbo_intermediary_colortexture);
    glBindTexture(GL_TEXTURE_2D, fbo_intermediary_colortexture);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, window_width * intermediaryTextureSizeRatio, window_height * intermediaryTextureSizeRatio, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
    glBindTexture(GL_TEXTURE_2D, 0);

    // FBO
    glGenFramebuffersEXT(1, &fbo_intermediary);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo_intermediary);
    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, fbo_intermediary_colortexture, 0);

    // Test
    if (glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) != GL_FRAMEBUFFER_COMPLETE_EXT)
        cout << "Couldn't create frame buffer" << endl;

    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}

```

After that, when rendering, just adjust the viewport dimensions accordingly to where it's being done (in that case, first on the FBO, and then on the screen):

```
// Rendering on the FBO, first bind the created FBO and then adjust the viewport dimensions
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo_intermediary);
glViewport(0,0, window_width * intermediaryTextureSizeRatio, window_height * intermediaryTextureSizeRatio);

/** rendering to off screen FBO goes here **/

// Then bind the screen frame buffer, adjust the viewport dimensions again, and render
// Notice that the window dimensions are not being multiplied by the reducing factor here
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
glViewport(0,0, window_width, window_height);

/** rendering to screen goes here **/

```

You can check the generated textures dimensions with gDEBugger or some similar application.

One last thing: be warned that, as shown in the aforementioned tutorial, some artifacts may rise from a small texture being rendered on a bigger screen, which can be a bad outcome depending on the scenario.

---
Tags: opengl, c++, textures, shaders, glsl
---


# Question
Title: What image format supports transparency in Android?
I want to show an apple on screen but the image has a white background and it doesn't blend with the background of a tree.

Is there any image format in which only the red apple is displayed?

# Answer
**.png images** wont show the transparent area. But you will have to make sure that the "white" area is transparent and not white.

If its not a **.png** image just go in to photoshop or any other image editor, cut out (magic wand) the white area and save it as a **.png**
> 4 votes

---
Tags: android, graphics, transparency
---


title: drawing line using angle

text:
# Question
Title: drawing line using angle
code below make enemy move towards player.

```
    //Calculate Distance formula
    double xDiff = player.x - enemy.x;
    double yDiff = player.y - enemy.y;
    double dist = Math.sqrt(xDiff * xDiff + yDiff * yDiff);

    //find angle
    angle = (int) Math.toDegrees(Math.atan2(yDiff, xDiff));
    if (angle < 0)
        angle += 360;

    xDiff = xDiff / dist;
    yDiff = yDiff / dist;
    x += xDiff * speed;
    y += yDiff * speed;

```

how to draw line with length 20, same direction as enemy is moving?

```
enemy.x2 = angle?
enemy.y2 = angle?
draw(enemy.x1, enemy.y1, enemy.x2, enemy.y2);

```

# Answer
```
MyLineLength = 10
enemy.x2 =enemy.x1 + (xDif / dist)*MyLineLength //dist!=0 should be tested
enemy.y2 =enemy.y1 + (yDif / dist)*MyLineLength
draw(enemy.x1, enemy.y1, enemy.x2, enemy.y2);

```

You don't need to have the angle in order to draw the line if you already know the start and end positions (Vector from player to enemy) Using vectors what you do is to normalize vector, then multiply for length. Basically we did it using separated components.

Study more about vectors and you will see things more easy. Also avoid frequent calls to aTan2 function, is slow.

Anyway answering your original question, if you only have the angle then you'll use Cos and Sin functions (assuming `angle` in radians):

```
MyLineLength = 10
enemy.x2 =enemy.x1 + Math.Cos(angle)*MyLineLength
enemy.y2 =enemy.y1 + Math.Sin(angle)*MyLineLength
draw(enemy.x1, enemy.y1, enemy.x2, enemy.y2);

```
> 2 votes

---
Tags: coordinates
---


title: Compiling Quake 3 in Snow Leopard

text:
# Question
Title: Compiling Quake 3 in Snow Leopard
First of all I have Xcode 4 installed in Mac OS X Snow Leopard 10.6.8. I have downloaded the Quake 3 source code 1.32b release but I can't open the Xcode project that is inside the /macosx folder since it is in the old .pbproj format and therefore it throws an "incompatible version" error. Has anyone been able to convert this to a Xcode format or is there any other way to compile the source code in Mac OS X Snow Leopard?

Thanks

# Answer
The original Quake 3 source was released quite some time ago. I wouldn't be surprised if it's out of date.

I would suggest the ioquake3 version, except that I tried it recently on Leopard and the build failed for me. Your mileage may vary.

The ioquake there is essentially just bug fixes and maintenance work on top of the original quake3 source. If you just want to study the engine or do some prototyping it should be a better starting point than the original source that id released. Plus, it's in svn so you can get the history of changes if you need them.
> 3 votes

# Answer
try adding .xcode to end of the folder name. open it in xcode and save it as an xcodeproj
> 1 votes

# Answer
# Opening and browsing

To be able open project with latest XCode go through steps:

1. Download and install **Xcode 2.5 Developer Tools for Mac OS X v10.4 (Tiger) and Mac OS X v 10.5 (Leopard)** from developers.apple.com
2. Open code/macosx/Quake3.pbproj in XCode 2.5 and it will prompt you to save `.xcodeproj` project file
3. Open project in XCode 4/5 and browse the project
> -1 votes

---
Tags: macos, quake3
---


# Question
Title: What's the best way to time a character AI movement on android/java?
I'm creating an android game and I'm trying to figure out the best way to time a character position change, something like this:

```
public void move() {
    //this.posX += 5;
    this.posY += 5;

    if (posY < 350) {
    new Timer().schedule(new TimerTask() {
        public void run()  {
            this.move();
        }
        }, 300, 300);
    }
}

```

Is this the best way? I'm using `Canvas`. Thanks for your time.

# Answer
Try to stay away from using constants in your code as much as possible, mostly because when your game starts getting larger it will be easier to remember a variable named `playerSpeed` compared to a certain number. Not crucial but just a tip.

What is crucial however is to use delta time when u add speed to your objects, and when incrementing your timers. If you dont know what delta time is its just a quick google search away.

Another thing to keep in mind when designing for android is to use density pixels when you are working with positions on screen like `posY < 350`. (Again, try to find a suitable variable name for the int "350", good to get used to it)

Try something like this:

```
public void move() {
//this.posX += 5;
this.posY += objectSpeed*deltaTime;

if (posY < 350*dp) {
new Timer().schedule(new TimerTask() {
    public void run()  {
        this.move();
    }
    }, 300, 300); //dont know what these are but if positions add density pixels like above
}
}

```

Another tip is to create ur own timers, something I like to do. You can do this when you start learning more about delta time, it will look something like this:

```
aiTimer+=deltaTime;
if(aiTimer >= 2.0f){ //2 seconds
doStuff();
aiTimer-=2.0f;
}

```
> 0 votes

---
Tags: java, android, movement, html-canvas
---


# Question
Title: Picking random monster cards from a deck
What is the best way to go about making user defined classes (monsters, items, loot, armor, weapons, spell types, etc) and then calling them later during an encounter? Looking at the entire card list for a trading card game is intimidating, and I would love some advice on tackling this before I go about it the wrong way.

```
class Card(object):
def __init__(self, name, value, type, power):
    self.name = name
    self.value = value
    self.type = type
    self.power = power
    self.expan = 'Base'

class Monster(Card):
def __init__(self, name, value, type, power):
    self.active = False
    Card.__init__(self, name, value, type, power)
    #monsterlist.append((self.name, self.value, self.type, self.power))

```

Is it ideal to just make a random number and create the monster like this (there's over a thousand cards, so this doesn't seem optimal to me):

```
def pickMonster():
    chance = random.randint(1,2)
    if chance == 1:
        goblin = Monster('goblin', 8, 'animal', 'run')
    if chance = 2:
        troll == Monster('troll', 8, 'troll', 'smash')

```

Can I define monsters in a list/dictionary somehow and pull them at random from there? I was trying to use this method to make the code easier to read, but I'm having a hard time figuring out exactly how to do it that way (as I'm not even sure it's possible to put more than 2 values into a list, and dictionaries are the bane of my existence -- I'm fairly new to python).

# Answer
> 2 votes
> define them in a list/dictionary somehow and pull them at random from there?

Take this approach; not sure why you were having trouble figure out how to make a list for this. Also you may want your `Monster` initializer to simply take a dictionary passed to it, so that the list is a list of dictionaries you can pass that factory class. For example:

```
monsterList = [{'name': 'goblin', 'health': 8, 'type': 'animal', 'ability': 'run'},
               {'name': 'troll', 'health': 8, 'type': 'troll', 'ability': 'smash'}]

def pickMonster():
    monster = Monster(random.choice(monsterList))

```

---
Tags: python
---


title: How do I simulate a trampoline?

text:
# Question
Title: How do I simulate a trampoline?
I'm quite new to game development. I was pretty impressed with the elastic effect I saw in this flash game when the ball hits the trampolines and I'm wondering how to recreate it.

I've done some poking around and I've heard the term "vertlets" come up lots, but I think that's more for rope physics, not something with two anchor points.

How should I approach this?

# Answer
You don't need to search "verlets" or "verlet". For anyone else reading this: verlet is a mostly outdated type of integration in modern physical simulation. This sort of thing can be achieved in two dimensions whith custom (almost gameplay specific) code. The exact details of doing this sort of thing don't have to be very fancy (not that verlet is fancy at all).

I would imagine that rendering the rope would done separately from any physical simulation. Perhaps one way to fake the trampoline would be to apply a constant acceleration (or force) to the ball if the ball is "colliding" with the trampoline. The acceleration can be aimed towards the average of the two anchor points, or in other words the direction from the ball to the average of the two anchor points (a vector).

The collision detection and rendering of the trampoline should be harder than the manipulation of forces.
> 1 votes

---
Tags: collision-detection, box2d, physics
---


# Question
Title: 2D Rope with verlet and Semi-implicit Euler integration
I'm trying to create 2D rope. Chain based solution is not working pretty well, so I'm looking for new approach. Every good looking rope implementation is based on verlet integration, but this method is not good for rigid body based system. Is there any save method to combine these methods - ropes with verlet and rigid bodies with Euler? Basic requirement for method I'm looking for is proper (or good enough) collision detection for both of simulated bodies.

# Answer
> 1 votes
What I am trying to offer here is not exactly what you described, but could be "good enough".

The *proper rope* will be pretty an interesting challenge that will take some time to tackle.

I don't think that's what you need/want nor do I have such excellency to offer the solution. Instead I thought I leave you with more of "cheat"; this is how I would have done it if I needed "rope" in **rigid body based system**.

Gist is : Since you are in this rigid body system world, why don't you just make rope out of rigid as well?

Here let me explain what I mean with picture.

You could set boxs(red) to have fixed maximum length L to box next to it, then just let them roll in the world. This will be visually less appealing option to you. So here, you just hide those boxs from user, then instead draw a rope like visual effect(blue line that's going across the red boxs) onto it. Example below.

(in this picture, rope like visual is drawn based off of location of blue box. here in this example, the visual effect rope has many nodes to give it more fluid feeling)

For your rigid body rope, you will want to have many small boxs that compose the rope in order to gain more rope like behavior.

---
Tags: 2d, rope-physics
---


# Question
Title: isometric coordinates issue: (0,0) and (5,5) are flipped?
I am having an issue with the isometric coordinates.

When I enter the coordinates (5,5), the character should be at the bottom corner of the tile, but it is at the top corner, (5,5) and (0,0) look like they have been switched :

With (5,5), my character goes at the top instead of being at the bottom corner :

(The convertToScreen method is from : Isometric rendering and picking? )

```
//create isometric tiles
public Vector2 convertToScreen(float x, float y, int offsetX, int offsetY)
    {
            Vector2 screen;
            float TILE_WIDTH = 1;
            float TILE_DEPTH = 0.5f;
            //calculate the screen coordinates
            float _x =  offsetX - (y * TILE_WIDTH/2) + (x * TILE_WIDTH/2) - (TILE_WIDTH/2);
            float _y = offsetY + (y * TILE_DEPTH/2) + (x * TILE_DEPTH/2);

            screen = new Vector2(_x, _y);
            return screen;
     }

//in the "create" method
float valueCam = 10;
    camera = new OrthographicCamera(valueCam, valueCam * (Gdx.graphics.getHeight() / (float)Gdx.graphics.getWidth()));
    camera.translate(new Vector2(0,0));

    Vector2 conv = convertToScreen(5,5, 0,0);
    myCharacter.setPosition(conv.x, conv.y);

    public void renderMap(){
        float tileWidth = 1;
        float tileHeight = 0.5f;
        for (int x = 0; x < 5; x++){
            for(int y = 5-1; y >= 0; y--){

                Vector2 v = convertToScreen(x,y, 0,0);
                float x_pos = v.x;
                float y_pos = v.y;

                //float x_pos = (x * tileWidth*0.5f ) + (y * tileWidth*0.5f);
                //float y_pos = - (x * tileHeight*0.5f) + (y * tileHeight*0.5f);

```

(edit: the previous issue was the offset of x-1, fixed by changing the x\_pos and y\_pos as shown above)

# Answer
> 0 votes
The centre of the screen is x\_pos:0 y\_pos:0.

As you draw the tiles, y positive is 'upwards' on the screen.

So the code is now functioning correctly, but your perception of the tile positions is horizontally mirrored.

---
Tags: libgdx, isometric, coordinates, screen
---


# Question
Title: How to make part of the Texture not to be scaled.?
I am new to LibGdx, i was doing one example for my learning and struck with this question, i had searched in google but i am not able to find the answer for this.

1) How to make part of the Texture not to be scaled.

as you can see in the image i am reducing the height of bottom pipes so that the top pipe scale is reduced to fit the height given but i want the top part of the pipe not to be scaled.

in this example whole pipe is one texture, for fixing this problem i thought to split the top and body to separate texture and set height for only body but i thought there should be some other solution so that only i had put this question here.

# Answer
> 7 votes
Option #1: Split tubes into 2 parts, the tube and the rim. So that you stretch the tube to be as long as you need it and the rim part is always the same size.

Option #2: Make the tubes to be always the same length and hide the ends behind the walls.

# Answer
> 0 votes
You can scale the texture coordinates over the region of the texture that you want to manipulate.

Typically, your textures are drawn using linear interpolation ("lerp"), so the texture is evenly distributed / linearly scaled across the target polygon, like so:

However, you can manipulate this to give non-linear interpolation by changing your texture coordinates. For instance,

With that example, 1. the top two quad rows contain the top 50% of the texture. 2. The third row (from the top) contains 40% of the texture (from 0.5 to 0.9) 3. The last row contains only the last 10% of the texture

This causes the texture to be stretched.

This is flexible in that you can dynamically manipulate the texture coordinates, preferably in fragment shader. I'd pass in a uniform indicating how far you wanted the platform to extend vertically, and figure out the texel coordinates based on that.

The other option is to manipulate the vertex coordinates of the 3rd row to extend the platform, which will have the same effect. As long as you have "stretching" in your tex coords, you'll get the effect you are looking for.

---
Tags: textures, libgdx
---


title: Developing AI for Zatacka

text:
# Question
Title: Developing AI for Zatacka
I am trying to develop a stronger AI for the popular game, Zatacka. The basic aim of the game is to survive the longest. It's like the TRON game, but the characters can only turn smoothly, instead of 90 degree turns.

I am new to game AI. I have the following ideas in mind, but I don't know how they can be implemented.

* Collision prediction. If another player is about to come into the same area, then the player should turn around and try to evade.
* Hole taking capability. How to detect holes. How to distinguish holes from a normal empty area.
* Early detection of a dead end and being able to turn around before its too late. The problem with this how do we determine a dead end, it could be a bit far than our current position. Doing a path finding algorithm and searching for the wall or a player's body might not be efficient enough as this has to be done for each steps.

Are there any standard algorithms for these problems? Can somebody throw some light on how I can approach these problems?

# Answer
> 1 votes
First of all I would like to say that I completely agree with Willem, specially regarding the suggestion for you to start with a simplification of your problem and that game AI is "much about experimenting with ideas".

Particularly I find Willem's second approach to be more suited to the conditions of your game, in which the environment is very dynamic (specially with more players), making very difficult to plan much ahead. A rule-based solution may work quite well, allowing your agent to figure out the best course of action in a reactive fashion: each turn it can sense the environment (walls, holes and opponents positions) and choose an action that maximizes its goal.

But I would give a try to a solution based on (or inspired in) the subsumption architecture. The basic idea of this architecture is that the agent is composed of different behaviour layers (i.e. that take particular decisions) that are organized and evaluated in a stack from bottom to up. The most "primal" behaviours are positioned at the bottom, with the more general behaviours (that use the ones bellow) on top. All layers may be constructed with a set of finite state machines, producing outputs that may inhibit other layers. The final agent behaviour is the result of the many interacting behaviours.

In that way, your agent may have obstacle avoidance behaviours at the bottom, and opponent chasing at the top. Or something similar to that. :)

Here are some interesting readings:

# Answer
> 1 votes
Seriously think about is how can you simplify the problem. One simplification is to limit the game to two players (or even one). Another simplification is to use bigger and discrete turn angles and increase time steps. So instead of curves you have lines with corners. Such simplifications may or may not end up in your final AI, but it will help you explore the problem a bit better.

I can suggest two general approaches. These approaches may lead to some specific algorithms.

One approach is to search through a tree of possible future game states (such as A\* and minimax). Then based on this search, make an optimal move. Some future states would then predict collisions.

Another approach is to define a set of rules that decide a course of action. Then make an assessment of the current game state, apply the rules and get a course of action based on that.

If you get an understanding of both approaches, you will probably see that they can be combined in crazy creative ways :). AI is much about experimenting with ideas.

---
Tags: ai
---


# Question
Title: How do I render into a sub-region of a texture atlas with XNA / HLSL?
Is it possible to render into a texture atlas?

I've been wondering how to reduce the number of textures required for shadow-mapping, and came across a blog post here about rendering up to sixteen shadow maps into one texture-atlas.

According to the blog post mentioned above, these are the steps required:

1. The first step is writing to the texture; bind it to the framebuffer and set the viewport to render into the texture sub-region.

2. When accessing the sub-region, scale/bias the texture coordinates as follows: scale = region size / texture size, bias = region offset / texture size.

I understand this, but I'm not sure how to alter the viewport specifically to allow me to render into a certain square of the texture. I've found plenty of information about reading from it (up-sampling and down-sampling) but I don't know how I'd manipulate the viewport specifically to render into a small square region of the screen, and how I'd do this with a texture smaller than the back-buffer.

I'm using XNA and HLSL at the moment because it's simpler than SharpDX, and there's no point in messing around with that until I've got the theory working 100%.

Thanks for your help.

# Answer
> 2 votes
Set the `GraphicsDevice.Viewport` property to a new `Viewport` struct with the values you want. Set `X` and `Y` offset, set `Width` and `Height`. All these values are in units of pixels, so the size of the target texture doesn't matter.

Here is a simple code example. It uses separate cameras to accomplish different perspectives per viewport, but you don't need that portion. You only need the lines that assign different `Viewport`s.

---
Tags: xna, hlsl, texture-atlas, viewport
---


# Question
Title: How can I communicate changes to a 2D tile-based world state in a P2P context?
Suppose two players in a game want to build a city together on a blank tile-based game world *simultaneously* in a peer-to-peer connected context.

When a player clicks on a tile it changes the state (or tile ID) of that tile, which is saved into a text file for later reading by the renderer.

For example, in the image below a player has modified some tiles from "empty" (1) to "road" (2):

What method should I employ to transmit these changes to connected peer-to-peer clients?

# Answer
> 1 votes
You will need two mechanisms:

* First, you will need to be able to transmit the *entire* world state to a user. You don't want to do this regularly, but you will need it to transmit "initial" world states to users as they join the game or potentially at the very beginning of the game.
* Second, you will need to be able to transmit packets to all connected clients that notify them of state changes (deltas). Something of the form "change tile (1, 2) to state 3."

You mention this "text file" that you save the state into after every change; that seems unnecessary. Unless your levels are *massive* you should keep the entire state in-memory at all times, and share it with the renderer. Disk is one of the slowest forms of memory so having to hit it twice per frame on average is undesirable.

Since your game is running in a P2P context there is no central authority to validate the moves or resolve races (two players clicking the same tile at the "same time"). To help alleviate this, especially if your game is real-time and not turn-based, you can synchronize each player to a known good clock when the game starts, and have players transmit the timestamp on that clock with each move, which can be used to resolve races. This can also be done with a sequencing number, or consider an approach where every client gets a vote on the correct state of the game and that majority vote wins (this is sometimes useful in cheat detection as well).

Note that you may need to buffer some moves in memory on all clients to account for the possibility that other clients can "replace" locally-made moves.

---
Tags: tiles, multiplayer
---


# Question
Title: How do I detect a tile map collision's direction?
I'm implementing collision detection with the map for my platformer. I have a method that generates a polygon on every tile and checks if the player hits it -- that's all fine. The problem is that when ever a player touches a wall in front of him the `d` key which moves him to the front gets disabled so he can't walk any further that way.

This method works great for preventing him from walking into walls, but I also want him to be able to jump on the walls and there is the problem. So he falls on the tile(polygon) the game senses that and applies the same method for the `d` key, preventing the character from walking left or right, because the game thinks it is hitting the tile in the front but it is hitting from above.

Long story short, the game handles collision from above same as from the front or back. How do I make it recognise collisions from the side separately from above?

My code is along these lines:

```
if(PlayerPolygon.interesects(TiledPolygon) && dKey==1) {
         moveX = 0;
}
if(dKey==1) {
  player.x +=moveX
}

```

# Answer
> 0 votes
You ask how to detect collision on both sides. Well, that answer is simple. Detecting collision on multiple sides is simply a matter of saying 'Okay is he colliding on the left? What about the right? Top? Bottom?' The method you're asking for checks for collision on every side and then gives responses as to where collision occurs.

You're also handling your movement incorrectly. This can be a little bit tricky, but I'll walk you through it. In a game, it might sound easy to just write a piece of code like this to handle your movement

```
if (a key is pressed
{
    player.move();
}

```

But this ends up giving you a glitchy response and bad results with collision. Instead, you need to have several methods. One for detecting when the key is up, when for when the key is down, and one to detect the movement. Here's a rought sketch:

```
boolean keyIsPressed;

void isKeyUp()
{
    keyIsPressed = false;
}

void isKeyDown()
{
   keyIsPressed = true;
}

void detectMovement()
{
    if (keyIsPressed)
    {
        player.move()
    }
}

```

This will give you correct movement.

Now for collision that you're asking for. Essentially what you want is to detect collision on all 4 sides. So with the correct movement that I displayed above, you should make a method like

```
if (collisionOnLeft)
{
    handleCollision(left);
}

if (collisionOnRight)
{
    handleCollision(right);
}

if (collisionOnBottom)
{
    handleCollision(bottom);
}

if (collisionOnTop)
{
    handleCollision(top);
}

```

So because you're detecting collision on all 4 sides and then handling it accordingly, with proper movement, you will get proper collision response with multiple points. Note, I use an `if` statement for each, instead of using `if`, `elseif`, or `else`. The reason for this is because collision on each side should be handled separately, instead of grouping it.

---
Tags: java, collision-detection, tilemap, direction
---


# Question
Title: How to design a useful scripting system?
I have decided to use the Squirrel (probably doesn't matter much for this question) scripting language in my C++ project. I'm wondering how game developers usually handle scripting in their games. I've managed to run scripts, bind functions etc. - that is not the problem. I'm just not sure how a scripting system is actually implemented in a sensible way.

So far I have got a singleton ScriptManager, which owns a virtual machine and can interact with it.

Some specific questions:

* Does every functionality, that you want to control with scripts, need to be bound manually or can you somehow make all functions/classes available to your scripts? (I do not intend to use scripting everywhere in the final game, but it would make the development process a whole lot easier.)
* How should squirrel scripts be structured? Should they represent some kind of library, that you load, or just a set of commands that get executed whenever a game object wants to? If the former approach is better, how would such a library look like and how would the execution of the script be triggered?

I would be great if you could point me into the right direction! Thanks!

# Answer
> 3 votes
There's a few routes that you can take. Some include making an event type system where actions in your C++ code map to functions directly/indirectly in your scripting system. So, if you read that a player presses the up key in game, that will send an event to the scripting system that will then decide what to do.

You could also hard code certain actions and map the scripts directly to them.

Also, for data retrieval one might create a global class/singleton/etc to retrieve data from the game for usage in scripts (or pass through to functions)

Also, in terms of structuring, you could group them by action/category, so all of the player's scripts could go in one file/folder and then broken up by action and so on.

There's many games that have employed scripting (Garry's Mod:Lua, Battlefield series uses Python I think, TES uses their own system, etc.) Try looking through those and look at modding guides

---
Tags: c++, scripting
---


# Question
Title: Square Grid Polygonal Terrain Query algorithm?
I have a square, fixed-grid terrain with one terrain type per grid unit in my game, and I want to do an arbitrary polygonal terrain query which returns all of the grid units enclosed/intersected by the polygon. Can anyone point me towards an algorithm for this?

I'll be using this to make sure that my actors aren't going through invalid terrain when they move.

Thanks!

# Answer
> 3 votes
**Prepare your polygon**

Set up your polygon as a directed sequence of points / lines. This is described in any point-in-polygon test, for which there are countless resources online and on Stackoverflow / Stackexchange, so I won't repeat here.

**Prepare your map for querying**

Assign every grid square a unique ID.

Construct a list of all unique vertices (corners) which define your grid squares. For a map N x M squares, there will be (N+1) x (M+1) corners.

Give each corner a list of which squares reference it. (between 1 and 4 -- most will be 4 since generally a corner sits at the intersection of four squares).

**Query and resolve**

Now against every corner point, run point-in-polygon test. For corner points that fall inside, add them to a new "inside" list.

The final step is to determine which squares your inside points belonged to; this is why we kept lists of squares for each corner, earlier. There are two ways you can interpret "insideness" for squares:

* Squares with even just 1 point inside, are considered to be inside the polygon.
* Only squares whose 4 points all fell inside the query polygon, are considered to be inside the polygon.

If the former, it's very easy, just run through all inside points and add squares referenced by them, to a set (i.e. a list that does not allow duplicates). This set is your final result.

Else, you can do reference counting. Set up a map of integer values (zeroes) keyed by square IDs, for every square of your terrain. Now run through the list of inside points, and for every single referenced square in every one of those inside points, add one to the relevant keyed map entry. Once this is done, run through the map and add any entries that have a 4 in the value field, to a new list. This is your final result., since those squares' 4 corners fall completely inside the polygon.

**Optimisation - OPTIONAL**

You can simplify the process somewhat by assigning each square a centre point, and checking which of these fall inside the polygon. This is conceptually simpler, but not as accurate as 4-corner checking. If you don't mind a rougher approach, I'd recommend this.

**Final tip**

Quantising polygons and polyhedra into cells can often be a tedious process. In cases like this, I sometimes recommend that if you don't want to go through the rigmarole above, you instead just construct your game dynamics such that your polygon is in fact already just a shape made out of cells / blocks, rather than a nice neat polygon. This makes it very easy to check against the grid map.

---
Tags: 2d, mathematics, path-finding, terrain, grid
---


title: Andengine reducing sprite quality?

text:
# Question
Title: Andengine reducing sprite quality?
I have a problem with bandings using andengine. When painting a picture on PC and uploading it to my phone, they look exactly the same. But as soon as I use that bitmap (PNG) in Andengine, I have bandings (big color steps).

Now I know that my display is capable of displaying the image right and I know how to us dithering but it bothers me. Does anyone know how to disable this quality reduction in Andengine?

# Answer
You are using `TextureOptions.DEFAULT`. If you inspect the `TextureOptions` class, you will notice that:

```
public static final TextureOptions DEFAULT = NEAREST;

```

Which means your textures are being resampled using nearest-neighbor interpolation. AndEngine will automatically scale your game to the phone's resolution. If you are not scaling in steps of 2 (e.g. your resolution of choice is 800x480 and your phone's resolution is 1280x768) it will create "bandings".

Try `TextureOptions.BILINEAR` or `TextureOptions.BILINEAR_PREMULTIPLYALPHA`.

You can also try whether the following option improves the banding:

`engineOptions.getRenderOptions().setDithering(true);`
> 1 votes

---
Tags: andengine, png
---


# Question
Title: What is the differencen between ccTouchesEnded and ccTouchEnded
I'm learning cocos2d-x. Following the tutorial I found that ccTouchesEnded works perfectly in linux (and windows) but when I replace by ccTouchEnded the event isn't detected anymore.

What are differences between this two functions? And why one is detected and the other isn't.

Taking the HelloWorld project sample as a base, I add the following lines in init()

this-\>setTouchEnabled(true); this-\>schedule(schedule\_selector(HelloWorld::updateGame));

Also, add this method to my code:

```
void HelloWorld::registerWithTouchDispatcher()
{
    // TouchDispatcher::sharedDispatcher()->addTargetedDelegate(this,0,true);
    Director::getInstance()->getTouchDispatcher()->addStandardDelegate(this,0);
}

```

Then if I add ccTouchesEnded like this:

```
void HelloWorld::ccTouchesEnded(Set* touches, Event* event)
{
    // Choose one of the touches to work with
    Touch* touch = static_cast<Touch*>( touches->anyObject() );
    Point location = touch->getLocation();

    log("++++++++after  x:%f, y:%f", location.x, location.y);
}

```

it works perfectly but if I use ccTouchEnded as:

```
void HelloWorld::ccTouchEnded(Touch* touch, Event* event)
{
    Point location = touch->getLocation();

    log("++++++++after  x:%f, y:%f", location.x, location.y);
}

```

The events aren't fired.

Any help is welcome Thanks!!

# Answer
> 1 votes
It depends on what you want to do. The `ccTouchesEnded` version handles multiple touches (as the name implies) so it's a little more difficult to work with, but also more powerful. Use this method if you're dealing with more than one touch, like pinch zooming or rotating.

The `ccTouchEnded` version is just looking at one touch. This is simpler to use, since you don't have to break apart the events yourself.

Both of these methods are part of larger sets of similar methods:

(Standard)

```
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

```

and

(Targeted)

```
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event;
@optional
// touch updates:
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event;
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event;
- (void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event;

```

You need to be consistent in your use of these. If you start with `ccTouchesBegan` you need to end with `ccTouchesEnded`. Likewise, if you start with `ccTouchBegan` you'd check for moves with `ccTouchMoved` and ended with `ccTouchEnded`.

You can learn more about Targeted vs Standard touch delegates here

# Answer
> 1 votes
I think you need to use `void CCLayer::setTouchMode(ccTouchesMode mode)` to change the touch event mode.

```
typedef enum {
  kCCTouchesAllAtOnce,
  kCCTouchesOneByOne,
} ccTouchesMode;

```

According to my understanding, the touch event will only be invoked in either mode of the two. And by default, it is *AllAtOnce*.

---
Tags: cocos2d-x
---


# Question
Title: matrix to rotate a vector to a known arbitrary axis
Let's say I have a vector V (v.x,v.y,v.z) which is normalized and points somewhere in 3d space. And that I have another vector Z of (0,0,1). Knowing only these two things I'm looking for a transformation matrix that will take the vector Z and turn it in to V.

Or some other way to get to the vector V from the vector Z.

In my application for this I'll be taking other vectors that are in a Z axis space and putting them in (or rotating them to) the same space as the V vector. But a proof that it's working will be to take Z and make it V.

I know that if I had this matrix I could multiply the vec3 by the matrix and get the answer. But making this matrix from only that destination vector is what I'm not sure how to do.

Seems like it might be super simple and that I'm just not thinking of it correctly. Answer right in front of my face?

# Answer
1. Cross product the two vectors `N = V x Z` where N is the rotation axis.
2. Calculate the angle to get an axis angle representation.

> dot( A, B) = len(A)\*len(B)\*cos(theta)

if A and B where normalized vectors then

> dot( A, B) = 1 * cos(theta)

So we can get the angle using cos-1

> theta = cos-1( dot(A,B) )

3.Now we have an axis angle representation of orientation, to apply rotation we can do one of the following:

* Convert the axis angle representation to matrix and multiply it be the vectors.

or
> 3 votes

# Answer
Since vector V had been normalized you know the length of vector V and Z will be the same; V has length 1 since it had been normalized, and Z has length of 1 since it is( 0, 0, 1).

Good job :D now the only thing left to take care of in order to make Z vector V is it's orientation.

You will want to get rotation matrix of V then combine it with reverse-rotation matrix of Z. Then apply the resulting matrix to Z.

* By reverse rotation matrix I mean, a matrix that cancels applied rotation. If vector Z rotated 30 degree along Y axis, you want matrix that will rotate Z vector -30 degree along Y axis.

Rotation matrix required for Z to be V = rotation matrix of V * reverse-rotation matrix of Z

* V = RotationMatrixOf\_V * ReverseRotationMatrixOf\_Z * Z;
> 1 votes

---
Tags: mathematics, ios, vector, opengl-es2
---


title: Ground hitting system

text:
# Question
Title: Ground hitting system
I want to know how to make character hit ground and lose health. For example: when character is falling of one meter he losing only a small part of his health, and when he's falling of 10 metters he dying.

I just want to know if it's about speed or distance or maybe even time? (If you can implement some code. please.)

P.S. I'm planning to use SFML and C++.

# Answer
What have you tried? Are you just asking for the code? I don't want to be rude, but you won't find anyone willing to write the code for you.

Instead, try different approaches and see how far you get. You might be surprised to see where you get.

You could try to give the character a boolean value to see if it's falling or not. If it's falling, every tile of free fall, store one hearth of damage in a temporary variable and when he hits the ground, take the life from the character.

Again, try different approaches and see what works for you. Asking for the code won't give you the answer you want.
> 1 votes

---
Tags: collision-detection, physics, platformer
---


# Question
Title: Tweening multiple image objects in html5/js
Is there an optimal way to choose when tweening multiple images as a single image?

For example let's say i have 10 preloaded image objects in my script, and i want to place them one on top of the other (the arrangement is supposed to be dynamic), and then tween it as a single "collage".

Do javascript tweening libraries like Tweenjs/GSAP etc, care about how many objects you tween concurrently (as long as in the end they move in the same direction and with same speed), or is it transparent for the fact that the hardware will move an array of pixels in the end?

Do you think that it would be better - performance-wize - to pre-combine the multiple images into one larger image, and then feed it to the tweening algorithm?

I would like to do it this way, as it would be more transparent to me, seperating the image "collage" process from the tweening process, but i haven't found a way to dynamically create javascript image objects by combining multiple single images.

Thank you.

# Answer
It seems that for TweenJS, there is no performance penalty in tweening multiple image objects.

After contacting CreateJs support, i got extra information on how to do it.

You can group multiple images (createjs.Bitmap objects) using a createjs.Container, and the only performance penalty is the creation of the container object it self.

Hope this helped someone else too.
> 0 votes

# Answer
One way you can do this is to draw all the images where you want them onto a new canvas (one which is separate from the main canvas, but positioned absolutely exactly on top of the main canvas). Then you can tween the entire canvas element (not the images on the canvas), keeping the images that were drawn on it as one.
> 0 votes

---
Tags: javascript, html5, image, tweening
---


# Question
Title: How can I randomly generate 2D tile-based side-scroller terrain?
**I want to randomly generate a map for a 2D sidescroller game using the following tileset:**

I have found a few great articles on the bitmasking process, for example: http://www.angryfishstudios.com/2011/04/adventures-in-bitmasking/ http://www.saltgames.com/2010/a-bitwise-method-for-applying-tilemaps/

I like the idea of using a bitmask/tilemask instead of doing a huge if clause or switch statement.

However, I am having trouble visualizing the entire process and none of these articles talk about randomizing.

My tiles fit together in multiple different ways, not just one way as the tiles in the examples I linked seem to.

For example here are just a few examples:

Since my tiles fit together in many different ways I don't think an 8 bit mask will work. Therefore, I was thinking of using a larger bitmask. Something like char\[8\] or char.

If someone could please show some pseudocode/examples of how the general algorithm would look, I would greatly appreciate it.

# Answer
Yes, the mask size would grow with increasing number of options - your own link http://www.saltgames.com/2010/a-bitwise-method-for-applying-tilemaps/ second part explains the main idea.

In essence, you'd have to enumerate X possibilities for each 'border' between tiles; in your particular example it looks like the "tile top/bottom" may be either (1) white (2) covered or (3) half-covered - which coincidentally matches the 'trinary' example given in the article.

But the masks would only help you restrict the tile possibilities to those that can be drawn, by itself it isn't a method that shows how to *generate* the actual maps in a sensible way.

Your particular tileset actually is quite restrictive - it describes only a single surface rising/falling, and at any 'integer-level' starting point you have only a few valid choices. For example, after tile #2 only tiles #1 or #8 are possible. You could simply move from left to right, making a list of which (few) tiles can come after the previous tile, and randomly choosing one of them.
> 3 votes

# Answer
Have you considered using a 1D Perlin or simplex noise function? There are a number of advantages to this, including:

1. Infinite (within the realm of floating-point precision), non-repeating terrain
2. Can be generated real-time (even in a shader, which is **fast**), or ahead-of-time and stored in textures, as in your example
3. Borders automatically match up as both Perlin and simplex are continuous.
4. Although the terrain itself is pseudo-random, it's easy enough to apply an envelope function or simply reduce the number of octaves in areas where you need flat areas or other specific terrain features that you need.

See this link for a fairly thorough explanation of 1D Perlin implementation.

An envelope is basically a scalar field or function that is multiplied with the noise function before saving or displaying your output.

(Initial image borrowed from the above-referenced article.)

In this example, the red line represents a piecewise function defined as

```
x < 0.3 : y = (0.3-x)/0.3)
x < 0.5 : 0
x < 0.7 : (x - 0.5) / 0.2
else    : 1

```

... which may be better defined using a smooth function. In this case, it just scales things down to 0 before the plateau, then back up to 1 afterwards.

**Update**

Here's an example of a 3D simplex "terrain" from one of my projects, with diffuse + specular lighting applied, generated entirely within a vert + tess + frag shader pipe. For your situation, I'd take a vertical slice out of this to get the terrain slope.

And a top-down orthographic view:
> 6 votes

---
Tags: tiles, procedural-generation, tilemap, level-design, tile-bitmasking
---


# Question
Title: Representing multi-tile objects in a tilemap
I'm building an isometric tiled game, where the terrain and objects are represented by a 2-dimensional array of lists. Depth of objects on the map is derived from the tile (and a per-tile sorting routine), the objects are updated/drawn by going over the entire map, and it is important to know whether a tile is occupied or not for interaction/collision purposes.

Now, I want to have objects that are larger than a single tile (say, a 2x2 or 2x3 object). Drawing them this way is trivial, however, there is the occupation detection requirement. Putting the same object or dummy objects into the array merely to indicate that the tiles are taken doesn't seem like an elegant solution, but neither does checking surrounding tiles for possible big objects, each time the occupation status of a tile is requested.

Is there a more elegant solution that I've overlooked?

# Answer
The most reasonable solution in this case would be the former where you indicate the same object is in multiple positions in the map array. There is nothing wrong with that. As you may realize a platform in a 2d tile based game is "one" object that is being indicated sometimes by dozens of tiles.

Checking nearby tiles for a "Large" object would be an obfuscated solution cause it will require unneeded work and lots of it if you decide to add larger objects. The collision map unlike a list of objects and their positions is required to handle (quickly and efficiently) the detection of the presence of an object in a certain position.
> 1 votes

---
Tags: architecture, tilemap
---


# Question
Title: Texture size and scaling, 2D, for OpenGl ES 1.0/1.1
I read everywhere that you have to use a power of two size for your texture width and height, like 16, 32 or 64, but right now my sprite drawing is based on Grid.java from SpriteMethodTest, and I set the Vertex array "quad" to the pixel size, 20 X 28, and and apply the texture, the same pixel size, to that, and I'm not using any scaling information, and it's drawing them fine and I don't seem to be getting any errors.

Is it actually scaling it behind the scenes?

When I process each Bitmap I use:

```
gl.glBindTexture(GL10.GL_TEXTURE_2D, iTextureName);

gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,    GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);

gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE);

```

So if I start doing sprite batching instead, the image I grab out of the bigger image has to be a power of two width and height, if I want it drawn without any scaling?

Thanks!

# Answer
> 1 votes
While it is always recommended that you stick to power of two textures, whether or not it is required is dependent on platform implementation and content pipeline features. OpenGL itself does not require the textures to be square, or powers of two.

See this link for more specifics on OpenGL Textures. https://www.opengl.org/wiki/Texture

To add in some of the details from the comments, there are performance and portability issues that affect your choice of texture dimensions. While it is indeed often not necessary for your artists to produce textures in powers of two, placing this restriction on them can provide benefits over the lifetime of the project.

**Performance**

This is something that could be overlooked, especially with the latest generation of gaming consoles and high end PC hardware, but the topic of performance is always relevant in gaming.

Power of two texture dimensions allow for assumptions to be made with various post processing and computer vision applications. This becomes even more true when your textures become square, though this is not always an option for various reasons. Whenever you can place constraints that enable your engineers to make assumptions, you can likely facilitate performance games.

Another performance gain can be made in the realm of memory management when building a texture atlas, or a simple decal/sprite sheet. When your textures are composed of random dimensions, it becomes increasingly difficult to pack them together, and you will require additional texture atlas'. While this may sound insignificant if you are developing for the PC, or the current generation of consoles, hand held devices such as the 3DS, the Vita, and the world of mobile devices are very concerned with texture size and memory footprint.

Finally, compression algorithms are always best when they are applied to a very specific type of data, and textures are no exception. These techniques can not only be better at compressing, but also faster at it. Many hardware platforms today have support for texture decompression as a part of the graphics pipeline. This is best supported via very specific texture formats.

**Portability**

A more overlooked benefit would be platform portability. Not all platforms support the same texture formats, and while you can guarantee that any platform will support powers of two, not all platforms support random dimensions. This leads to the logical conclusion that producing all your texture assets in power of two dimensions increases the cross platform support that your project has. This also might sound insignificant, but we are seeing more big name games being ported to these limited platforms. Such a project the designers likely thought was as far fetched as a trip to the moon once was.

# Answer
> 0 votes
Arbitrary texture sizes became fully supported in OpenGL 2.0, but GPU's nowadays support them anyway, so there's no need to worry unless you plan to support ancient devices.

---
Tags: opengl-es
---


# Question
Title: How can I make a sprite jump at a particular angle?
I have a sprite that is moving horizontally across the screen. I want it to jump when the user touches the screen. The jump needs to be at the angle of the touch and the sprite’s current position.

I found out that I could use:

```
Math.atan(deltay,deltax) * 180 / PI

```

to get the angle between the current position and the touch on the screen.

I tried doing this and then calculated the velocity of jump using:

```
velocity += 1.5f * Math.cos(angleInDegrees);

```

where I used 1.5f as a random number. Can I do that?

The sprite doesn't jump properly. What am I doing wrong?

# Answer
I'm assuming you want the sprite to jump towards the touch point, so instead of calculating and using the angle, rather just create a vector from the current position to the touch position:

```
dir.x = touch.x - current.x;
dir.y = touch.y - current.y;

```

Next, you need to normalize the vector (making it a unit/direction vector):

```
length = sqrt( (dir.x * dir.x) + (dir.y * dir.y) );
dir.x = dir.x / length;
dir.y = dir.y / length;

```

Finally, you can scale this vector by your jump velocity - the 1.5 you used in your example, or whatever value you want (you may want to experiment with this):

```
vel.x = dir.x * 1.5f;
vel.y = dir.y * 1.5f;

```

**Note:** You may also need to add your existing horizontal velocity to `vel.x` if needed.

This gives you a velocity vector in the direction of the jump, with the specified magnitude. Then you simply use it to adjust your sprite's position:

```
position.x = position.x + vel.x;
position.y = position.y + vel.y;

```

Then of course you will need some gravity (define it to some value based on what you need) to bring the sprite back down again, as well as some code to ensure when the ground is reached the jump ends:

```
position.y -= gravity;
if ( position.y <= ground.y )  {
   vel.x = (original x velocity for movement only)
   vel.y = 0;
}

```

These examples did not include any time values (for the sake of simplicity), but you will probably need to include it in the calculations.
> 2 votes

---
Tags: java
---


title: Build a Unity asset bundle on linux?

text:
# Question
Title: Build a Unity asset bundle on linux?
I'm trying to generate an asset bundle on a remote linux machine and stream the bundle to a running Unity instance.

Is it possible to download the same libraries Unity uses and compile on Linux?

# Answer
> 1 votes
I don't think so, currently Unity3D doesn’t yet support Linux targeted development - only deployment. At the moment, http://unity3d.com/unity/system-requirements states only Windows and Mac versions are available.

There are two main possibilities if you want to use Unity3D:

1. Deploy for Linux from one of the supported systems (you could make a script that would upload it to the test Linux machine for example)
2. IF and only if Unity3D does NO packaging, and I believe it does which would mean this isn't an option, you could use mono. maybe http://docs.unity3d.com/Documentation/Manual/UsingDLL.html might help? I realize that link is for importing, but it might be useful anyway.

# Answer
> 0 votes
http://unity3d.com/unity/multiplatform/desktop … claims that they only officially support Ubuntu. What have you tried?

# Answer
> 0 votes
No you can't build bundles on the fly from a Unity runtime(linux or otherwise) you can really only use the editor to do this. So essentially you'd update your bundles then load them up to your linux server.

To stream a bundle from a remote server you can do the following (javascript code this is from the docs here)

```
function Start () {
    var www = new WWW ("http:/myservermyBundle.unity3d");
    yield www;
    // Get the designated main asset and instantiate it.
    Instantiate(www.assetBundle.mainAsset);
}

```

---
Tags: unity, assets, linux, mono
---