# Question
Title: Can you write the current frame number to a text file?
I am running an experiment in Unity 5 to see the effect increasing the particles of a particle effect has on FPS over time. (this is background work for a much larger piece of work). Currently I write the FPS count from the profiler to a log file and this shows the framenumber and its FPS at that frame. To a seperate log file I write the number of particles on screen and the time.

I have no way of linking these two files to draw up results.

So my question is, how do I write the current framenumber to a file? Can I do this?

**UPDATE**

I would like the same framenumber that the unity Profiler gives me in its log.

# Answer
> 4 votes
You can retrieve the number of frames that have passed with `Time.frameCount();`, if that's what you're looking for.

http://docs.unity3d.com/ScriptReference/Time-frameCount.html

From there, writing to a file in C# is pretty trivial:

http://forum.unity3d.com/threads/how-to-write-a-file.8864/

# Answer
> 1 votes
An alternative to the answer of @KevLoughrey would be:

```
uint framesSinceStartup;

void Update()
{
    framesSinceStartup++;
}

```

This is probably the same thing that Unity does for counting frames.

---
Tags: c#, unity, scripting, frame-rate
---


# Question
Title: Change Andengine Text By clicking and typing a new text like native android EditText
I have a board in my game, with a name. I want to edit it on a button click (not by text.setText("text") method ) i want the user to enter a text and set it there. I couldnt find, how to change the changeableText in andengine other than by setText(), Any help is appreciated :) Thanks in advance

# Answer
> 0 votes
AndEngine doesn't have an editable TextBox. You have to do it yourself (programmaticaly of course). Like:

1-Draw a white rectangle (Textbox) and an empty text into it
2-Handle touch
3-Show keyboard
4-Handle Input and \[change\] / \[append to\] the text

---
Tags: android, sprites, andengine, text
---


# Question
Title: Separating .js elements/ .js element communication
So I have 2 questions regarding the code below:

```
function goldClick(number){
    gold = gold + number;
    document.getElementById("gold").innerHTML = gold;
};

function buyMiner(){
    var minerCostG = Math.floor(100 * Math.pow(2.1,miner));
 var minerCostW = Math.floor(10 * Math.pow(3.1,miner));
    if(gold >= minerCostG){
  if(wood >= minerCostW){
   miner = miner + 1;
   gold = gold - minerCostG;
   wood = wood - minerCostW;
   document.getElementById('miner').innerHTML = miner;
   document.getElementById('gold').innerHTML = gold;
   document.getElementById('wood').innerHTML = wood;
    }};
    var nextCostMG = Math.floor(100 * Math.pow(2.1,miner));
    document.getElementById('minerCostG').innerHTML = nextCostMG;

 var nextCostMW = Math.floor(10 * Math.pow(3.1,miner));
    document.getElementById('minerCostW').innerHTML = nextCostMW;
};

window.setInterval(function(){

 goldClick(miner);

}, 1000);
```

Question 1: Is it possible to separate these functions (goldclick, buyminer, window interval,) into their own documents so that if I have say, 50 different XXXXclick functions, and 50 buyXXXX functions and 50 interval functions, I have just 3 .js documents instead of 50.

Question 2: If it is possible to separate them, how would I ensure that they are communicating with each other and variable values are not being confused or sent to the wrong `<span>` in the displaying html.

# Answer
> 1 votes
Is it, you can write your code in any files you want and load them in the app load time and share the important data via window variables or via the class constructor.

But i would make it little different, i would create some clases (miner, plumber, whatever) and make them inherit some "base" functions like .buy(), .goldClick(), etc so you can have a common "base class" file and some "specific" class file such a "miner.js", etc...

I made kind of engine that "Loads" any requirements you need, such a node modules in clientside, give it a pick if you want.

I hope this helps.

---
Tags: javascript, data-structure, architecture
---


# Question
Title: How to compress game frame by frame animation to a minimum on disk
I developing a game like Age of empire (buildings on map) and for every building I have a sprite sheet for its animation. I am using frame by frame animation to animate the building ( not aware of any other method anyways). I am noticing that my resources folder is going extremely large due to the images I am putting in it.

How do games like CoC and Age of Empires keep their apk size under 50 Mg? Am I missing something here when it comes to game development

Thank you

**EDIT: More info to the problem I am facing**

I have a LOT of animations drawables objects. I chose this way because it was the quickest and it was yielding the results the I want. Basically every building is an animation drawable in which its xml file refers to 8 drawables (8 images = 8 files). All of them are PNG due to transparency. Since I have over 200 images, the apk size is 120 MB ( And I am not done copying half of the files yet). That's what prompt, there has t o be a way to solve it. Please assist a fellow developer

# Answer
It's not clear by your question if you really want to know techniques that allow games to save disk space even when having large amounts of heavy image/resource files (that's what is in the body of the question), or if you just wanna know if there are less disk-space hungry ways of doing animation for your buildings (that's what is implied by the title of your question).

So, I will put this answer here trying to be of help in relation to saving space when you have a lot of images. If you are only interested in knowing about animation techniques that might allow you to save disk space, please let me know then I might delete the answer.

---

That said, in a similar situation, two solutions I have seen (and used once) in terms of saving space in the disk, were:

1) to concatenate individual images within one same image. Sometimes it can be of help. So instead of saving 4 separate files for each of the following colored squares, I save all of them side-by-side within the same image (and will only split them via game code):

In this example, saving each in 4 different PNG files amounts to 1255 bytes, while the single file with all concatenated is 451 bytes. Of course, how much it could help depends on a case-by-case basis and you should test to see if that can be of help to you depending on your images.

2) to compress the resources folder. This can often be very helpful to save disk space. Then when the game is running you either decompress or pull the desired image from the compressed file - depending on the compression format you use. See this past answer that became a wiki of this site: https://gamedev.stackexchange.com/a/37649/72423

But also keep in mind that **each type of compression may be more or less advantageous depending on the image file type you use**: Avoid double compression of resources

For more details on compression: State of the art in image compression?

---

Lastly, you might also be interested in thinking which types of image to use for each situation: Which image format is more memory-efficient: PNG, JPEG, or GIF?
> 24 votes

# Answer
I would propose that you try TexturePacker

* you can simply drag and drop all your images and get them packed
* you can apply different compression - e.g. use indexed PNGs which consume way less memory - up to 70% less compared to a standard PNG file
* you can create a file data files that contain the name + position of each of your buildings
* the free version might already suffice to create the sprite sheets for you

Do you use a game development framework like AndEngine, Cocos2d-x or LibGdx? =\> None

Do you need all your images loaded at the same time? It sounds like you'll run into massive RAM problems on the target devices.

---

Update: Snake sent me some images. As promised won't make them public here so I've created some art myself to demonstrate how to reduce the memory usage.

In the original image, only one part of the image was moving. I've placed a bird on a house to demonstrate this:

Basically packing the complete animation into a sheet is a big waste of memory. You should split static and moving parts:

Static:

Anim01:

Anim02:

**Keep the original position of the bird in the images**. This is why there is so mich empty space above. You need this for aligning the animation.

Now drag the images on TexturePacker and select the following parameters

* Data format: JSON hash (or XML if you prefer that)
* TrimMode: Trim (this creates rectangles)
* Pixel format: INDEXED 8bit - to create 8bit PNGs (about 70% less memory)
* Allow Rotation: false
* Enter a filename for the data

The result is that you now get 2 files: The sprite sheet and a JSON description file.

```
"house_anim_01.png":
{
    "frame": {"x":351,"y":246,"w":110,"h":79},
    "rotated": false,
    "trimmed": true,
    "spriteSourceSize": {"x":67,"y":8,"w":110,"h":79},
    "sourceSize": {"w":400,"h":400},
    "pivot": {"x":0.5,"y":0.5}
},

```

The important parts are **frame** and **spriteSourceSize**.

The **frame** gives you the location of the original sprite in the sprite sheet.

**spriteSourceSize** gives you the offset for drawing the image - the parts of the image that are left out because of the trimming:

A simple pseudo-code drawing routine looks like this:

```
drawImage(spritename, posX, posX)
{
    data    = sheetData[spritename]
    offsetX = data.spriteSourceSize.x
    offsetY = data.spriteSourceSize.y
    frameX  = data.frame.x
    frameY  = data.frame.y
    width   = data.frame.w
    height  = data.frame.h
    screen.draw(sheetImage, posX+offsetX, posY+offsetY, width, height)
}

```

You might have to adjust the offset calculation depending on the pivot point / origin in your graphics system. The routine above assumes a coordinate system who's origin is top left.

Then simply draw the house in 2 passes:

```
draw("background", 100, 100);
draw("anim_01", 100, 100);

```

You don't have to care about the offsets - since the images are already aligned.
> 9 votes

# Answer
Here are few pointer you can use

1. Try to make sure all your Background and non transparent images are not in PNG format
2. Try to have all animation loop-able i.e. if animation is 1,2,3,4,5,6 try to make it like 1,2,3,4,3,2,1 where these numbers are frame number of animation, it helps a lot
3. if many image are same and only color differs (generally UI buttons,m particle animations, game coins ) then try to take one White image and change its color dynamically
4. Try to make your .apk with only those images that are extremely important and then load everything from a server and keep in phone memory

I hope these pointers help

**P.S.** I am only give generalized idea as i am not aware of your exact game content and apologies if these pointers are not useful
> 7 votes

# Answer
A lot of games don't keep their graphical assets in the .apk; they only include the "basics" like UI graphics and the game code and download the rest of the assets once the game's been installed. This is especially true for games that use different graphic resources depending on the resolution of your display to keep the .apk from having to contain both low-res and hi-res assets.

You should look at both the optimization options provided by the other answerers, as well as whether or not you will ultimately have to serve your game's graphics separately from the .apk itself.
> 4 votes

# Answer
I came to this site looking for a similar question and there are indeed a few good resources pointed both in the answers to your question and in other questions.

You should probably take a look at 2D animation: Animated 3D models or sprites with animation frames? for some debate on different types of animation. It helped me optimize my game. Also, you don't tell us which API you are using or which Engine you use. That alone can make quite a difference: Android frame by frame PNG animation

Besides that, keep in mind that if you will go the compression route, there can be important differences between how you compress. Specifically, there are quite a few differences between types of compression and there is some specialized debate on what is the most appropriate route for mobile devices. Specially if you take into account that for mobile, RAM usage and CPU waste for loading are also paramount. See: http://www.gamasutra.com/blogs/AlexandruVoica/20130419/190833/Why\_efficiency\_is\_key\_in\_texture\_compression\_standards\_for\_mobile\_graphics.php?print=1
> 4 votes

---
Tags: android, animation, storage
---


title: Getting rid of texture bleeding

text:
# Question
Title: Getting rid of texture bleeding
**Edit:** I figured out what problem I was facing, it's called **Texture/Pixel bleeding**, which I was not aware of yet. I posted an answer below consisting of a small description of the problem and a link to a post, that I felt explained the problem pretty well.

---

I'm building a little engine for myself (okay, let's say framework) to learn using DirectX 11. I'm pretty pleased with the results so far but today I ran into a little problem I was not able to solve. **When rendering a textured model there are ugly gaps at some polygon joints observable.** I will depict the issue more clearly with images of the example I'm rendering at the moment. My model consists of simple cuboids, one of those uses the following part of the UV map (marked vertices and triangles in yellow to clarify, the lines and points are not actually part of the texture).

(As you can see, The cuboid has 14 vertices

Now, I want to display the the pixels discrete. That means: Don't smooth the pixels. Doing this I got visual issues seen in the screenshot below. This is a screenshot of the edge, where the two triangles meet.

*(When I use smoothed pixels by using a linear filter when creating the sampler Description there are no real gaps, but the edges of the plane are influenced by the color that would have been the gap)*

As you can see, there is a gap between polygons. The corresponding spot on the uv map is marked in red on the top picture. This behaviour is observable at every spot two polygons, that are not adjacent on the UV map, meet. Also note how the gap is partly filled with orange/pink, the color that is adjacent to the polygon on the UV map (Pixels of other meshes, in this case the right arm).

Steps I took to find a solution:

* First I thought it could be caused by float inaccuracies. Moving every Vertex a little bit (the minimum a float can encode) to the inside of the UV-Map would probably solve the issues. But I think that this would be one hell of a workaround and can't be the solution.
* Changed the texture to be 16x16 (instead of 13x12) because I thought this would decrease the inaccuracies with float, but it didn't help much.
* I thought changing the filtering to something different could help, but I wasn't lucky.
* I even tried modifying the uv coordinates inside the Pixel Shader, but this was doomed to fail and resulted in some weird (but in some way funny) results.
* Googled around with various keyword, but couldn't find anything that appeared to solve this issue.
* When I tested drawing it as a wireframe the edge was drawn in orange/pink

---

**I'm probably missing the obvious here, but how can I fix this and get rid of the gaps?**
I triple checked that all vertex data (x|y|z and u|v) are correct. Is there any kind of filter I am missing? Or do I even have to use some nasty workaround (like surrounding the actual texture on the uv map with an extra row of correctly colored pixels)? I would like to resolve this before going on.

Thanks in advance to anyone taking the time to read (and even answer or point me in the right direction) this presumably stupid question.

In case it's relevant here is the data for the 4 involved vertices(numbering as depicted above). First Vector is x|y|z, second one u|v:

```
vertices[ 0] = { { -1, -1.5f, .5f },{  9.f / 16.f, 5.f / 16.f }};
vertices[ 1] = { {  1, -1.5f, .5f },{ 11.f / 16.f, 5.f / 16.f }};

vertices[11] = { { -1, -1.5f, .5f },{  8.f / 16.f, 4.f / 16.f }};
vertices[12] = { {  1, -1.5f, .5f },{  6.f / 16.f, 4.f / 16.f }};

```

(A screenshot of the complete model in case the look of the whole thing wasn't clear. There are also fragments visible at the head and the top of the arm. )

# Answer
After much more research I found out what the source of these "gaps" was. They're not really gaps, they're effects of **pixel/texture bleeding** (I was not aware of this problem).

---

**What is texture bleeding?**

Texture bleeding is the effect of color values of adjacent pixels in the UV-map/texture "bleed over" in your polygon. If using linear filtering it alters the rendered colors at the edges of the polygon. If you're not using any filter a small line of the adjacent color appears at the edges (as in my case, see the pictures in the question).

---

**How to solve/avoid it?**

There are numerous ways to avoid it, depending on the specific case.

* Surround the pixels of the UV Map with at least one additional pixel (if using linear filtering or other filters you have to add more)
* For tiles filling the entire texture you can use D3D11\_TEXTURE\_ADDRESS\_CLAMP (or the OpenGL equivalent), so you don't need the additional line. (When using a texture atlas for tiles I'd suggest extracting the tiles as individual texture ressources).

If you want to read more about it I'd recommend this forum post: Click

---

**P.S.** I edited the title and the question so that people stumbling over this question aren't confused by the weird description of the problem
> 1 votes

---
Tags: directx, directx11, fragment-shader
---


# Question
Title: Most efficient way to optimize based on gpu type?
So, I'm writing an optimization button that should optimize a game based on the type of hardware the user has. I know I can use d3dadapter\_identifier9 to achieve this, but what would be the most efficient way of actually implementing it? Not sure whether i should check based on deviceid, name, etc. was hoping someone could give me a couple tips for that. Thanks in advance.

# Answer
Why not actually perform some frames of rendering and time it. If it is below your target speed turn off some features and try again. Keep doing this until performance is within your target. To hide it from the player just draw fullscreen quad overtop or setup offscreen rendertarget and never present it. As commenters note you will want to allow the user to override the setting somehow as some may want to have better visuals regardless of performance impact or vice versa.
> 2 votes

# Answer
Direct3D 9 and prior optimization is quite challenging. You have to handle the 'sea of caps' where specific hardware and drivers can remove almost any caps bit and expect apps to handle it when in fact few do. This really complicates the 'feature fallback' problem.

With Direct3D 10 or later, the 'sea of caps' problem is greatly reduced by the Direct3D hardware feature level where each new feature level is a superset of the older ones. You pick a minimum feature level for your game, perhaps scale up to a specific higher feature level or two, and not worry that individual hardware caps will disappear at these higher levels.

With all versions of Direct3D, you still have to scale based on performance. A Feature Level 11.1 device is required to support hardware tessellation, DirectCompute, and a whole slew of other features including everything a Feature Level 11.0 device supports. This says nothing with how fast the hardware is at doing any of this. For example, the WARP software device supports Feature Level 11.1 but is much slower than dedicated video hardware.

The typical solution here is to have some basic assumption of 'good enough' settings and allowing users to tweak settings as desired. Ideally you can do a benchmark to make the initial settings more accurate, but it's still a pretty open ended problem. Developers use display resolution scaling, level-of-detail artwork, turn on and off individual features, etc. to try to provide this flexibly.

This is the main way that consoles are easier to target than PC because you the developer can do all the tuning in development and know the user's machine is basically the same. This process on PCs is complicated by aggressive power management and heterogeneous GPUs (i.e. the laptop/tablet has an integrated part, but if you dock it or plug it in it can use a dedicated GPU).

The device id (`DXGI_ADAPTER_DESC.VendorId` / `DeviceId` or `D3DADAPTER_IDENTIFIER9.VendorId` / `DeviceId`) is typically only used to generate a warning--like I do in Anatomy of Direct3D 11 Create Device--or as a workaround for a specific driver bug. It's not a safe way to handle feature detection or to do performance scaling.
> 2 votes

---
Tags: directx9
---


# Question
Title: Software polygon rasterization with transparency using raw image data
I have an image with shapes in it (squares and triangles with different colors scattered in the image) and I have an algorithm that matches the image and extracts the geometry vertices from image raw data (unsigned char\*) and the extracted vertices are correct and I have checked theme there is no doubt about theme.

Now that I have got the vertices of the squares and triangles from the raw image data. How can I fill the pixels that lies inside the vertices with transparency so they become deleted shapes?

PS: the vertices that i have got are just an array of points and each point has x and y property in it and the raw image data is rgba8888 (32 bit).

# Answer
> 1 votes
Ok, here is the solution.

First, you need to ensure that your vertices are winded in a correct direction. For this explanation I'm going to use counter-clockwise order. Like this:

```
    1

2       3

```

And our coordinate system is:

```
Y
^
|
|
0------> X

```

Let's call our 3 points `a`, `b` and `c`.

Let's create some vectors: `b - a` = A, `c - b` = B, `a - c` = C.
Now we need to rotate them 90 degrees clockwise: `[A.y,-A.x]` = AA, `[B.y,-B.x]` = BB, `[C.y,-C.x]` = CC.

Now you need to understand what *dot product* is: `dot(a, b) = a.x*b.x + a.y&b.y`. It has useful properties. For example, dot product of `a` and `b` is equal to `length of a * length of b * cos of angle between a and b`.

And now we can test if some point is in this triangle: The point is inside if `dot(AA, point - a) < 0 and dot(BB, point - b) < 0 and dot(CC, point - c) < 0`.

And now we take a minimal square that contains all 3 points. Like this:

```
+--a----+
|       |
|       c
|       |
b-------+

```

And now you just test every point in this square.

---

You can use same method for quads, you just need to add 4th point.

---
Tags: c++, image, rasterization
---


# Question
Title: How to do Marching Cubes Meshing in unity 3D
I'm getting very peculiar results from my marching cubes based surface generator within unity and figured this must be a pretty common problem that has been solved already, so I thought I would extract this out as a tiny example project that only includes the broken generation code ...

http://ccoder.co.uk/files/mc.zip

... if you download and run the example you should get something like this ...

... so my question is:

How can I resolve the logic in the marching cubes meshing code to generate a complete mesh with consistent uv mappings all the way around?

> If someone can solve this I will edit the sample in this question with the solution so others can download this solution in the future.

UPDATE:

So I figured out what was causing the vertex generation issue, it looks like paul burkes lookup tables however result in some cases returning the vertex data in different orders to others which appears to be the cause of this uv issue (see image, updated)

I have updated the sample project too, anyone fancy debugging the marching cubes tri table?, something tells me this will be a long winded task!

# Answer
Ok so i figured it out ....

I'm still working my way through it but basically the problem is that unity and the lookup tables supplied by Paul Burke don't quite tally up as had suspected.

The process basically involves reshuffling each case so that the tri's orders and winding are correct for unity.

I'm little bit annoyed at this since unity uses OpenGL under the bonnet you'd expect the positioning system to be similar, that said I haven't seen anything published by paul burke that even remotely suggested he had ever tried to texture a mesh generated with his algorithm so maybe its just bad lookup tables that were published.
> 0 votes

---
Tags: procedural-generation, unity, 3d-meshes, marching-cubes
---


# Question
Title: Calculate average velocity of the object before the game start
I have a game object (player), and with device screen width and average FPS, I'm able to calculate exact velocity for the player to reach whole screen from left to right in a specified time (fx. for 1 second). Objective of this is to move player on different devices still same (reach for 1 second their screen width).

I can calculate this in runtime. But is it somehow possible to calculate it before, for example in surfaceCreated? Because in my game, I need that velocity to be constant from start (I can't change it in runtime). Is possible to approximately calculate it?

# Answer
**First**, a side note: you seem to need the speed, not the velocity. And since it's constant, you don't need the average speed, since that's the same as the speed.

**Second**, an advice: per your question and responses to comments, it really seems that you should be re-factoring the code of your game. There is almost always a way back from a messy setting, and not being able to due what you want simply in the Awake() or Start() parts of the game seems like the whole thing will give you future troubles nevertheless.

**Third**: besides the option of loading into your game a previously baked data, there is no such a thing like a calculation being *really* done before run-time. Run-time means time during which processor is running your game, and processor running is a necessity for you to make a calculation.

The problem, in your case, with loading a previously calculated data with information when the game scene Awakes(), is that you would have to be sure that you cover all and any screen resolution of all and any devices possible that could be running your game.

**Fourth**: one workaround that you could use is the following. Create an additional scene for your game (like an additional level) that will become the very first one. Then, you make the calculation in it normally, in the Start(). After the calculation, you just end such scene/level and call the next, which will be the real one you already have. Of course, keeping the result from the calculation from first scene/level to the second, as a global variable or class. That would take milliseconds, since the calculation you seem to need looks simple and inexpensive.
> 4 votes

---
Tags: java, android
---


# Question
Title: Get Stencil buffer working iOS OpenGL ES 2.0
I have been trying to get this work but either get black screen or reporting error when using XCode to analyze the GL code like below. Any help appreciated. I am using Swift here if that making a difference. Any help appreciated.

The code I used to attach a stencil buffer is like below:

```
var depthRenderbuffer: GLuint = 0
glGenRenderbuffers(1, &depthRenderbuffer)
glBindRenderbuffer(GLenum(GL_RENDERBUFFER), depthRenderbuffer)
glRenderbufferStorage(GLenum(GL_RENDERBUFFER), GLenum(GL_DEPTH24_STENCIL8), 2208, 1242)
glFramebufferRenderbuffer(GLenum(GL_FRAMEBUFFER), GLenum(GL_STENCIL_ATTACHMENT), GLenum(GL_RENDERBUFFER), depthRenderbuffer)

```

# Answer
> 1 votes
I figured it after found some sample code. Basically, after I bind the render buffer, the current render buffer is bound to the depthRenderBuffer, However, the bound rendering buffer while presenting must be a color render buffer. after I added another line of code at the end, it works. Hope this helps somebody in the future.

```
// Make the Color Render Buffer the current buffer for display
// This is important. colorRenderBuffer needs to be the one
// binding to render buffer at the time of presenting
glBindRenderbuffer(GLenum(GL_RENDERBUFFER), self.colorRenderBuffer)

```

---
Tags: opengl-es, opengl-es2, swift
---


# Question
Title: Chromium Embedded Framework and Unity3D?
I have recently heard about the Chromium Embedded Framework and was over-joyed as I want to use html as my GUI source.

I did find a C# version but it seems to be for Windows Forms.

I'm not too terribly well versed but I was under the impression that it may cause it to be unavailable for cross-platform use.

Can anyone provide and insights? And if this will not work, any free alternatives?

# Answer
> 2 votes
The .NET version of Chromium Embedded Framework (CEFSharp) does have a version for offscreen rendering, however you need to handle converting the rendered screen into another image format to use with your framework of choice (in this case Unity). There also does seem to be a recent discussion about integrating it into Unity.

As for alternatives, there is Awesomium, however I don't recommend it as it is still running on Chromium 18 (with no plans to update in sight, apparently they are *really* busy improving the API for the next big version), virtually no CSS3 support and the engine takes a good few seconds to start up in a parallel thread, meaning the actual screen will be blank until it finishes its start up. However it does have good JS bindings compared to CEFSharp (you bind individual methods instead of entire classes), and it has a much more user friendly API, which means its easier to pass mouse and key events compared to CEFSharp.

CEFSharp, on the other hand is a lot rougher around the edges in regards to its API, but a lot faster on startup and is fairly up to date (it was running Chromium 43 or 44 when I tried it out a month ago). You'll also need to pass mouse and key events to the browser instance as well, but you'll need to do some digging to find the correct handlers, as they are buried rather deep in parent objects (took me 2 days to find the correct functions).
Only issues I had with it was that it took a while to shut down and the API wasn't as user friendly as Awesomium, which made it a bit awkward to work with, and its JS binding didn't seem to like existing class instances to bind to.

Coherent UI is probably the best option around, and is supposed to have Unity bindings, but is rather expensive. Googling reveals that the Unity Asset Store has a few cheaper options available.

If you don't want to use any of those, it is probably possible to implement the offscreen versions of CEFSharp or Awesomium into your Unity game. I don't know how difficult it would be, but provided you could get mouse/keyboard input and render a 2D texture over the entire screen, it is probably doable. I integrated both of them into XNA/MonoGame, and I still have the code referencing the functions to be called to pass input/get the rendered screen to a texture lying around somewhere if you want to try and implement it.

# Answer
> 1 votes
There was a project, Awesomium for Unity, but I don't know in what state it is right now, but what I've got after a few google lookups it got quite stagnant if not completely on hold. But there is an alternative, here: Coherent-UI. You should check that up. But, if you want to use CEF, then be prepared to do some "low level bit pushy trickery", but I'd vouch against that. That Coherent-UI might be the perfect fit for you.

---
Tags: unity, gui, html
---


# Question
Title: Avoiding GC when rebuilding Mesh.uv and Mesh.vertices
Since unity will not allow users to iterate over mesh.uv and mesh.vertices, I am stuck having to use GC intensive calls when applying an array of uvs and vertices to a mesh. I run into high GC allocation because every time I rebuild a mesh, the uv and vert arrays will be a different size due to the mesh being modified. In turn, this results in having to resize or create new uv/vert array and that is where the garbage collection comes in to be a problem when the old array or list is discarded as well as when applied to the mesh.

**Example 1 - List:** For example, building a List UVList for a mesh that is built frequently will require calls of UVList.Add(Vert), this creates garbage for the GC whenever the List is resized with List.Add because when the list is resized, it creates a new copy and the old copy goes into GC. Also, to apply this list to a mesh.uv requires the call UVList.ToArray(); which is a nasty call that creates huge GC if you have a long list of vertices because again, to convert to array, that array after it is copied mesh.uv = UVList.ToArray() the UVList array created goes to GC.

**Example 2 Array:** I've instead tried using fixed array sizes but then learned that you cannot iterate over vertices or uv array of a mesh. For example, using a for loop to directly apply a vertices array to mesh.vertices will result in no mesh showing (i.e. for(i = 0; ...){ mesh.uv\[i\] = uvArray\[i\];} )

If I cannot do this, then I run into the same problem as example 1, because the only way is to create new array every time you want to update your mesh that has diff uv/vert length. Resizing array requires creating a new copy of it, and then you have the same issue with GC.

I tried reading through this example of someone else dealing with Unity GC when frequently updating meshes http://gamasutra.com/blogs/RobertZubek/20150504/242572/C\_memory\_and\_performance\_tips\_for\_Unity.php

He doesn't really explain his helper method in applying the UVs to the mesh and when trying from his example, it also results in GC.

I guess my question is, how can I frequently update a mesh with diff uv/vert array size without running into GC Alloc slowing down my project?

# Answer
According to http://answers.unity3d.com/questions/855637/mesh-uvs-wont-change-positions.html, mesh.uv is a deep copy, explaining why your second example doesn't work.

Another link corroborating this position, with less supporting detail: http://answers.unity3d.com/questions/956387/how-can-i-modify-a-mesh-objects-uv-variable-direct.html

In your link to Robert Zubek's post, I think it's crucial that he says "of the appropriate size." I.e., I think he's mutating some specific array size, not variable size. I don't believe he has a trick for UV arrays of variable sizes.

Given this information, I think the only suggestion I have is a truely sinful hack: maintain scratch arrays of each size you need.

Depending on what sort of geometry manipulation you're doing, this could actually be fairly benign, if a bit of a headache.

Also, if you're able to break the mesh into smaller chunks, then hypothetically you only need as many scratch arrays as the max size of those chunks. Again, a headache.
> 1 votes

---
Tags: unity, optimization, 3d-meshes, vertex, vertex-arrays
---


# Question
Title: How to create a seamless cubemap noise texture?
I have, so far, been able to create the vertices and UV coords etc for a sphere that would be textured with a cube map. I have also successfully loaded a cube texture from file and applied it to my sphere and it looks awesome.

So now, I want to randomly create a noise cube texture map to apply to my sphere.

I have a class which can create 1d, 2d, 3d and 4d noise. My problem is I don't know the math needed to sample a sphere map out of the cube, and then how to translate this to the 6 textures that make up with my cubemap.

I guess first I need to know how to first sample the points of a sphere in 3d; and then how to translate these to x,y,z coordinates for the 6 sides. I can probably work it out from there.

I would have thought this would be simple enough to Google, but I'm not finding what I need.

**SOLUTION**

For whomever comes along next, here's the answer. @Jason has the right idea below. Here's how I solved it:

1. March through each of the faces of the cube and each UV coord for that face
2. Normalize each position vector
3. Multiply by the radius of your sphere. You now have the coordinates of the sphere edge
4. These coordinates can be used to sample from your 3D noise function

You'll end up with each faces UV coordinates being filled with the noise that is at the spherical equivalents position in the noise.

(I hope that was in english). I will try to remember to update this later with full code once I've cleaned it up.

# Answer
To generate noise which is isotropic, you need to sample from 3D space but from the surface of as sphere:

Here the black point is the location in space of the pixel in the image you want to generate the color for. Project it onto the unit sphere (the green point) by normalizing the vector from the origin (red), and then sample from your noise function (scale it up by a constant to get finer noise, or down to get softer noise). You will need functions to compute the x,y,z coordinates of a cube map pixel given the image dimensions, pixel x,y, and which face the pixel is on.

Note that classic Perlin noise has some serious artifacts when taking a 2D slice of 3D noise, so you should use another function, or add a bunch of randomly rotated copies of classic noise (which kinda hides the artifacts).

This noise will look distorted when you look at the raw images, but when rendered as a skybox it will appear uniform in every direction.
> 3 votes

# Answer
> I have also successfully loaded a cube texture from file and applied it to my sphere and it looks awesome.

This implies that you've already calculated the UV's on the CPU and stored them in the vertices. Those same UV's should work for any cube textures that are similarly oriented since they all range from 0:1.

A diagram follows, in case it helps, but I think you're already doing this.

The gray sphere represents your skysphere.
The purple cube is just a cube with the same "radius" as the skysphere.
The green cube is a unit cube.

Given some arbitrary "forward" direction that corresponds to the cube map, and the normalized direction from each pixel world-coordinate to sphere-center, a few dot products will tell you which face to sample and how to convert the angle into a UV.

For example, when you are working with the top face, the normalized pixel world X and Z will become the UV. On the face shown below, Y and Z change but X is constant. The dot products range from -1:1 and UV's are 0:1 so you'll also need a linear scaling and translation i.e. (XZ + 1) / 2

The same, from above:

Any point within the face has an angle away from "face-forward" of -45:45. This corresponds to the dot range -1:1. Again, scaling to 0:1 range is trivial. This diagram occurs twice for each point; the face determines which of the 3 axis' go into the UV.
> 0 votes

# Answer
Please confirm that my other answer is not-at-all or, less-, applicable, so I can delete it.

This is one way to "unwrap" a cube, (neglecting the bottom face (assuming there is a terrain of some kind)).

(right-handed)
For face 1:
U+ corresponds to Y+
V+ corresponds to Z+

For face 4:
U+ corresponds to X+
V+ corresponds to Y-

and so on..
> 0 votes

# Answer
As I done in my project Seamles Noise Generator

I suggest to apply a 3d noise (i.e. 3d perlin noise) on the cube surface and unwrap it like already suggested

And use a cube sphere aproach
> 0 votes

# Answer
Your question is similar to what I'm doing , but I'm using libnoise , doing most of the work for me .Can generate 4 faces of a icoespher using libnoise(they fit perfectly in a icoesphere) and saving as bmp, but unfortunately , there must be some wrong in libnoise , which causes distortion in the top faces and down , looked at the code utils::NoiseMapBuilderSphere, which takes two latitudes and two longitudes and turns in an image and everything seems ok , the code looks like the first answer from user41442.

```
/*snipt from libnoise utils::NoiseMapBuilderSphere.*/
model::Sphere sphereModel;
sphereModel.SetModule (*m_pSourceModule);

double lonExtent = m_eastLonBound  - m_westLonBound ;
double latExtent = m_northLatBound - m_southLatBound;
double xDelta = lonExtent / (double)m_destWidth ;
double yDelta = latExtent / (double)m_destHeight;
double curLon = m_westLonBound ;
double curLat = m_southLatBound;

// Fill every point in the noise map with the output values from the model.
for (int y = 0; y < m_destHeight; y++)
{
    float* pDest = m_pDestNoiseMap->GetSlabPtr(y);//get pointer to fill one slice of sphere, one at a time
    curLon = m_westLonBound;
    for (int x = 0; x < m_destWidth; x++)
    {
        float curValue = (float)sphereModel.GetValue (curLat, curLon);
        *pDest++ = curValue;
        curLon += xDelta;
    }
    curLat += yDelta;
}

```

my code for gen faces Z+ Z- X+ X-:

for each face i change that :

```
heightMapBuilder.SetBounds (-45.0, 45.0, -45.0, 45.0); //Z+  front
heightMapBuilder.SetBounds (-45.0, 45.0,    45.0, 135.0);//X+ right
heightMapBuilder.SetBounds (-45.0, 45.0,   -225.0, -135.0);//Z- back
heightMapBuilder.SetBounds (-45.0, 45.0,  -135,-45 );//X-     left

```

just do not understand why it does not work with latitudes 45,90 and longitudes -180,180 for generating face top.
> 0 votes

---
Tags: opengl, cubemap
---


# Question
Title: Unity animations not transitioning properly
I am currently trying to animate transitions between four different directions. I have four total animations for walking, and another four for the idle state. I cannot seem to figure out why when I try to transition from a walking state to another walking state in a different direction (not the direction I am idling in) it must wait for the walking animation to finish, and then play the walking animation in the new direction.

You can see my sprite begin to walk forward, and then when I attempt to turn south the animation it continually plays the north animation until the animation is finished. What I am trying to achieve is a smooth transition that switches immediately.

I know very little about animating and much more about programming. My list of attempted solutions is very short, and limited to only changing the length of each animation.

# Answer
Don't have enough points to comment but have you tried turning of **Has Exit Time**
> 3 votes

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


# Question
Title: How to set up Cocos2d-x for visual studio?
I want to make a cocos2d-x game. I read you can use any IDE, so I was planning to use Microsoft Visual Studio 2015, since I want to make my game primarily for Windows. I have been searching for tutorials, but i couldn't find any. It'd be great if someone wrote a step-by-step guide on how to set it up.

Thanks in advance.

# Answer
Follow the steps in this video for setup.

After you do all the steps in the video (you may need to restart here) run this command from the command line to create a new Cocos2d-x project:

`cocos new GameNameHere -p com.MyCompany.GameNameHere -l cpp -d path/to/project`

It's better not to use spaces in the names that you choose.

Go to the project directory that you choose and open it, where you should find:

```
Classes
cocos2d
proj.android
proj.android-studio
proj.ios_mac
proj.linux
proj.win8.1-universal
proj.win10
proj.win32
Resources
.cocos-project.json
CMakeLists.txt

```

Open the proj.win32 folder and go to a file named `YourGameName.sln`, where YourGameName should match the name you chose earlier.

Finally, just run the project and your done.
> 4 votes

---
Tags: cocos2d-x, visual-studio
---


# Question
Title: Gamemaker - Maintain relative position between objects during rotation
I have a large object and a small object - the small object updates its `x` and `y` position every step to match the `x` and `y` of the larger object. It is easy to keep it in the same position on the larger object without any rotation, as follows (in this instance, slightly above and to the right of the centre of the larger object, here called `Owner`:

```
x = Owner.x + 50
y = Owner.y - 50

```

However, this all goes pearshaped if the larger object is rotated from its sprite's initial position!

How can I maintain the relative position of the two objects even when rotated?

# Answer
> 2 votes
You need to use `lengthdir_x` and `lengthdir_y` functions, like:

```
x = owner.x + lengthdir_x(distance, owner.image_angle); // or owner.direction
y = owner.y + lengthdir_y(distance, owner.image_angle);

```

Also see answer for similar question, with an example and special tool for calculate values.

P.S. And remember that you need do it in `End Step` event, and not simple `Step`

# Answer
> 3 votes
I don't know about GameMaker, but usually you need to rotate second object with an angle of the first one like this:

```
// Distances between two object are needed
dx = 50;
dy = 50;

// Cosinus and Sinus are needed
cos = Cos(angle);
sin = Sin(angle);

// Calculate rotation
x = cos * dx - sin * dy + Owner.x;
y = cos * dy + sin * dx + Owner.y;

```

---

*You can also check Wikipedia article about rotation.*

---
Tags: game-maker
---


# Question
Title: LibGDX - Rotating sprites and still keep the positioning between them
I've been struggling with a problem regarding rotations and relative positions between sprites (in this case, the sprites are just lines) - a bit off-topic, but should i be using the ShapeRenderer class to do this, though?

Anyway, it might be quite simple but i can't seem to figure it out properly. Heres a picture of the situation: https://gyazo.com/78988e07991fedc778eaeb70f8a04d8e

Now, after trying a bunch of different approaches, this piece of code is the one i'm testing right now:

\` public class TestState extends AbstractGameState {

```
private static final String LINE = "lineEffect.png";

private Sprite[] sprites;

public TestState(GameStateManager gsm) {
    super(gsm);

    sprites = new Sprite[2];
    for (int i = 0; i < 2; i++) {
        sprites[i] = new Sprite(new Texture(LINE));
        // both lines starting at the same X and Y
        sprites[i].setPosition(20, 50);
        // both lines have the same size
        sprites[i].setSize(100, 2);
        // guess i might be messing up here
        sprites[i].setOrigin(sprites[i].getX(), sprites[i].getY());
    }

    // for testing purposes
    sprites[0].setRotation(-20);
    sprites[1].setRotation(45);
}

@Override
public void render(SpriteBatch batch) {
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    for (Sprite sprite : sprites)
        sprite.draw(batch);
    batch.end();
}`

```

Any help on this would be appreciated, thanks in advance.

# Answer
> 1 votes
You should set the origin to a line edge:

```
// guess i might be messing up here
sprites[i].setOrigin(0, 0);

```

It depends on real line location in lineEffect.png.

---
Tags: java, libgdx, sprites
---


title: Connect phone to computer?

text:
# Question
Title: Connect phone to computer?
In order to test out my game, I need to use my real life device. The problem is, android studio isn't recognizing my device plugged in:

**The problem:** My device isn't getting detected in android studio

**The solution:** Install the correct usb drivers

**The problem that arises to the solution:** I am not able to...and here are the details:

I have recently system wiped my computer due to slowness. This brings me back to the tedious task of setting up my computer for android studio. I have tried **everything** to get the usb drivers to work in android studio, but for some reason, I can't update my usb driver:

Now, here is the annoying screen that always pops up when trying to update my usb driver:

My usb driver **is installed:**

This is pretty pathetic. I have tried everything. **I even tried to go into my computers bios and disable Intel xHCI.** I remember when I first started android, I had this same problem, and the solution was to do something in the computer's bios, but the problem still persists.

By the way, I have done lots of research on this topic, and this is a code 28, which means it doesn't have the correct drivers:

I have been on this for 3 hours now (3 HOURS!) and would really appreciate **any** help. How can I get my phone recognized on my windows 8 laptop? I have done it before, so I know my phone is compatible. Is there something I need to do in the bios? Virtualization is already enabled in bios.

I would really appreciate any help, and you all have my upvote.

Thanks so much,

Ruchir

# Answer
> 5 votes
Not sure if this is really the right question for this site. But I still personally uninstalled and reinstalled my Android Driver to install it again. It's not in English but all buttons should be placed the same. Make sure you have the right driver for your devices. Some might require special drivers.

Select show all units.

Make sure you select the right driver. Click browse and navigate to where on your computer the driver is saved. The driver should end in .inf, android\_winusb.inf is this case.

Select show all units.

# Answer
> 0 votes
First make sure that you have virtualization on in the bios.

Next, make sure you have done what I have done in my question.

What I forgot to do was install the `android_winusb` file in the usb\_driver folder. The path should be `sdk\extras\google\usb_driver`. In my case, `C:\Users\Ruchir\AppData\Local\Android\sdk\extras\google\usb_driver`

After doing that, go **back** to device manager and go to the install as path. At the bottom of that should be another option:

Let me pick from a list of devices on my computer

Select your android phone, it shouldn't have a yellow exclamation mark over it any more. After that, select `composite ADB Interface`.

THAT'S IT.

---
Tags: android
---


# Question
Title: Multiple inputs for Google Cardboard on iOS and Android?
So far I am having a problem with having only a singular input mechanism (the magnetic trigger) for Google Cardboard games. Are there any other options to augment this in order to have at least two or three input "buttons" or triggers for a Cardboard app or are we stuck with one?

# Answer
> 1 votes
The only ways to add extra inputs is to either:

1. Connect a Bluetooth controller or another similar device.
2. Make your own custom Google Cardboard viewer with more buttons.

---
Tags: android, ios, virtual-reality
---


title: Strange Rotation in LWJGL

text:
# Question
Title: Strange Rotation in LWJGL
What I am trying to do is to create a Rubik's Cube game using LWJGL in Java. I have a lot of it done already, the only problem is the rotating. It just isn't working. I've tried multiple ways of rotating the cube but none of them seem to be working. Here's an image of what I've done so far:
It works fine as you can see. Now if I rotate the front slice, it also works well.
It seems to be messing up when the rotation is more that one. What I mean by that is when I rotate "F R D", this is front, right, and down. Like so:
But the problem occurs when I rotate the front side one more time, the rotation completely messes up:
As you can see, the cube rotates the wrong way. I don't know how to fix this.

What I've tried is calling three separate `GL11.glRotatef( ... )` functions but that hasn't worked. I've tried storing the rotations in a Matrix4f and then `GL11.glMultMatrix( ... )` and that has had the same output. I finally gave up and settled on this code here:

```
GL11.glPushMatrix();
GL11.glTranslatef(pos.offsetX * 1.1F, pos.offsetY * 1.1F, pos.offsetZ * 1.1F);
GL11.glRotatef(realRotation.x * 90F, 1F, 0F, 0F);
GL11.glRotatef(realRotation.y * 90F, 0F, 1F, 0F);
GL11.glRotatef(realRotation.z * 90F, 0F, 0F, 1F);
for (int i = 0; i < 6; i++)
{
    if (quads[i] != null)
    {
        quads[i].renderQuad();
    }
}
GL11.glPopMatrix();

```

I am at a loss now. If you need the variables and code up there defined: `realRotation` is a `javax.vecmath.Point3i` instance. All it has are the values from 0 to 3. It will never be greater than three, or less that zero. This is also the same reason why I am multiplying the values by 90 to rotate it 90 degrees each time. The `quads` array is just for rendering, it doesn't matter and has not caused a problem. Now the `pos` variable is an enum value that I have created to keep track of all the pieces in the game and where they are. Again, probably not the problem, but I don't know. It just might be the problem.

EDIT #1: I still haven't found any answer to the problem. The only other idea that I have gotten is that I can manually set the rotation to what it is actually supposed to be. I assumed that this will be EXTREMELY tedious and inefficient, so I've left that as a last resort. If I'm incorrect about this method, please feel free to let me know. I have a deadline for this project and I haven't gotten any progress beyond this.

EDIT #2: I have had an (I think) epiphany! I believe the problem for this peculiar rotational behavior is the cause of the Gimbal Lock. This is when an object is rotated in an axis, and the other axis pretty much becomes useless because of the previous rotation. This is explained very well with this GIF:
As you can see, once the plane is pitched to a 90 degree angle, roll and yaw are seemingly the same because of the pitch's rotation. On the wikipedia page, it is stated that a solution to this would be to use Quaternions, or so. I have not worked with Quaternions too much and still would like to hear if anyone has anything to say about this. I'm just guessing that this is the problem.

EDIT #3: After hours of studying and looking for an explanation as to what is going on. I have come up with nothing. I have still not solved the problem and I think I might have even made it worse. The code I have to render each cube is as follows:

```
GL11.glPushMatrix();
GL11.glTranslatef(pos.offsetX * 1.1F, pos.offsetY * 1.1F, pos.offsetZ * 1.1F);
//GL11.glRotatef(realRotation.z * 90F, 0F, 0F, 1F); // Roll
//GL11.glRotatef(realRotation.x * 90F, 1F, 0F, 0F); // Pitch
//GL11.glRotatef(realRotation.y * 90F, 0F, 1F, 0F); // Yaw

Quaternion roll = new Quaternion();
roll.setFromAxisAngle(new Vector4f(0F, 0F, -1F, rotation.z * 90F * DEG_TO_RAD));
roll.normalise();

Quaternion pitch = new Quaternion();
pitch.setFromAxisAngle(new Vector4f(-1F, 0F, 0F, rotation.x * 90F * DEG_TO_RAD));
pitch.normalise();

Quaternion yaw = new Quaternion();
yaw.setFromAxisAngle(new Vector4f(0F, -1F, 0F, rotation.y * 90F * DEG_TO_RAD));
yaw.normalise();

Quaternion change = Quaternion.mul(Quaternion.mul(roll, pitch, null), yaw, null);

FloatBuffer buff = BufferUtils.createFloatBuffer(16);
toFloatBuffer(change, buff);
GL11.glMultMatrix(buff);

for (int i = 0; i < 6; i++)
{
    if (quads[i] != null)
    {
        quads[i].renderQuad();
    }
}
GL11.glPopMatrix();

```

This is the toFloatBuffer method: dest.clear();

```
float x = quat.x;
float y = quat.y;
float z = quat.z;
float w = quat.w;

float x2 = x * x;
float y2 = y * y;
float z2 = z * z;
float xy = x * y;
float xz = x * z;
float yz = y * z;
float wx = w * x;
float wy = w * y;
float wz = w * z;

dest.put(1.0f - 2.0f * (y2 + z2));
dest.put(2.0f * (xy - wz));
dest.put(2.0f * (xz + wy));
dest.put(0.0f);
dest.put(2.0f * (xy + wz));
dest.put(1.0f - 2.0f * (x2 + z2));
dest.put(2.0f * (yz - wx));
dest.put(0.0f);
dest.put(2.0f * (xz - wy));
dest.put(2.0f * (yz + wx));
dest.put(1.0f - 2.0f * (x2 + y2));
dest.put(0.0f);
dest.put(0.0f);
dest.put(0.0f);
dest.put(0.0f);
dest.put(1.0f);

dest.rewind();

```

Again, this isn't working and I (once again) am absolutely clueless. The page I am looking at to figure out this stuff is this page. Don't even know if it's right. I got it from my Physics teacher who is also working on Quaternions. Once again, I have a deadline for this project and I would love it if I can get this done by then. I am willing to accept anything anyone says, I really need a lead on this. I keep hitting walls after walls.

# Answer
Quaternions can't suffer from gimbal lock; they are functionally identical to full matrix multiplations. However, the angles you use to generate them can be wrong.

The problem is that you are generating your rotations around fixed angles, in your case Cartesian unit vectors. You can't do that; your rotation axes must rotate along with everything else. Yours are static.

Whether you're doing this:

```
GL11.glRotatef(realRotation.x * 90F, 1F, 0F, 0F);
GL11.glRotatef(realRotation.y * 90F, 0F, 1F, 0F);
GL11.glRotatef(realRotation.z * 90F, 0F, 0F, 1F);

```

...or this:

```
roll.setFromAxisAngle(  new Vector4f( 0F, 0F,-1F, rotation.z * 90F * DEG_TO_RAD));
pitch.setFromAxisAngle( new Vector4f(-1F, 0F, 0F, rotation.x * 90F * DEG_TO_RAD));
yaw.setFromAxisAngle(   new Vector4f( 0F,-1F, 0F, rotation.y * 90F * DEG_TO_RAD));

```

Both are using fixed unit vectors.

---

You need relative axes in order to calculate the changes in rotation. `roll` must be calculated around a `relative-forward` vector, `pitch` must be rotated around `relative-right`, and `yaw` must be calculated around `relative-up`.

And on top of that, changing `roll` changes `relative-up` and `relative-right`, `pitch` changes `relative-forward` and `relative-up`, and `yaw` changes `relative-forward` and `relative-right`.

---

Alternately, you could simply store your current orientation as a full transform matrix. Then the number of manual operations would be reduced greatly. You would still need to calculate the additional rotations on the transformed (relative) axes, but you could use that same matrix to transform them.
> 1 votes

---
Tags: java, rotation, lwjgl
---


title: Rotate sprite direction Cocos2d

text:
# Question
Title: Rotate sprite direction Cocos2d
I want that my sprite go always forward, and you can only control his direction moving right and left (on 360 degrees). I don't know why, but the movement it's senseless.

The constants to move and rotate:

```
const int POD_DEGRE_MOVE = 5;
const int POD_STEP_MOVE = 3;

```

The sprite initalization:

```
_dragonSprite->setPosition(Point(visibleSize.width / 2,_dragonSprite->getContentSize().height * 0.75));
addChild(_dragonSprite, 2);

```

The event key listener:

```
void GameScene::onKeyPressed(EventKeyboard::KeyCode keyCode, Event *event){
    _pressedKey = keyCode;

    switch (_pressedKey) {

    case EventKeyboard::KeyCode::KEY_LEFT_ARROW:
        giro = -POD_DEGRE_MOVE;
        _isMoving = true;
        break;
    case EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
        giro = POD_DEGRE_MOVE;
        _isMoving = true;
        break;

    }

}
    void GameScene::onKeyReleased(EventKeyboard::KeyCode keyCode, Event *event){
        if (_pressedKey == keyCode) {
            _pressedKey = EventKeyboard::KeyCode::KEY_NONE;
            _isMoving = false;
            giro = 0;
        }
    }

```

And the calculations of the new direction:

```
void GameScene::update(float dt) {

    _dragonSprite->setRotation(_dragonSprite->getRotation() + giro);
    _podVector = Vec2(cos(_dragonSprite->getRotation()) * POD_STEP_MOVE, sin(_dragonSprite->getRotation()) * POD_STEP_MOVE);
    Vec2 newPos = Vec2(_dragonSprite->getPosition().x + _podVector.x, _dragonSprite->getPosition().y + _podVector.y);

_dragonSprite->setPosition(newPos);
}

```

Another problem is that the sprite at the start moves to the right (because Cos(0)==1), so I rotate the image of the sprite 90 degrees to the right, to then rotate it again at the initialization 90 to the left so the sprite is in the right position and his start angle is 90 (sin(90)==1), but the angle is not 90, and it moves as he wishes.

The last problem I have with this is that when I press a key (right or left), the sprite stops, rotates, and starts again (a direction that is not the direction where the sprite is aiming, that's the main problem). The sprite shouldn't stop while you are moving it.

Can anyone help me?

# Answer
Te problem here was that the cocos method to rotate an sprite uses degrees, but the sin() and cos() methods are from the math library of c++, so they work with radians. In the end I've made a function to change from degrees to radians and use it to transform the \_dragonSprite-\>getRotation() to rads.
> 0 votes

---
Tags: sprites, rotation, movement, cocos2d, cocos2d-x
---


title: FAST position reconstruction from depth

text:
# Question
Title: FAST position reconstruction from depth
I'm struggling a lot with reconstructing the world space position (or alternatively the view space position) from depth (by reading the depth buffer) in a performant way (in a full-screen post-process).

So far I've been using this approach:

```
vec3 calculate_world_position(vec2 texture_coordinate, float depth_from_depth_buffer)
{
    vec4 clip_space_position = vec4(texture_coordinate * 2.0 - vec2(1.0), 2.0 * depth_from_depth_buffer - 1.0, 1.0);

    //vec4 position = inverse_projection_matrix * clip_space_position; // Use this for view space
    vec4 position = inverse_view_projection_matrix * clip_space_position; // Use this for world space

    return(position.xyz / position.w);
}

```

While this works perfectly, it's really slow. What I'm looking for is an approach like this:

```
vec3 world_position = world_space_eye_position + view_direction * depth;

```

I have found a couple of results on google but most are based on DirectX and I didn't understand them and therefore I have failed to implement them.

# Answer
I found a solution that works well. I don't think it gets any faster than this.

What I did first is, I did the matrix-vector multiply by manually and skipped all the matrix components which are zero. I used an inverse projection matrix for this (to transform to view space). That left me with this code:

```
vec3 calculate_view_position(vec2 texture_coordinate, float depth_from_depth_buffer)
{
    vec3 clip_space_position = vec3(texture_coordinate, depth_from_depth_buffer) * 2.0 - vec3(1.0);

    vec4 view_position = vec4(vec2(inverse_projection_matrix[0][0], inverse_projection_matrix[1][1]) * clip_space_position.xy,
                                   inverse_projection_matrix[2][3] * clip_space_position.z + inverse_projection_matrix[3][3]);

    return(view_position.xyz / view_position.w);
}

```

Then I tried to get rid of the clip space position calculation so I can use the texture coordinate and depth directly. I did that by biasing the projection matrix (moving the coordinate system from -1.0 ... 1.0 to 0.0 ... 1.0) in C++ and then inverting it and supplying it as a uniform. The performance boost of doing that was small, but it's something. The final shader code looks like this:

```
vec3 calculate_view_position(vec2 texture_coordinate, float depth_from_depth_buffer)
{
    vec4 view_position = vec4(biased_inverse_projection_matrix[0][0] * texture_coordinate.x + biased_inverse_projection_matrix[3][0],
                          biased_inverse_projection_matrix[1][1] * texture_coordinate.y + biased_inverse_projection_matrix[3][1],
                          -1.0,
                          biased_inverse_projection_matrix[2][3] * depth_from_depth_buffer + biased_inverse_projection_matrix[3][3]);

    return(view_position.xyz / view_position.w);
}

```

The C++ matrix biasing code looks like this:

```
const MATH::FLOAT4X4 bias_matrix(0.5f, 0.0f, 0.0f, 0.5f,
                                 0.0f, 0.5f, 0.0f, 0.5f,
                                 0.0f, 0.0f, 0.5f, 0.5f,
                                 0.0f, 0.0f, 0.0f, 1.0f);

MATH::FLOAT4X4 inverse_biased_projection_matrix = projection_matrix * bias_matrix; // Offsets the projection matrix' clip space coordinates from -1.0 - 1.0 to 0.0 - 1.0.
MATH::FLOAT4X4::invert(inverse_biased_projection_matrix);

glUniformMatrix4fv(uniform.id, 1, GL_FALSE, &inverse_biased_projection_matrix.elements[0][0]);

```

Depending on how you calculate your projection matrix, this might not work for you.

**======== UPDATE ========**
If you're linearizing your depth buffer or storing the view space z (like me now), you can do the following, which is the fastest possible way to reconstruct the view space position:

**Vertex shader (can also be supplied as a uniform):**

```
v_fov_scale.x = tan(fov_x / 2.0);
v_fov_scale.y = tan(fov_y / 2.0);
v_fov_scale *= 2.0; // Required to avoid the multiplication by 2.0 in the fragment shader at "vec2 P_ndc = vec2(1.0) - texture_coordinate * 2.0;".

```

**Fragment shader:**

```
vec3 calculate_view_position(vec2 texture_coordinate, float depth, vec2 scale_factor)  // "scale_factor" is "v_fov_scale".
{
    vec2 half_ndc_position = vec2(0.5) - texture_coordinate;    // No need to multiply by two, because we already baked that into "v_tan_fov.xy".
    vec3 view_space_position = vec3(half_ndc_position * scale_factor.xy * -depth, -depth); // "-depth" because in OpenGL the camera is staring down the -z axis (and we're storing the unsigned depth).
    return(view_space_position);
}

```

What this method does is, it basically computes a ray from the camera position to the far plane (in view space), which then gets scaled by the depth from the texture. If you aren't storing the view space Z, but just the normalized, linear depth, then you should multiply `v_fov_scale` with your depth range (zFar - zNear) and offset the coordinate to zNear in the fragment shader.
> 5 votes

---
Tags: opengl, glsl, deferred-rendering, deferred-shading
---


# Question
Title: Terrain shader from heightmap opengl GLSL
I generated a terrain from a heightmap and now I'd like to apply shader on it which can contain different textures, based on height but I can't adapt any online code to my project. This is the GL\_LINE rendered image

The matrix generated from the heightmap has 0-255 values and -1 as the endline character.

This is the code of the terrain, the matrix is stored in a `map<int, map<int, int>> data;`structure:

```
#include "Terrain.h"

Terrain::Terrain(Scene* s, string filename): Entity(s) {
    this->hm = s->getHeightmap(filename);
    texture = scene->getTexture("avatar2.jpg");
    shader = scene->getShader("terrain.shader");
}

Terrain::~Terrain() {
}

void Terrain::draw() {
    cout << "Draw Terrain" << endl;
    glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
    //glUseProgramObjectARB(0);
    glUseProgram(this->shader->getRes());
    glTranslated(0, -20, -31.4);
    glRotatef(45, -1, 0, 0);

    const float offX = -25;
    const float offY = 0;
    const float lato = 0.5;
    const int limit = 100;
    const int limsx = 0;

    glBegin(GL_QUADS);
    for (float i = limsx; i < limit-1; ++i) {
        for (float j = limsx; j < limit-1; ++j) {
            glVertex3f(offX+lato*(j+1), offY+lato*i, hm->getHeight(i,j+1)/50);
            glVertex3f(offX + lato*(j + 1), offY + lato*(i + 1), hm->getHeight(i + 1, j+1)/50);
            glVertex3f(offX + lato*j, offY + lato*(i + 1), hm->getHeight(i+1, j)/50);
            glVertex3f(offX + lato*j, offY + lato*i, hm->getHeight(i, j)/50);
        }
    }
    glEnd();
}

```

Can you help me generating a terrain shader? Thank you very much

EDIT: thanks a lot to sakul\_ca. This is what I got by using and editing his code

I used a shader that applies 4 textures to different heightmap values

# Answer
> 5 votes
To give you exactly what you are asking for, look at the bottom two code examples.

To use those code examples, there are other code examples preceding it. These examples are using Vertex Buffer Objects. Which is something you should start using, and not "glBegin/glVertex/glEnd", because those are all deprecated OpenGL functions.

You are asking for multiple textures in your question too. You can do that by adding another texture with the shaders, and set them in the appropriate places in the C++ code.

*Load Function*

```
void LoadModel ( void )
{
    // ...
    // 1. Load the model from file.
    // 2. Get model information
    //  - Number of vertices
    //  - Texture coordinates
    // 3. Make Data information
    //  - e.g.
    //  - Vertex_p4t4* pTempVertArray = new Vertex_p4t4[numVertices *2];
    //  - GLuint* pIndexArrayLocal = new GLuint[numIndicesInIndexArray * 2];
    // ...

    GLuint vboID;
    glGenVertexArrays( 1, &vboID );
    // Check for OpenGL error.

    glBindVertexArray( vboID );
    // Check for OpenGL error.

    // [SimpleTextureShader.vertex.glsl]
    // layout (location=0) in vec4 in_Position
    // layout (location=1) in vec4 in_UVx2;
    glEnableVertexAttribArray ( 0 );
    glEnableVertexAttribArray ( 1 );
    // Check for OpenGL error.

    GLuint vertexBufferID;
    GLuint indexBufferID;
    glGenBuffers ( 1, &vertexBufferID );
    glGenBuffers ( 1, &indexBufferID );
    // Check for OpenGL error.

    glBindBuffer ( GL_ARRAY_BUFFER, vertexBufferID );
    // Check for OpenGL error.

    // In this case [sizeof ( YOURVERTEXDATA )] = 32)
    unsigned int vertSize = sizeof ( YOURVERTXDATA );
    unsigned int size = numVerticesInModel * vertSize ;
    glBufferData ( GL_ARRAY_BUFFER, size, VERTEXDATA, GL_STATIC_DRAW );
    // Check for OpenGL error.

    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, vertSize, 0 );
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, vertSize, 16 );
    // Check for OpenGL error.

    glBindBuffer ( GL_ELEMENT_ARRAY_BUFFER, indexBufferID );
    // Check for OpenGL error.

    glBufferData ( GL_ELEMENT_ARRAY_BUFFER, TOTALSIZEINBYTES, pIndexArrayLocal, GL_STATIC_DRAW);
    // Check for OpenGL error.

    glBindVertexArray( 0 );
    // Check for OpenGL error.

    // ...
    // Delete things you don't need anymore
    // ...
    // Add model information to wherever you want
    // ...

    return;
}

```

*Render Function*

```
void Render ( void )
{
    // Set the texture shader program
    glUseProgram(currentProgramID);

    // uniform mat4 ModelMatrix;
    // uniform mat4 ViewMatrix;
    // uniform mat4 ProjectionMatrix;
    // uniform sampler2D texture_0;

    // Normally you would get this information when loading the shader, and save all of the data somewhere else instead of getting it every time you render.
    GLint ModelMatrixUniformLocation = getUniformLocation ( currentShaderProgramID, "ModelMatrix" );
    GLint ViewMatrixUniformLocation = getUniformLocation ( currentShaderProgramID, "ViewMatrix" );
    GLint ProjectionMatrixUniformLocation = getUniformLocation ( currentShaderProgramID, "ProjectionMatrix" );
    GLint Texture0UniformLocation = getUniformLocation ( currentShaderProgramID, "texture_0" );

    // I'm using glm for this example, you can use whatever math library you wish, or write your own.

    // Create a model matrix to use
    glm::mat4 matModel = glm::mat4( 1.0f ); // initialize as identity;

    // Create a view matrix to use
    glm::mat4 matView = glm::lookAt(eye, look, up);

    // Create a projection matrix to use
    glm::mat4 matProj = glm::perspective( fovy, aspect, zNear, zFar );

    // OpenGL does matrix Transformation Calculations backwards, so you want to do:
    // Post Rotation, Translating, Pre Rotation, Scale
    // We are only translating in this example
    matMode = matMode = glm::translate ( matMode, ObjectPosition );

    // Send the matrix values to the shader program
    glUniformMatrix4fv( ModelMatrixUniformLocation, 1, GL_FALSE, glm::value_ptr ( matModel ));
    glUniformMatrix4fv( ViewMatrixUniformLocation, 1, GL_FALSE, glm::value_ptr ( matView));
    glUniformMatrix4fv( ProjectionMatrixUniformLocation, 1, GL_FALSE, glm::value_ptr ( matProj));

    // Send the texture information to the shader program
    glActiveTexture(textureEnum);
    // Check for OpenGL error.

    glBindTexture(GL_TEXTURE_2D, textureID);
    // Check for OpenGL error.

    glUniform1i ( Texture0UniformLocation, textureID );
    // Check for OpenGL error.

    // Render your object(s) [ vboID from LoadTexture function ]
    glBindVertexArray ( vboID );
    // Check for OpenGL error.

    unsigned int numberOfIndices = NumberOfTrianglesInMesh * 3;
    glDrawElements ( GL_TRIANGLES, numberOfIndices, GL_UNSIGNED_INT, (GLvoid*)0 );
    // Check for OpenGL error.

    // All done
    return;
}

```

*SimpleTextureShader.vertex.glsl*

```
#version 400

layout (location=0) in vec4 in_Posiiton;
layout (location=1) in vec4 in_UVx2;

out vec4 ex_Position;
out vec4 ex_UVx2;

uniform mat4 ModelMatrix;
uniform mat4 ViewMatrix;
uniform mat4 ProjectionMatrix;

void main ( void )
{
    mat4 MVPMatrix = ProjectionMatrix * ViewMatrix * ModelMatrix;
    gl_Position = MVPMatrix * in_Position;

    ex_Position = gl_Position;
    ex_UVx2 = in_UVx2;

    return;
}

```

*SimpleTextureShader.fragment.glsl*

```
#version 400

// From the vertex shader
in vec4 ex_Position;
in vec4 ex_UVx2;

// Texture information
uniform sampler2D texture_0;

// If you want multiple textures...
// uniform samples2D texture_1;
// uniform samples2D texture_2;
// uniform samples2D texture_3;
// ...

void main ( void )
{
    vec4 colour = vec4 ( 0.0f, 0.0f, 0.0f, 0.0f );
    colour = texture( texture_0, ex_UVx2.xy );

    // if you want multiple textures...
    // vec4 texture1Colour = texture( texture_1, ex_UVx2.xy );
    // vec4 texture2Colour = texture( texture_2, ex_UVx2.xy );
    // vec4 texture3Colour = texture( texture_3, ex_UVx2.xy );
    // Then do what you want with them.. e.g.
    // vec4 tex1Times2 = texture1Colour * texture2Colour;
    // vec4 texHeightColour = texture1Colour * ( 10.0f - gl_Position.y )
    // texHeightColour += texture2Colour * gl_Position;
    // colour= clamp ( texHeightColour, 0.0f, 1.0f );

    out_Colour = colour;

    return;
}

```

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


title: Libgdx incredibly high RAM usage!

text:
# Question
Title: Libgdx incredibly high RAM usage!
Alright so I'm new to Libgdx and Game programming in general, and I've got a huge problem.

If I leave my game on, it will start to eat memory, pretty fast at that, until it reaches a point my PC hasn't enough so it forcefully shuts it down (I have 24GB of RAM!!!)

What could be the reason for this, I don't have FPS lag or anything.

# Answer
Looks like making a new SpriteBatch ever update wasn't such a smart idea of me!

Lesson learned!
> 1 votes

---
Tags: libgdx, memory-efficiency, memory
---


title: Pathfinding assistance

text:
# Question
Title: Pathfinding assistance
Here's a quick image:

I've generated a navmesh for my game that shows how an AI can get to each of its possible neighboring tiles in a map. (I followed some gamasutra article as reference, I'll paste a link if I can find it again). You can see that it calculates all possible jump, fall, and walking connections between points.

Now that I have this, I've been researching how to actually use it. I understand that A\* is generally the algorithm that people use but I haven't been able to find a resource for adapting it to a non-grid based dataset. Any articles that you know of or pseudocode would be awesome :)

# Answer
> -1 votes
Have you look at wikipedia? there is this sample code: https://en.wikipedia.org/wiki/A\*\_search\_algorithm

```
function A*(start,goal)
    ClosedSet := {}       // The set of nodes already evaluated.
    OpenSet := {start}    // The set of tentative nodes to be evaluated, initially containing the start node
    Came_From := the empty map    // The map of navigated nodes.

    g_score := map with default value of Infinity
    g_score[start] := 0    // Cost from start along best known path.
    // Estimated total cost from start to goal through y.
    f_score := map with default value of Infinity
    f_score[start] := g_score[start] + heuristic_cost_estimate(start, goal)

    while OpenSet is not empty
        current := the node in OpenSet having the lowest f_score[] value
        if current = goal
            return reconstruct_path(Came_From, goal)

        OpenSet.Remove(current)
        ClosedSet.Add(current)
        for each neighbor of current
            if neighbor in ClosedSet
                continue        // Ignore the neighbor which is already evaluated.
            tentative_g_score := g_score[current] + dist_between(current,neighbor) // length of this path.
            if neighbor not in OpenSet  // Discover a new node
                OpenSet.Add(neighbor)
            else if tentative_g_score >= g_score[neighbor]
                continue        // This is not a better path.

            // This path is the best until now. Record it!
            Came_From[neighbor] := current
            g_score[neighbor] := tentative_g_score
            f_score[neighbor] := g_score[neighbor] + heuristic_cost_estimate(neighbor, goal)

    return failure

function reconstruct_path(Came_From,current)
    total_path := [current]
    while current in Came_From.Keys:
        current := Came_From[current]
        total_path.append(current)
    return total_path

```

# Answer
> 2 votes
A\* is a graph based algorithm. The only thing that would change between a grid-based algorithm and a graph-based algorithm is that when you're determining neighbors, your algorithm changes from picking neighboring squares to picking nodes that are connected to the current node.

You can basically think of a grid like a graph, which each square being a node, and each square having a connection to its neighbors.

---
Tags: path-finding
---


# Question
Title: Do physics engines take shape into account or they operate solely on predefined variables?
I have never given it much of a thought about how physics engines operate behind the scenes.

Though, I am currently working on a game that would greatly benefit from as precise as possible physics model, hence the question.

To apply the counter forces, do physics engines, such as Havoc, Bullet and PhysX, take into account the actual shape of the mesh (probably only it's collider) or they operate solely as math functions working with only the predefined physical variables (mass, drag, friction etc.)?

I know that collisions operate on colliders and their shapes, but I am thinking about aerodynamics, gravity and other forces that are counter-applied while objects are in motion.

# Answer
> 4 votes
Physics engines for games do not take shape into account for these kinds of calculations, though they can have various bits of data like center of mass and moment of inertia (which help to *approximate* shape for some uses) used in calculations.

You can somewhat improve things by having complex objects made up of multiple physics bodies held together via constraints, but particularly complex configurations are likely to run into various simulation stability problems.

It is not currently realistic to take shape into account for these calculations for the kinds of of objects and world sizes that general game physics engines handle. If you need a very precise physics simulation for a narrowly-scoped application you can possibly write what you need yourself.

There are very powerful physics libraries available for "professional" simulation in science and military applications that but these are not generally available or even that useful for games.

That said, if you are indeed making a game, you almost certainly don't need as high a level of accuracy as you think. Games are smoke and mirrors. You can apply a lot of tricks to make aerodynamics seem more realistic and meaningful to gameplay without actually needing to do a full fluid sim of the air so long as you properly scope things.

---
Tags: physics
---


# Question
Title: 2D Spaceship Thruster Movement - Turning
I have a spacecraft (shown in the image) built out of ‘blocks’ / 3D planes. It is drawn within a 3D space, but I’m ignoring the Y axis for now and keeping things on a “2D” XZ axis.

The ship has a number of thruster blocks (represented in blue); each of which should fire depending on user input (does the user want to go forward? or turn left? etc).

Although the image doesn’t show it, each thruster is oriented in a logical direction; i.e the thrusters labelled A & E point left, B & F point right, thrusters G & H point down, thrusters C & D point up.

Thrusters are placed arbitrarily around the ship. There is no actual 'Thruster A' or 'Thruster B'; I'm just using the spacecraft in the above image as an example.

I already have the following which works for forward/backward thrust and strafing (in pseudo code):

```
foreach(thruster in ship.thrusters) {

    // Forward thrust
    if(keyPressed W) && thruster.direction == ShipLocalSOUTH) {

        thruster.fire();
    }

    // Backward thrust
    if(keyPressed S) && thruster.direction == ShipLocalNORTH) {

        thruster.fire();
    }

    // Strafe Left
    if(keyPressed Q) && thruster.direction == ShipLocalEAST) {

        thruster.fire();
    }

    // Strafe right
    if(keyPressed E) && thruster.direction == ShipLocalWEST) {

        thruster.fire();
    }

    // Turn left
    if(keyPressed A && ??) {

        // ??
    }

    // Turn right
    if(keyPressed D && ??) {

        //??
    }
}

class Thruster {

    private thrusterPower = 10;

    public void fire() {

        shipRigidbody.AddForceAtPosition (thruster.transform.forward * thrusterPower, thruster.transform.position);
    }
}

```

**My problem lies in determining which thrusters to fire to turn the ship.**

I’ve done a lot of googling on this and have found quite a lot of info already. I.e:

Using Torque and Thrusters to Move and Rotate a Player-Designed Spaceship

However my maths/trig skills are - to be blunt - crap and so I’m hoping to get a somewhat simpler explanation or even some code to help me understand and solve this problem. I'm not aiming for superbly accurate physics, just something that is fun to play.

# Answer
If you know the center, you have to find out if the thruster is above or below and left or right of your center.

```
public class Thruster : MonoBehaviour {

public Transform center;
public ThrusterType type;

public bool IsBelowCenterAxis {
    get {
        return transform.localPosition.z<center.localPosition.z;
    }
}

public bool IsLeftOfCenterAxis {
    get {
        return transform.localPosition.x<center.localPosition.x;
    }
}

public bool IsAboveCenterAxis {
    get {
        return transform.localPosition.z>center.localPosition.z;
    }
}

public bool IsRightOfCenterAxis {
    get {
        return transform.localPosition.x>center.localPosition.x;
    }
}

public void fire() {

}

}

```

and then :

```
if(Input.GetKey(KeyCode.A) &&
            ((thruster.type == ThrusterType.LEFT && thruster.IsBelowCenterAxis) ||
             (thruster.type == ThrusterType.RIGHT && thruster.IsAboveCenterAxis) ||
             (thruster.type == ThrusterType.UP && thruster.IsLeftOfCenterAxis) ||
             (thruster.type == ThrusterType.DOWN && thruster.IsRightOfCenterAxis))) {

            thruster.fire();
        }

        if(Input.GetKey(KeyCode.D) &&
           ((thruster.type == ThrusterType.RIGHT && thruster.IsBelowCenterAxis) ||
            (thruster.type == ThrusterType.LEFT && thruster.IsAboveCenterAxis) ||
            (thruster.type == ThrusterType.DOWN && thruster.IsLeftOfCenterAxis) ||
            (thruster.type == ThrusterType.UP && thruster.IsRightOfCenterAxis))) {

            thruster.fire();
        }

```

Now you just need to know the force with which to fire, but that's a different question.
> 0 votes

---
Tags: unity, physics-engine
---


# Question
Title: Why is GameObject.FindGameObjectsWithTag returning null?
I'm currently working on refactoring my gravity simulator, but I'm running into a problem. I have two `GameObject`s, both tagged with the tag `"Body"`, as you can see below:

I'm attempting to cache a list of all `GameObject`s like so:

> ```
> private GameObject[] _bodies;
>
> ...
>
> public void Start()
> {
>     ...
>     this._bodies = GameObject.FindGameObjectsWithTag("Body");
>     ...
> }
>
> ```

When I try to use the value `this._bodies` though, as seen in the `foreach` loop below, I get a `NullReferenceException`.

> ```
> foreach(GameObject body in this._bodies)
> {
>     ...
> }
>
> ```

I have verified that the value of `this._bodies` is `null`, using this piece of code:

> ```
> Debug.Log(this._bodies);
>
> ```

I'm honestly stumped as to why `GameObject.FindGameObjectsWithTag` is returning `null` when I run it. Is there a way to solve this?

For reference, here's the full code involved:

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

[RequireComponent(typeof(Rigidbody))]
public class GravityComponent : MonoBehaviour
{
    public double gravitationalConstant = 6.674 * Mathf.Pow(10, -11);
    public Vector3 startingForce;

    private GameObject[] _bodies;
    private Dictionary<GameObject, double> _massProducts;
    private Rigidbody _bodyRigidbody;

    /// <summary>
    /// Initalize various private values and caches, like the
    /// cache of bodies, masses, etc.
    /// </summary>
    public void Start()
    {
        this._bodyRigidbody.AddForce(this.startingForce);
        this._bodyRigidbody = GetComponent<Rigidbody>();
        this._bodies = GameObject.FindGameObjectsWithTag("Body");
        this._massProducts = this._bodies.ToDictionary(
            body => body,
            body =>
                  this.gravitationalConstant
                * this._bodyRigidbody.mass
                * body.GetComponent<Rigidbody>().mass
        );
    }

    /// <summary>
    /// Calculate the attractions between two separate bodies, and
    /// then apply the calculated attraction.
    /// </summary>
    public void ApplyAttraction()
    {
        foreach(GameObject body in this._bodies)
        {
            Vector3 bodyPositionDifference = body.transform.position - this.transform.position;
            double attraction = this._massProducts[body] / bodyPositionDifference.sqrMagnitude;
            this._bodyRigidbody.AddForce(bodyPositionDifference * (float)attraction);
        }
    }

    public void FixedUpdate()
    {
        Debug.Log(this._bodies);
        this.ApplyAttraction();
    }
}

```

# Answer
\*gulp\*

Simple typographical errors, the bane of every programmer ever. In the end, all I had to do was swap these two lines, simply because I was attempting to use the `Rigidbody` of the object *before* I assigned it a value.

> ```
> this._bodyRigidbody.AddForce(this.startingForce);
> this._bodyRigidbody = GetComponent<Rigidbody>();
>
> ```

After swapping, these two lines became this:

```
this._bodyRigidbody = GetComponent<Rigidbody>();
this._bodyRigidbody.AddForce(this.startingForce);

```

Some days it just pays to double-check things.
> 4 votes

---
Tags: unity
---


# Question
Title: Can someone help me with my mario-inspired timer scoring system?
I am new to GameMaker's coding language or GML. I have learned and done a lot so far, but now i am having a problem. I have a countdown timer starting at 5 minutes counting down and I want the player to receive points based on how much time is left kind of like in Super Mario Bros. along with the points accumulated for performing other tasks. How do I go about doing this with the coding language? Thanks in advance!

# Answer
My suggestion may sound obvious, but why don't you try the following.

1) Save in a counter the time left when a player finishes the current level. Let's call it "time\_left".

2) Set a loop that runs, for instance, every millisecond. At each iteration of that loop, you decrease X from "time\_left".

3) At the same time, at each iteration you increase X\*Y your score counter.

The trick here is only the values you will use for X and Y. The simplest way is to chose X=1, because then Y becomes merely the value you give as a score-give per each millisecond, depending on your score scale. Of course, if the loop at step 2 runs for every each millisecond, then Y probably should probably be a small float number.

I never worked with GameMaker, so I don't know its language. In C#, you could easily accomplish that with a Couroutine that at the end, yields a "wait for seconds". But if you have a problem making a loop run every given time (e.g. each millisecond or second or whatever) in your language and also wants the counting to be slower so the player can see it, you can also try just decreasing X from the "time\_left" counter and increasing X times Y to the score counter, every frame\*delta.Time.

It's a simple solution, but that can work pretty well depending on what you want.

PS: in case you don't know what I mean by delta.Time, it is a measure of how much time has elapsed since the last frame was ended and the current began.
> 2 votes

---
Tags: game-maker, timer, scoring
---


# Question
Title: Questions on the legal protection of games and their parts (assets, sounds, title)
we started new pirate game, and I just want to ask some questions about rights. So I am new in game dev, I guess there are a lot of answers, but I guess professionals can advise something for first steps.

So we started some things like:

1. concept arts
2. sounds
3. we are working on the name of the game (just use temp one for now)
4. we develop some models of ships and characters

I have question what's my step to protect everything I listed above. Do I need to protect everything separately? Do I need to register a game somewhere? Can I use my already made domain and subdomain for the game? Or do I need to register unique one domaine.

# Answer
> 4 votes
First of all, I am not a lawyer and in this site questions about these issues have to be always taken as ideas, thoughts or experiences, never as technical advice.

Second, I see you are not from US and I have to tell you that what I am about to say is fairly based on the US laws.

So, that said, you don't need, but you can and you likely should copyright the specific parts of your game. Let's see.

> we are working on the name of the game (just use temp one for now)

Game titles are usually not copyrightable, but they can be protected under trademarks. Those are different things. But yes, you should trademark your game title when possible.

> Do I need to protect everything separately?

Kind of. Code is copyrighted similarly to literary works, although there is quite a debate on to which extent code can/should be patented. While art and sound are usually copyrighted as audiovisual.

> Can I use my already made domain and subdomain for the game? Or do I need to register unique one domaine

If you are talking about your website, that's your choice. As far as my experience with that goes, your game doesn't even need to have a website, and it certainly doesn't need to have the same name as the game. You can have a website like www.mycompany.com/mygame. No problem with that. It's your choice, not a legal requirement.

---

Now, about your more general question about whether you should or not pursue legally protecting your game and its pieces, I think at some point you should. There is quite an interesting article on the NewMediaRights website, on copyright, trademarks and intelectual property for video-games: http://newmediarights.org/guide/legal/Video\_Games\_law\_Copyright\_Trademark\_Intellectual\_Property

As they say, "While you don’t need to have the work (ie your video game) registered to covered by copyright law, there are advantages to registration (see our guide to copyright law)".

So, what are these advantages? The most obvious are: first, it is much more effective in scaring people off trying to use your stuff without authorization. Second, it makes eventual legal battles easier to win. Third, it saves you the eventual legal battle part of proving you did create what you are saying you created. That saves time and money. Fourth, it is cheap, as already said in other answer. Among other things. The NewMediaRights has a very good guide for Copyright as well: http://www.newmediarights.org/frequently\_asked\_questions\_about\_copyright\_law\_book You will be particularly interested in the section "IV. Now that I have the copyright to something, what does this allow me to do?".

For a basic introduction to the questions related to copyright, trademark and etc, you can also try the Gamasutra article: http://www.gamasutra.com/view/feature/3546/hey\_thats\_my\_game\_intellectual\_.php?print=1

---

But of course, I don't want to mean you have to be over-concerned at the very beginning. I think that this is the kind of problem I start thinking of more when the project has developed quite a bit. After all, as I just said above, at least in the US and countries with which the US has treaties on these things, just by making something you already have a set of rights about it, even it you didn't copyright.

Still, if you made graphical or sound assets that, in case your project is eventually abandoned, you would still try profit on somehow, that's a stronger incentive for protecting them from the beginning. You would be surprised how often people take other's assets without permission even for professional-ish uses. Not to mention how many assets are put online as if they were copyright-free, when they are not.

# Answer
> 2 votes
In short, "Register with the US Copyright Office, but otherwise don't worry." (Or whatever your national copyright organization happens to be.)

I expect others have more nuanced, more informed opinions on this, but here's my thoughts anyways. And of course:

**None of this should be taken as legal advice - if you're truly concerned, seek the advice of a game-industry-savvy attorney.**

First, let me start with some context about my situation:

* I create asset-light games, so I'm a low-value target for infringement.
* I make my assets or buy them cheaply, so I'm not attached to the art, music, sound, etc.
* Nothing of mine has been copied yet, AFAIK, so my attitude towards it is purely hypothetical.

**Reasons/beliefs for the "Register copyright" stance:**

* **To defend yourself against other people registering infringing content against you.** How awful would this be? (I can't decide if this is a real risk, or just a highly charged emotional one.)
* It's cheap (approx $55 right now, via online form).
* It will give you a decent platform for making takedowns if you do decide they're worthwhile.
* It takes some of the stress/overhead out of maintaining records.
* You can pursue **statutory damages and attorney's fees**, if done within 3 months of publication. This may prove a significant *deterrence* to some infringers, since they may reasonably expect you to be more willing to take them to court.
* Many countries have agreements to respect each others' copyright laws, so e.g. registration in the US extends over much (but not all!) of the globe.

On that last point: **While you have copyright automatically** by creating a work (in the US, at least), **it's not always easy to prove you made it**. You have to have good evidence that your product existed prior to whatever the infringer claims their earliest possession of the work was. Personally, I use repos and online revision-controlled documents to keep track of this stuff, but I have no sense for whether that's adequate. It's just what I can afford to do.

You could also register a trademark if you think your brand will be valuable. This is a bit more expensive (Google says $275), but protects you from a specific type infringement. E.g. it would be hugely profitable if someone were to ship an Angry Birds Endless Runner, if Rovio couldn't take it down.

**Reasons/beliefs for the "Don't worry" stance:**

* Everyone overestimates the risk of being stolen from, though it definitely happens. Given the number of products released every day, it's unlikely you'll be targeted.
* Detecting infringement is difficult. Players might help if you own your assets openly (have consistent art across your site/game, for example).
* Proving infringement can be difficult. Assets may have traveled through multiple transactions, each believing it valid, since someone intentionally stole your content. Can make enforcement a time-consuming, expensive chore.
* Even with a clear case, enforcement is apparently difficult, judging by the amount of obviously stolen content on Apple's app store. I expect it's even worse for stores with a lighter review process.
* Protecting your assets is a never-ending battle.

Given these factors, I elect to simply not care. As game developers, we have enough on our plates already, and I think the returns on involved protection efforts do not justify the costs.

Finally, you don't have to make yourself an easy target. Asset thieves are doing it to make money (whether directly, or by shortening and cheapening development cycles), so if you're able to cheaply make your content harder to steal (e.g. obfuscation), that may be worthwhile.

So yeah, that's the set of beliefs I work under. They might work for you, they might not. I try to judge every effort based on return on investment. I think most "protect your assets" efforts are driven by emotion rather than actual calculation of the benefits.

Hope this helps.

---
Tags: legal, copyright
---


# Question
Title: What does maximum normalized frictional force mean in this tutorial?
I tried following this tutorial: https://nccastaff.bournemouth.ac.uk/jmacey/MastersProjects/MSc12/Srisuchat/Thesis.pdf, but in page 19 I ran onto a problem - I don't understand the step 4. It is also not explained before. Could somebody explain what is it and what values may be used?

# Answer
An important concept in physics is that "***friction never does mechanical work***"; it only retards motion by generating heat.

Since *mechanical work* is calculated as the dot product of the force acting on a body with the displacement of said body (or more specifically, the integral over time of said *dot product*), this principle means that the total frictional force must always be such as to *minimize* the amount of mechanical work done by all forces acting on the body. Thus it is always necessary to check and ensure that this is true, else one will have an unrealistic simulation.

The *maximum normalized frictional force* (at any point of friction) referred to is obtained by multiplying the *normal force* at that point by the corresponding "coefficient of friction\* (static or kinetic as appropriate) for that point of friction.

The *normal force* is that exerted by the ground/track at that point just sufficient to both prevent the vehicle from *dissolving* into the ground/track, and from spontaneously starting to rotate off of the track. The latter can only occur when other forces acting away from the ground/track have already reduced the corresponding *normal* force to zero, usually from aerodynamic lift of some sort.

**Update**:

The *Normal Force* and the *Frictional Force* are respectively the perpendicular and parallel components of the reaction force from a surface when another body comes in contact. Neither can do *mechanical work*. The usual model is that the *Frictional Force* varies linearly as the *Normal Force*, with the *coefficient of friction* being the ratio. The *coefficient of static friction* (applicable to initiating movement or during *rolling without slipping*) is usually significantly greater than the *coefficient of kinetic friction* (applicable otherwise). Both are a property of the combination of materials at the point of contact and of the roughness of both - there is no theoretical model I am aware of that will predict these values, so you must simply look up what typical values are for the circumstances of interest.
> 1 votes

---
Tags: physics, car
---