# Question
Title: Deferred rendering: camera inside point light's sphere of effect
I'm trying out deferred rendering and I'm using the tutorials at http://ogldev.atspace.co.uk. I've got the basics working and I'm currently trying to implement the final step from tutorial 37 (http://ogldev.atspace.co.uk/www/tutorial37/tutorial37.html). In the previous tutorial, the author explains how to render point lights as spheres in a second render pass, combing the effect of the lights with the data generated in the geometry buffers in the first pass, and I've got this working already.

In tutorial 37, he explains how to use the stencil buffer to limit the influence of the lighting to only light up objects actually inside the light sphere. He describes how the stencil buffer is set up to decrease the stencil value when the depth test fails for front facing polygons and increase it for back facing polygons, resulting in the stencil buffer containing zeroes for all pixels belonging to objects outside the light sphere (as these will either be in front of the light sphere, leading to the depth test failing both for the front facing and the back facing polygons of the lights sphere, causing the stencil value to first decrease by one and then increase by one, or behind it, leading to neither front facing nor back facing polygons of the light sphere failing the test so the stencil value remains unchanged). Objects inside the sphere though cause the depth test to fail only for back facing polygons, leading to the stencil value being not zero. This will later be used to only render the light sphere on pixels for which the stencil value is not zero.

So far, so good. But then there is a remark saying that the case when the camera is inside the light sphere is left as an exercise for the reader, and this comment puzzles me. Won't it still work the same way? If the camera is inside the light sphere, then objects in front of the light sphere will not be rendered at all (since they are behind the camera). Objects behind it will still not cause the depth test to fail for the back facing polygons of the light sphere (and the front facing polygons will of course not be rendered) so the stencil values for those pixels will still be zero. As for objects inside the light sphere, the depth test for the back facing polygons will fail, causing the stencil value to be different from zero. It seems to me that no special consideration will need to be taken for the case when the camera is inside the light sphere, but maybe I'm missing something. Can someone please help me figure this out?

# Answer
> 1 votes
This method uses geometric shapes to represent volumes of light. The outline of a sphere, viewed from any angle, is a circle. "Selecting" the pixels within that circle is the primary reason for using geometry in this way; this method only invokes the light shader on the pixels within the circle rather than testing every pixel on the screen, many of which may be unaffected by the light source being rendered.

His comment applies to the final pass (using typical back-face culling), and not to the initial pass (with culling disabled).

When you are "inside" the light volume, the front faces are behind you (culled) and the backfaces are reverse-wound (culled). Since no fragments are generated, the stencil value is never used.

Your exercise was to realize/determine that you need to reverse the culling direction in order to draw the backfaces, instead. If you are outside of the volume, both cull-modes produce the same circle, so it's just as easy to *always* render back-faces for the last pass.

This is the "changelog" for the affected shader (about 3/4 down the page):

> Same as the other passes the point light pass starts by setting up the G buffer for what it needs (by calling GBuffer::BindForLightPass()). It sets up the stencil test to pass when the stencil value is not equal to zero. After that it disables the depth test (because we don't need it and on some GPUs we may get some performance by disabling it) and enable blending as usual. The next step is very important - we enable culling of the front face polygons. The reason why we do that is because the camera may be inside the light volume and if we do back face culling as we normally do we will not see the light until we exit its volume. After that we render the bounding sphere as usual.

# Answer
> 0 votes
It might be worth taking a look at the difference between depth pass and depth algorithms for the shadow volumes rendering (https://en.wikipedia.org/wiki/Shadow\_volume) since the problem is similar IIRC. It might be easier to convince yourself with the shadows.

You have some pictures here http://www.gamedev.net/page/resources/\_/technical/graphics-programming-and-theory/the-theory-of-stencil-shadow-volumes-r1873, there is also a tutorial at ogldev (40th).

---
Tags: opengl, lighting, deferred-rendering, deferred-shading, stencil
---


# Question
Title: Why flip sprites instead of creating extra assets?
Why is the preferred method for changing the direction a character is looking in a 2D game a sprite flip? Why not just create the extra asset and show that one on screen?

# Answer
Flipping an asset at render time is relatively trivial to do, even on the CPU.

Creating an entirely new asset that is just a copy of an existing asset is essentially a way to double your asset footprint for no gain.

If you have the budget in memory, disk, et cetera for unique assets per direction, they can provide extra visual fidelity (for example, Super Metroid provided unique sets of sprites for both directions Samus could face, and because she is a very asymmetrical character it made the game look a little better). But often a flip is good enough, and cheaper.
> 4 votes

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


# Question
Title: How to manage VBO geometry for constantly changing data?
Before going into specifics, I'm mostly interested in making simple 2D games with some 3D elements, not fancy AAA.

Based on what I've gathered, everyone seems to suggest to use OpenGL 3+ with shaders, instead of the 2.x style of `glVertex/glBegin/glEnd`. Now I do understand the reasoning behind moving to VBO and shaders, as it gives greater control and performance.

But it seems that it also forces me to produce all of the geometry beforehand, buffer is it somehow, generate the VBO, and then send all that to a single vertex/fragment shader to render it, correct?

It also seems that I need to have a single shader process completely different types of vertices, which means there has to be a lot of redundant information in the VBO? Or is there a way to have multiple VBOs? I know it is possible to have multiple shaders and swap them, but I haven't figured out when one would need that, considering I only have a single active VBO?

## Now comes the real question.

Consider I'm making something like a procedurally generated growing plant, where each frame changes the whole geometry slightly (or just adds something). For simplicity, let's just say the plant is a bunch of colored ellipses. How do I structure the algorithm for "drawing" the plant? Would I just build the whole VBO from scratch, given that the vertex data changes all the time?

Also considering that the number of plants and their size can vary greatly, how do I avoid re-allocate memory for the VBO on each frame? Do I just use a *large enough* buffer, which would be able to store the maximum amount of geometry I can manage in my shaders (like a 512MB static array)?

# Answer
> 2 votes
Your assumption that there should be only a single VBO and shader is incorrect. You can, up to the limits of available memory, have as many VBOs as you want. For smaller games you can get away with having one VBO per drawable object, but ideally you should share VBOs between objects that require the same set of uniforms, shaders, and textures, so that each set of objects can be drawn in one shot using `glDrawArrays` or `glDrawElements`.

As far as structuring the VBOs in the case of your procedurally generated plant, it would probably be best to give each plant its own VBO, so as to not have to worry about moving vertices from other objects around to accommodate the increasing or decreasing number of plant vertices. You can allocate a "large" VBO up front to avoid reallocation as the plant grows, but 512mb would be way too much (and may even fail.) You can easily calculate the size of your vertex data, and estimate how large the plant could ever grow to be, and only make your VBO that big.

If your plant growth could be precalculated, you could load a VBO with all of the "frames" end-to-end before hand, and then just page through those frames at the appropriate rate with your calls to `glDraw*`, but if not, then yes, you should just refill the VBO every frame.

# Answer
> 1 votes
There are two more options solutions to overwriting single buffer in 3.x (few more in later versions):

1. use the buffer as ringbuffer, locking and updating only a part equal to current "pointer" + required size. Moving round the buffer using modulus.
2. use technique called buffer orphaning, where you just discard the buffers from your point of view and rely on the drivers do the optimization

both solutions are(or should be on typical hardware) faster, but basically as said in other answer - do not fix what is not broken, there is no reason to optimize unless your game is too slow. There is hardly any bigger productivity killer than premature optimization.

---
Tags: opengl, vbo
---


title: DeltaTime won't create smooth movement

text:
# Question
Title: DeltaTime won't create smooth movement
# The problem :

I tried adding deltaTime into my game, which seems to not be working when I try to smoothly move a object in my game.

---

# How I calculate delta time :

**Delta Time variables :**

```
float elapsedTime = 0;
float lastFrameTimeElapsed = 0;
float deltaTime = 0;

```

**At start of game loop I do this :**

```
elapsedTime = SDL_GetTicks();

```

**At end of game loop I do this :**

```
deltaTime = elapsedTime - lastFrameElapsedTime;
lastFrameTimeElapsed = elapsedTime;

```

And then the game loop ends.

---

# How I try to move my object using delta time :

**My `SDL_Rect` variable :**

Definition :

```
SDL_Rect* m_rect;

```

Initialization :

```
m_rect = new SDL_Rect();

```

**My move function :**

```
void Sprite::Move(float offsetX, float offsetY)
{
    m_rect->x += (int)offsetX;
    m_rect->y += (int)offsetY;
}

```

**How I call the move function :**

```
Move(5 * deltaTime, 0 * deltaTime);

```

# Answer
> 1 votes
Consider the equation y=x, for x in the real numbers this equation is continuous. Our problem is that video game time is a piecewise, that is to say our line is actualy a series of distinct points. The more points over a given interval the closer you are to y=x. Thus you could decrease your step size (distance between points) to increase the number of points on a given interval. It might even be a good idea to make your step size a function of the change in time (delta-t) to have it account for variations in game loop time.

The granularity of SDL\_GetTicks is milliseconds, instead of converting to seconds simply use it as is and change the scaling of your movement. This will remove floating point division and also probably the cause of your issue since your division is giving you whole seconds. If you want partial seconds change 1000 to 1000.0f assuming deltaTime is declared a float. If it is not, you might want to change that to increase the granularity of your calculations.

# Answer
> 1 votes
You definitely need to integrate deltaTime into a float structure, but you can copy the newly modified location into an SDL\_Rect for rendering. The player will still "teleport", but always and only by one, which may be acceptable in your game. My searches indicate that this is normal for SDL and the general solution seems to be to fallback on GL or DX and use orthographic projection to simulate the "2D" parts that benefit from floating point math.

`deltaTime` and all of your constants should also be floats; i.e. `1000.0f`.

**Scale:**

Imagine driving a car with a speedometer labeled in integer "miles per minute". 60 MPH would be the only label "1". So you can drive at 1, faster than 1, or slower than 1. How do you put 0.833333333MPM (50MPH) on a speed-limit sign? Miles-per-minute is, clearly, not the most convenient scale for vehicle speed limits, even though both scales are equally accurate.

"Units per millisecond" is an equally undesirable scale because humans do not experience life as such.

* "Carpe diem" - Seize the day, not the millisecond
* "Day-to-day needs" - Again, days
* "Tomorrow" - 86.4 million milliseconds from now
* "Days of our lives" - Again, days
* "Give me a minute" - 60,000 milliseconds
* "Do it now; right this second" - 1000 milliseconds

**Code:**

```
Uint32 elapsedTime = 0; //Why not since SDL_GetTicks() returns Uint32
Uint32 lastFrameTimeElapsed = 0;

//Convert Uint32 milliseconds to float seconds
float deltaTime = (elapsedTime - lastFrameTimeElapsed) / 1000.0f; //Per-second is easy

Move(10.0f * deltaTime, 0.0f * deltaTime); //10 units per second

void Sprite::Move(float offsetX, float offsetY)
{
    //Moving 10 units per second at 60 FPS, yields offsetX/Y of +-0.1666666f
    //Since 0.1666666f rounds to 0, this won't work:
    //m_rect.x += roundf(offsetX);
    m_floatRect->x += offsetX;
    m_floatRect->y += offsetY;
    m_rect.x = roundf(m_floatRect->x);
    m_rect.y = roundf(m_floatRect->y);
}

```

---
Tags: c++, sdl2, timestep
---


# Question
Title: Put a coroutine on potentially infinite loop
I have several coroutines always running.

I want to put these coroutines on hold as I set the game to pause mode.

Consider the content of these coroutines as follows

```
while (timeleft > 0)
        {
            if (pause)
            {
                continue;
            }
            ...
            timeleft -= Time.FixedDeltaTime;
            yield return null;
        }

```

I thought that would be okay to insert the `if(pause)` clause to have the coroutines to wait while pause is up.

What, insted happens is that (I guess) these infinite loops make unity not responding so that I have to kill the process.

Can I be right in thinking that the system does not like coroutines to be in a potential infinite loop? Or that is just okay and I have to heavily debug somewhere else?

# Answer
> 3 votes
It has nothing to do with it being a coroutine. It's an infinite loop, that can't exit. You need to return control to the code that's calling the coroutine. Your idea is good, it's just missing that component. If you're paused, just return without doing anything:

```
while (timeleft > 0)
{
    if (pause)
    {
        yield return null;
        continue;
    }
    ...
    timeleft -= Time.FixedDeltaTime;
    yield return null;
}

```

This will cause a return to the calling code, without decreasing the time remaining. Later, when the coroutine gets control back, it'll continue (like you wanted), starting back at the top of the loop. If you're no longer paused at that time, it'll proceed as normal.

---
Tags: unity, coroutines
---


title: How do I lerp text color over time?

text:
# Question
Title: How do I lerp text color over time?
On my quest to understand Unity in a zero to hero sort of manner, I've run into a new problem I can't seem to really solve.

From computer science I know that updating GUI on the same thread as everything else is the worst thing you can do, so naturally I'd like to start a separate thread to update GUI Elements. I am not sure if this is how you are supposed to do it in Unity, or if it takes care of that on it's own but my guess is it doesn't.

So I went to Google and after a bit I found Color.Lerp(Color,Color,float) which seemed to do the job nicely. But applying it as a function over time have been harder than I anticipated. Below you see my code:

```
using UnityEngine;
using System.Collections;

public class GUITextTriggerController : MonoBehaviour
{
    public GUIText guiText;
    public float fadeDuration;
    private bool IsTriggered;

    public void Start()
    {
        guiText.color = new Color(1.0f, 1.0f, 1.0f, 0.0f);
        IsTriggered = false;
    }

    void OnTriggerEnter(Collider other)
    {
        if (IsTriggered == false)
        {
            IsTriggered = true;
            StartCoroutine(UpdateTextColor());
        }
    }

    IEnumerator UpdateTextColor()
    {
        yield return new WaitForEndOfFrame(); // So that I return something at least.
        float t = 0;
        while (t < 1)
        {
            guiText.color = Color.Lerp(new Color(1.0f, 1.0f, 1.0f, 0.0f), new Color(1.0f, 1.0f, 1.0f, 1.0f), t);
            t += Time.deltaTime / fadeDuration;
        }
    }
}

```

My understanding of Unity is still very much beginner so bear with me. From my understanding, using Co-routines and yield is essentially Unity's answer to Threading (correct me if I am wrong) so I thought the above could do the trick but rather than changing over time, the texts color changes instantly as soon as I enter my trigger volume.

# Answer
Really really simple. Actually you are using `while` loop just like a regular loop despite of being in `Coroutine`.

You did a small mistake, although it is necessary to return `yield` in `Coroutine` and that is for a reason and the matter of fact is, it will bring that in another thread.

In other words, `yield return new WaitForEndOfFrame();` works like execute all the code above this line, let pointer leave `Coroutine` for the specific time (time of a frame) and then come back and execute the remaining code.

Now if you can see, what you did is just yield return once, by that, all the remaining code will execute in regular manner.

What you can do is just move `yield return new WaitForEndOfFrame();` inside `while` so that it can slow down the loop.

```
IEnumerator UpdateTextColor()
{
    float t = 0;
    while (t < 1)
    {
        // Now the loop will execute on every end of frame until the condition is true
        guiText.color = Color.Lerp(new Color(1.0f, 1.0f, 1.0f, 0.0f), new Color(1.0f, 1.0f, 1.0f, 1.0f), t);
        t += Time.deltaTime / fadeDuration;
        yield return new WaitForEndOfFrame(); // So that I return something at least.
    }
}

```
> 1 votes

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


title: Collision with 2 of the same objects

text:
# Question
Title: Collision with 2 of the same objects
I'm looking to make a button that is activated by two of the same objects, but the code I'm using doesn't recognize the second object as a different instance. Not the best explanation but here's the code:

```
if place_meeting(x,y,obj_cube) && place_meeting(x,y,obj_cube)

```

So the game sees this as just one obj\_cube and the button is pressed even if there is only one cube on the button. I've tried using variables but I might be doing it wrong.

# Answer
When using the place\_meeting(x, y, obj) method, you can provide either an **instance** or **object** to check for as the third argument.

Your code is checking for obj\_cube, and will look for all obj\_cube's. What you need are variables to keep track of each individual cube.

```
cube1 = instance_create(x, y, obj_cube);
cube2 = instance_create(x, y, obj_cube);

```

Now when you use place\_meeting(), you can use this:

```
place_meeting(x, y, cube1) && place_meeting(x, y, cube2);

```

This code will only check that one particular obj\_cube at a time.
> 1 votes

# Answer
Based on this: Counting instances at position I made this script:

```
//script CountColliding(x,y,obj,0);
var ret;
ret = argument3;
show_debug_message(instance_place(argument0 /*x*/, argument1/*y*/,argument2 /*obj*/))
with(instance_place(argument0 /*x*/, argument1/*y*/,argument2 /*obj*/))
{
   instance_deactivate_object(id)
   ret = CountColliding(argument0,argument1,argument2,ret+1) ;
   instance_activate_object(id)
}
return ret;

```

Where `x`,`y` are your objects in question x and y and `obj` is the object to check collision with.

But I didn't like it very much so I made this one which I suppose it may be less error prone:

```
///CountColliding(obj)
var i,numOfColliding=0;
for (i = 0; i < instance_number(argument[0]); i += 1)
   {
   if(place_meeting(x,y,instance_find(argument[0],i)))
   numOfColliding+=1;
   }
return numOfColliding;

```

Which you use in your objects scope just bu passing as an argument the object that you want to check collision with.

Both return the number of colliding objects and both seem to work just fine but I don't know which one is more efficient performance wise.

Also I suppose you shouldn't use them in every step.
> 0 votes

# Answer
I would recommend duplicating the obj\_cube or using parents. If you duplicate it the objects will do the same thing anyway.

You could then write something like this:

```
   if (place_meeting(x,y,obj_cube)) && if (place_meeting(x,y,obj_cube1))

```
> 0 votes

# Answer
suppose the object that runs this code is called "obj\_Button", implement the following for when you want to know is two "cubes" are at the button:

```
if instance_position(x,y,obj_cube)!=noone //if there is some cube touching me...
with(instance_position(x,y,obj_cube)) //tell this cube to do this:
{
   if collision_line(x,y,other.x,other.y,obj_cube,false,true)!=noone //if there is another cube between me and the button
   {
      with (obj_Button)
      {
         //do the thing you want to do here.
      }
   }
}

```
> 0 votes

# Answer
If obj\_cube has rectangle mask

use below code in obj\_cube step action

```
var inst = collision_rectangle(x,y,x+39,y+39,obj_cube,false,true);
if inst != noone{
   //your code
}

```
> -2 votes

---
Tags: game-maker
---


# Question
Title: Frustum culling only working at certain angles
So how I'm doing this is a little sketchy but I plan on changing it to either AABBs or spheres once I get it working. So the problem I'm having right now is that the frustum culling I've implemented is only working at certain angles and is not even close to accurate, personally I believe that the problem is at a calculation level. I am fairly new to 3D game development so I just whipped up this class fairly quickly based on some thread I read. My ViewFrustum class can be found here: https://www.dropbox.com/s/3b97bgcwoyh2oq8/ViewFrustum.java?dl=0

So all I'm doing outside this class is calling the update method from my renderer class and I have an ungodly amount of if statements checking if an entity's xyz is within the min and max xyz of the frustum (This is temporary).

So my main question is, am I calculating the frustum right or did I make any mistakes?

Values (when game starts, rotation matrix is a identity matrix) :

* centerNear: \[134.49167, 7.3502045, -271.4365\]
* centerFar : \[134.49167, 7.3502045, -1170.7365\]
* points\[0-7\] :
    + \[0\] 2607.2214 1714.3507 -621.8992 1.0
    + \[1\] -2338.238 1714.3507 -621.8992 1.0
    + \[2\] 2607.2214 -899.70605 -1573.3379 1.0
    + \[3\] -2338.238 -899.70605 -1573.3379 1.0
    + \[4\] 136.4149 100.760254 -252.18294 1.0
    + \[5\] 132.56844 100.760254 -252.18294 1.0
    + \[6\] 136.4149 98.727104 -252.92294 1.0
    + \[7\] 132.56844 98.727104 -252.92294 1.0

# Answer
The *effective* algorithm here was:

1. Compute the 8 frustum points (correctly)
2. Rotate them all by the viewmatrix
3. Create an AABB that contains the double-rotated frustum
4. Process entities whose location is contained by the AABB

With no rotation, the coordinates for the frustum corners are relatively straight-forward; most easily noticed is that the FARPLANE's Z-value should be FARPLANE. The included output points have incorrect Z-values. Testing with a rotation of 90 around any axis should produce all of the same magnitudes, just in different components. In both cases, the coordinates were correct up until the very end where they were being transformed by the viewmatrix a second time due to a copy-and-paste error.

That was being obscured by the fact that the frustum tests were being performed against an AABB that contains all of the frustum's corners, rather than the actual frustum. It was probably the correct volume at cardinal directions but in the wrong place. Everywhere else, it was just double wrong. That made testing points against the AABB a crapshoot, at best.

OP intends on replacing current AABB if-else test with typical plane-dot and sphere methods using the corrected frustum.
> 0 votes

---
Tags: opengl, java, mathematics, frustum, frustum-culling
---


# Question
Title: Programming strategy to handle big programming project in Unity3d
Almost **three months** ago! We started a **big Tough project** and still it is continue almost done, some bugs, some logic issues and some redundancies in code. Its a Unity3d Project. Every models/animation/environment are all completed nicely then, it came to the programmers(us).

Now, after writing too many codes, some ill logics, bugs I have learn so many things and I don't want to share. Its is scatters in my mind strongly disagree with lead/teammates but anyhow it is continue. But the next big thing I want to ask you that **how do we handle a big project(programming side)**? What are the best right **suitable pattern to program in Unity3d using C#**. How experience programmer do this work? how do they **start to code**? What I did wrong or notice wrong is the list given below:

```
 1. Did not do paper work enoguh i.e., algorithm writing

 2. change code abruptly

 3. write code abruptly

 4. without plannig code

 5. things make dependent

```

Guide me the right thing so that next time it should keep in mind and we don't made any mess.

**Answer require from experience Developers, consider myself as your junior and you are giving me instruction.**

# Answer
This applies to most of the programming, not just Unity.

**Code should be readable**. Follow Clean code guidelines, to make single file, class, method, variable, etc as readable as possible. Meaningfull variable names ( No "x" but "Position.X", no "accMngrExt" but "accountManagerExtension") and continue with method names that should describe what they do, just by reading the name. Clean code book is something that every programmer should read. Atleast the first few chapters.

**Code should be easily located**. With file structure, you can isolate contexts so, that when you are looking for character shooting function or world spawn generator interface, you can just navigate through self explaining file structure. Ie. World/generation/interfaces or character/actions/shooting ( just an example ).

I have programmed as a hobby, for almost 20 years and as a professional, few years. I write crappy code. We all do. Some might hide it behind nice looking patterns some leave it right there :)

To be able to see that I did something wrong is the first step to cleaner code.

What you should right now do, is to wrap up all the code you have done to build runnable game. Then sit down and without personal attacks, just read the code and find the really smelly parts. Start refactoring. Usually, the code that first comes out, is not the best code. Its code that "just works". Its code, that you wrote, without precisely knowing, what you are even doing. Refactor it. Now you know what it should do, how it can be done and you can write it better. Cleaner.

I mentioned file structure. I find this thing very important with every project, that has more than one file. We spend so much time finding correct functions to fix, right places to add certain behaviour that we should not make it harder, by using overscoped file structure. What I mean is, that you should not have a folder named "Character" and stuff everything there, but brake it down to "inventory", "actions", "AI" and don't be afraid to brake even those down, until you have separated everything that does not share immediate context with each others.

Just remember, **THIS is the point where quitters quit**. Things are not rainbow colored roses anymore, you notice that you are just a human and even you do errors. Now you can really start to learn. Refractoring code is something you should always do. Everyday. Code is never ready. Even something that looked good yesterday, is now ( after few bug fixes ) looking like old testament was shredded to pieces and clued together by group of monkeys.

**TL;DR;** Refactor your code to be more readable. Do it step by step, don't force it. Start with the most buggy parts. Read your code. If you can't understand what it says while reading like a book, it needs to be refactored. If you need to comment code, to understand what it does, you need to refactor it. If your friend does not understand, you need to refactor it. Any english speaking person, should understand what your code does, when its read.

**WAIT, Theres more!**

REAL teams use somekind of **task manager system**. Something, that keeps track of new features, milestones, bugs and everyting relating to the project. We use JIRA. You can get JIRA as a standalone ( free for 5 users and you host it yourself (quite easy)) or as could service. Its cheap, like 10$/ month.

Next step is to start learning **agile development**. Don't just say to other developer, do feature x, but break it to parts. To **user stories**. Those are great and easy to start with.

So, start tracking your project. That is the first thing you should do, if you don't already do it. Fill it with all the bugs you find, all the features that full version of game has. Brake all the future features to smaller pieces, so that there is tasks that can be done in few hours.

With tracking, you start to get picture of what is really going on. You can see bug amount and an estimate about what is ready next week.

With agile, comes the "stand up"-session. You really should **discuss daily**, for few minutes ( per person ) about Did yesterday go as planned, what are you doing today and do you have any problems. This is important. With this meeting, you can see, if there is problems coming up, if some feature is harder to implement than was thought or some bug has reappeared or anything. This should be help face-to-face or as video-chat.

Now you are in position, where you know, what works and whats to come.

Use **code versioning system**, such as GIT. You can open public code reposity to github or private repository to BitBucket ( JIRA integrates nicely to it ). This helps you with the new feature implementation, bug fixing and refactoring. If something goes wrong, you can always revert to point in code, where everything worked.

**If it works, let it be**. This might be the most important thing I can say. While refactoring and clean code is nice, working code is the top priority. Always do best you can, but learn to move forward. Tasks help with this. If task says "as a AI, I wanna chase the player using sprint", then its done, when your code does exactly that.

**TL;DR2** Get task management software, such as JIRA. Use versioning software like GIT. Create tasks, complete tasks.
> 2 votes

---
Tags: unity, game-design
---


# Question
Title: How can I simulate tapping on touch for Android?
I'm searching on `Input.Touch` properties to find how can I simulate tapping on touch for Android. Something like `Input.getmouseButtonDown()` on mobile.

# Answer
> 1 votes
## For Single Touch:

`Input.GetMouseButtonDown` also works for touch devices if you are going to implement single touch.

## For Multiple Touches:

For multiple touch, you can do something like,

```
void Update ()
{
    int activeTouches = Input.touchCount;

    if (activeTouches > 0) {
        print (activeTouches + " touch(es) detected");

        for (int i = 0; i < activeTouches; i++) {
            Touch touch = Input.GetTouch (i);

            print ("Touch index " + touch.fingerId + " detected at position " + touch.position);

            switch (touch.phase) {
            case TouchPhase.Began:
                print ("User did touch the screen");
                break;
            case TouchPhase.Moved:
                print ("User dragging or moving his finger");
                break;
            case TouchPhase.Ended:
                print ("User did lift up his finger");
                break;
            }
        }
    }
}

```

---
Tags: unity, unityscript
---


title: Libgdx + Box2d working with 2 cameras

text:
# Question
Title: Libgdx + Box2d working with 2 cameras
Recently I have read that you can work with 2 cameras whenever you involve Box2d, which only works in meters.

In my Renderer class, I receive all the entities in the game and then draw them. I work with ashley library so all my entities are a formed by components.

Now, in my renderer method I check if the current Entity has BodyComponent. If true, then it draws the Sprite in the physicsCam, who has a Viewport of meters. Otherwise, it will just draw the Sprite in sceneCam, which has a Viewport of pixels.

My problem is I try to draw the Sprite according to the Body's position in meters, but it is drawn not exactly where the body is.

NOTE: I also have PhysicsDebugSystem which basically just call the DebugRenderer.render() method.

Here is my RenderSystem class:

```
package engine.systems;

import com.badlogic.ashley.core.Component;
import com.badlogic.ashley.core.ComponentMapper;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.IteratingSystem;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.Array;

import engine.Values;
import engine.components.BodyComponent;
import engine.components.SpriteComponent;
import engine.components.TransformComponent;

public class RenderSystem extends IteratingSystem{

    private SpriteBatch batch;
    private Array<Entity> renderQueue;
    private OrthographicCamera sceneCam;
    private OrthographicCamera physicsCam;
    private ComponentMapper<SpriteComponent> txt;
    private ComponentMapper<TransformComponent> trs;

    @SuppressWarnings("unchecked")
    public RenderSystem(SpriteBatch batch) {
        super(Family.all(TransformComponent.class, SpriteComponent.class).get());
        txt = ComponentMapper.getFor(SpriteComponent.class);
        trs = ComponentMapper.getFor(TransformComponent.class);
        sceneCam = new OrthographicCamera(Values.WIDTH, Values.HEIGHT);
        sceneCam.setToOrtho(false);
        physicsCam = new OrthographicCamera(Values.WIDTH, Values.HEIGHT);
        physicsCam.setToOrtho(false);
        renderQueue = new Array<Entity>();
        this.batch = batch;
    }

    @Override
    public void update(float deltaTime) {
        super.update(deltaTime);
        Gdx.gl.glClearColor(230/255f, 242/255f, 242/255f, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        sceneCam.update();
        physicsCam.update();
        batch.enableBlending();
        batch.begin();
        for (Entity entity : renderQueue) {
            Component comp = entity.getComponent(BodyComponent.class);
            if(comp == null) {
                batch.setProjectionMatrix(sceneCam.combined);
            } else {
                batch.setProjectionMatrix(physicsCam.combined);
            }
            SpriteComponent texture = txt.get(entity);
            TransformComponent transform = trs.get(entity);
            if (texture.region == null || transform.isHidden) {
                continue;
            }
            texture.region.setPosition(transform.position.x, transform.position.y);
            texture.region.setRotation(transform.rotation);
            texture.region.setScale(transform.scale.x, transform.scale.y);
            texture.region.draw(batch);
        }
        batch.end();
        renderQueue.clear();
    }

    @Override
    protected void processEntity(Entity entity, float deltaTime) {
        renderQueue.add(entity);
    }

    public OrthographicCamera getCamera() {
        return sceneCam;
    }

}

```

In my GameWorld class I construct the ball in this method:

```
public void initBall() {
        Entity entity = new Entity();
        float x = Values.WIDTH/2*Values.PPM;
        float y = Values.HEIGHT*Values.PPM;
        SpriteComponent txt = new SpriteComponent();
        txt.region = skin.getSprite("soccerball");
        txt.region.setSize(Values.BALL_WIDTH, Values.BALL_HEIGHT);
        entity.add(txt);
        TransformComponent trs = new TransformComponent();
        trs.isHidden = false;
        trs.position.x = x;
        trs.position.y = y;
        entity.add(trs);
        BodyComponent bc = new BodyComponent();
        BodyDef bodyDef = new BodyDef();
        // Set our body to dynamic
        bodyDef.type = BodyDef.BodyType.DynamicBody;

        // Set our body's starting position in the world
        bodyDef.position.set(x, y+Values.BALL_HEIGHT/2);
        bc.body = world.createBody(bodyDef);
        bc.body.applyAngularImpulse(50f, true);

        CircleShape circle = new CircleShape();
        circle.setRadius(Values.BALL_WIDTH/2f);
        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = circle;
        fixtureDef.density = 20f;
        fixtureDef.friction = 0.4f;
        fixtureDef.restitution = 0.6f;
        bc.body.createFixture(fixtureDef);
        circle.dispose();
        entity.add(bc);
        engine.addEntity(entity);
    }

```

Here's the screenshot I took during the simulation:

# Answer
You can instantiate as many `OrthographicCamera`s as you want. However, each frame will be rendered using only one camera. You can make it so every other frame renders with another view point (e.q. camera) in the world.

For example, we have a blue team playing soccer against a red team. We can instantiate two camera's - one that looks at the field from the blue teams' perspective and one that looks at the field from the red teams' perspective.

In the example above we can switch between the two camera's on-the-fly:

```
@Override
public void update(float deltaTime) {
    super.update(deltaTime);
    Gdx.gl.glClearColor(230/255f, 242/255f, 242/255f, 0);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    if (blueTeamPerspective) {
        blueCamera.update();
        batch.begin();
        batch.setProjectionMatrix(blueCamera.combined);
    } else if (redTeamPerspective) {
        redCamera.update();
        batch.begin();
        batch.setProjectionMatrix(redCamera.combined);
    }

    batch.end();
}

```

I hope this helps!
> -1 votes

---
Tags: java, android, libgdx, sprites, box2d
---


# Question
Title: How to figure out which tiles are within view, and where to draw them in the grid?
I know there are a few questions on here similar to mine, but none of them seem to fit my needs.

I'm using PyGame to implement a tile based game similar to Final Fantasy or Zelda from the early Nintendo and Super Nintendo generation consoles.

The issue I'm running into is that I can't figure out how make a general way to render and position the tiles within view of the player camera. Once the camera starts moving, finding how much of an image is present in the camera view is very difficult, and then positioning it correctly is more complicated.

Any suggestions on how I can figure out a general way to create the grid correctly?

# Answer
> 2 votes
To make the camera move when the player gets near the edge of the screen, you're going to need to set up a collision for the player to hit.

In the image, as the player moves closer to the displays edge, the player hits an invisible box that triggers the movement. Now, you may notice that instead of the display moving, it has the Map, in red, moving against the display.

That is because the map tiles should be blitted on a different surface than the display with the map moving the opposite direction of the player. This is due to the process of cancellation of momentum which I go into more detail in another question I answered here.

To implement this effect, the player is going to need be able to move around on the display itself within that box and only trigger the map to start moving when the player hits the box. An example of this would look something like this:

```
class Player:
    def __init__(self):
        self.image = pygame.Surface((32,32)) # Player Image
        self.image.fill((255,0,0))
        self.rect = pygame.Rect((284,284),(32,32))
        #Player Rect centered on a 600x600 display

        self.map_pos = (0,0)
        # The maps surfaces starting coordinates on the display

        self.moveBox = (100,100,500,500) # The move box.
        # (Lower x boundary,Lower y boundary,Upper x boundary, Upper y boundary)

    def move(self):
        mx,my = self.map_pos # Translate map_pos data

        # Get key press and move player
        key = pygame.key.get_pressed()
        if key[pygame.K_w]:
            self.rect.y -= 8
        if key[pygame.K_a]:
            self.rect.x -= 8
        if key[pygame.K_s]:
            self.rect.y += 8
        if key[pygame.K_d]:
            self.rect.x += 8

        # Check if player is hitting the x boundaries
        if player.rect.x <= self.moveBox[0]: # if player is hitting boundary
            self.rect.x += 8 # Return player to original pos
            mx += 8 # Move map against the player
            # note the original movement for this block was -x
        elif player.rect.x >= self.moveBox[2]-32:
            self.rect.x -= 8
            mx -= 8

        # Check if player is hitting the y boundaries
        if player.rect.y <= self.moveBox[1]:
            self.rect.y += 8
            my += 8
        elif player.rect.y >= self.moveBox[3]-32:
            self.rect.y -= 8
             my -= 8
        self.map_pos = (mx,my)
    def render(self,display):
        display.blit(self.image,(self.rect.x,self.rect.y))

```

The above is a sample player class that takes a player move event, checks if the player hit the move box, and moves the map if the box is being hit. If the box is not being hit, the player will move on the display normally. The below is small working script that illustrates the process. Feel free to play around with it.

```
import pygame
pygame.init()
#
display = pygame.display.set_mode((600,600))
clock = pygame.time.Clock()
#
scene = [
    "XXXXXXXXXXXXXXXXXXXXXX",
    "X--------------------X",
    "X--------------------X",
    "X--------------------X",
    "XXXXXXXX-------------X",
    "X--------------------X",
    "X------X-------------X",
    "X--XX--XXXXXXXXXXXXXXX",
    "X--XX--X-------------X",
    "X--------------------X",
    "X------X-------------X",
    "XXXXXXXXXXXXXXXXXXXXXX"]
#
map = pygame.Surface((len(scene[0])*64,len(scene)*64))
x,y = 0,0
for row in scene:
    for tile in row:
        if tile in "-":
            pygame.draw.rect(map,(0,155,0),((x,y),(64,64)))
        elif tile in "X":
            pygame.draw.rect(map,(125,125,125),((x,y),(64,64)))
        else:
            pygame.draw.rect(map,(255,128,122),((x,y),(64,64)))
        x += 64
    y += 64
    x = 0
#
class Player:
    def __init__(self):
        self.image = pygame.Surface((32,32))
        self.image.fill((255,0,0))
        self.rect = pygame.Rect((284,284),(32,32))
        self.map_pos = (0,0)
        self.moveBox = (100,100,500,500)
    def move(self):
        mx,my = self.map_pos
        key = pygame.key.get_pressed()
        if key[pygame.K_w]:
            self.rect.y -= 8
        if key[pygame.K_a]:
            self.rect.x -= 8
        if key[pygame.K_s]:
            self.rect.y += 8
        if key[pygame.K_d]:
            self.rect.x += 8
        if player.rect.x <= self.moveBox[0]:
            self.rect.x += 8
            mx += 8
        elif player.rect.x >= self.moveBox[2]-32:
            self.rect.x -= 8
            mx -= 8
        if player.rect.y <= self.moveBox[1]:
            self.rect.y += 8
            my += 8
        elif player.rect.y >= self.moveBox[3]-32:
            self.rect.y -= 8
            my -= 8
        self.map_pos = (mx,my)
    def render(self,display):
        display.blit(self.image,(self.rect.x,self.rect.y))
#
player = Player()
#
RUNNING = True
while RUNNING:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            RUNNING = False
    #
    player.move()
    #
    display.fill((0,155,0))
    display.blit(map,player.map_pos)
    player.render(display)
    #
    pygame.display.flip()
#
pygame.quit()

```

---
Tags: camera, tilemap, python, pygame
---


# Question
Title: Why is my bullet disappearing after I release the shoot button?
I'm making a game using DirectXTK for my university project. When I press space bullet moves forward like I wanted, but when I let go it stops my bullet from moving. How do I keep the bullet moving when space was pressed?

```
void update
{
  //shooting
  if (kb.Space)
    Shoot(true);
  else
    Shoot(false);
}
void Render()
{
  if (draw)
  {
    for (int i = 0; i < 10; i++)
    {
      m_projectile[i]->Draw(m_bullet[i], m_view, m_proj, Colors::Red);
    }
  }
}
bool shoot(bool test)
{
  shoot = test;
  draw = true;

  //bool isShot = false;
  if (!shoot)
  {
    for (int i = 0; i < 10; i++)
    {
      m_bullet[i] = Matrix::CreateRotationY(m_ship._42) * m_ship;
    }
  }
  else
  {
    m_bullet[0] = Matrix::CreateTranslation(-Vector3::Forward *float(1))*Matrix::CreateRotationY(0.f) * m_bullet[0];
    //m_bullet *= Matrix::CreateTranslation(-Vector3::Forward);
  }

  return draw;
}

```

# Answer
You've joined together the creation of the bullet when pressing the space bar to the movement of the bullet. You should change your code so that when the space bar is pressed, a bullet is created. Separately, still in your update method, apply your translation based on velocity to any bullets that exist.

You'll also want to remove bullets at some point, likely either some time after they were created, or when they pass outside the bounds of your game - or better yet, on collision with something.
> 3 votes

---
Tags: algorithm
---


# Question
Title: How to lock the mouse cursor in the middle in a first person camera?
I want to get a first person camera (like Call of Duty or Minecraft etc.) but I don't know which is the best way to do it.

I have some camera increase rotation methods (camera.increase Rotation(x,y,z) the y is only the up and down looking).

The thing is I don't know how to make it work so that the mouse can stay in the middle but the rotation is increasing.

Any information is welcome regarding this subject.

# Answer
It depends on the framework you use. Locking the cursor is basically done by setting the cursor to the center each frame and use the delta movement in x and y direction for your camera rotation.
> 1 votes

# Answer
You could use your framework to hide either hide the mouse cursor or set it to use a default, invisible cursor. You can then just draw your crosshairs in the middle of the screen and rotate your camera according to the mouse's movements.

Unlike Benedikt's awnser this still allows the cursor to move, wether you want this to happen is up to you.
> 0 votes

---
Tags: opengl, java
---


# Question
Title: Objects on TiledMap show different proportions/spacing on Android device
I'm a noob when it comes to programming Java apps, so I'm trying to make a very simple platformer game.

All is running very well on the desktop project, but when I put the game on my Xperia, a strange thing happens:

I have an elevated floor and other tiles, and on phone screen, this all appears squashed: the tiles and the elevated floor display in a lower position than the desktop version, which is an ugly problem. Resizing the window on PC, it all runs and resizes correctly, maintaining the aspect ratio.

The second image is the regular window, and the last is at the minimum size window, but the aspect ratio is the same as on the larger window. If I stretched out the window, everything is stretched, but the upper floor and the sprite maintains the same distance. I don't understand what is happening on the mobile version.

I'm using Tiled to draw the map, and in my code I use `OrthogonalTiledMapRenderer` and `TiledMap`, with an `OrthographicCamera`. I "zoom" with `camera.setToOrtho` to crop to a part of the map.

The figure is a `Sprite` in then code. The floor and the "door" are layers in Tiled (floor and doors). I configured them as 16x16 tiles, but configuring them as 32x32 or more gives the same result.

I tried all viewports and still have not solved the problem. A potential solution I can think of is to cut off the top part when resizing, but I don't know how to do it!

# Answer
> 1 votes
The book uses a "different" technique to resize objects on game, not a Viewport. Well, the solution (working at the moment) has been:

1. A fixed size to the sprite (character.setsize(3,5)).
2. Apply a ScreenViewport().

And that's all.

I found this asking a question on libgdx IRC channel, and a user said to try with different screen configurations in code, changing `Gdx.graphics.setWidth()` and `setHeight()` to screen values of the phone, and I tried that on PC version, and, after a lot of tries, it worked!

---
Tags: libgdx, scale, tiled, aspect-ratio
---


# Question
Title: Moving script not working after SetActive/Pause change
I have a pause menu for my game which instantiates a texture and sets a text frame to active and slides both objects onto the screen using the code below:

Instantiating the menu texture and activating the text frame:

```
public void MenuPressed ()
{
    Vector3 newPosition = new Vector3 (-13, -0.06f, -2);
    Quaternion newRotation = Quaternion.Euler (0, 0, 0);
    Instantiate (menu, newPosition, newRotation);

    menuButton.SetActive (false);

    textFrame.SetActive (true);

    Time.timeScale = 0;
}

```

Moving the menu items:

```
float xLimit = -5;
float speed = 0.6f;

void Start ()
{
    StartCoroutine ("MoveMenu");
}

IEnumerator MoveMenu ()
{
    while (true)
    {
        transform.position += Vector3.right * speed;
        if (gameObject.name == "Main Text Frame")
            xLimit = -7;
        if (transform.position.x > xLimit)
            yield break;
        yield return new WaitForEndOfFrame ();
    }
}

```

Now this all works fine, but the issue that I have is on a multiple pause situation. When the pause button is pressed and spawns the menu and activates the text, the game pauses as expected. One of the options on the menu is to resume playing, when the pressed the game carries on as expected.

The problem I am having is that if the pause button is pressed again, the menu texture spawns in and slides on screen as intended, but the frame for the text does not. The frame gets set active but does not actually move.

Any ideas for how to fix this?

P.S

Here is the code I use to resume the game after it had been paused

```
public void Button1Pressed ()
{
    Time.timeScale = 1;
    GameObject menu = GameObject.FindWithTag ("Menu");
    Destroy (menu);
    gameController.paused = false;
    textFrame.SetActive (false);
    menuButton.SetActive (true);
    textFrame.transform.position = new Vector3 (-15.2f, -4.0f, -2.5f);
}

```

# Answer
> 0 votes
When you `yield break` from `MoveMenu`, it ends that coroutine forever. So when the text reaches its destination for the first time, that coroutine stops until you start it again. When you reactivate the text, you're neglecting to restart the coroutine (Start is not called on reactivation.) So you should just have something like this in the component containing `MoveMenu`:

```
public class MenuMover : MonoBehaviour
{
    void Start()
    {
        StartMove();
    }

    public void StartMove()
    {
        StartCoroutine("MoveMenu");
    }

    IEnumerator MoveMenu()
    {
        // do your thing
    }
}

```

Then you should manually call `StartMove` whenever you reactivate the text.

For convenience you might also like to reset the position of the object in `StartMove`:

```
public Vector3 offscreen_start_pos;

public void StartMove()
{
    transform.position = offscreen_start_pos;
    StartCoroutine("MoveMenu");
}

```

---
Tags: unity, movement, menu
---


# Question
Title: Issue translating objects by one unit in the y direction
I'm currently making space invaders (in OpenGL/SDL) and I'm running into an issue with the movement of the aliens. I have a 2-d vector of aliens (5 rows of 11) and I'm translating each in the x direction by a constant factor times elapsed time. If the right or leftmost alien in the vector hits either side of the screen, I decrement the y position of every alien. For some reason, when it collides the side of the screen, it infinitely translates downward in the y direction.

I thought that this would not happen since I wasn't multiplying the y position by elapsed time, but I think that its probably happening due to the fact that the `update()` method is being called once per frame. Here is the code for the update function (inside of the enemies class which holds the 2-d array):

```
void update(float elapsed) {
        //Update positions

        float minX = -5.2;
        float maxX = 5.2;

        bool hitRight = false;
        bool hitLeft = false;

        //if the enemies haven't hit the right side
        if (((enemyVect[0][rightmost]->x) + ((enemyVect[0][rightmost]->width) / 2.0) <= maxX)) {
            for (int i = 0; i < enemyVect.size(); i++) {
                for (int j = 0; j < enemyVect[i].size(); j++) {
                    enemyVect[i][j]->x += elapsed * 0.4 * xDirect;

                }
            }

        }
        //if they've hit the right side
        else if(((enemyVect[0][rightmost]->x) + ((enemyVect[0][rightmost]->width) / 2.0) >= maxX)){
            xDirect = -1;
            hitRight = true;
            for (int i = 0; i < enemyVect.size(); i++) {
                for (int j = 0; j < enemyVect[i].size(); j++) {
                    if(hitRight)enemyVect[i][j]->y -= 0.6; //move each row of enemyVect down to the next level
                }
            }
            hitRight = false;
        }
//if the enemies haven't hit the left side
        if (((enemyVect[0][leftmost]->x) -((enemyVect[0][leftmost]->width) / 2.0) >= minX)) {
            for (int i = 0; i < enemyVect.size(); i++) {
                for (int j = 0; j < enemyVect[i].size(); j++) {
                    enemyVect[i][j]->x += elapsed * 0.4 * xDirect;
                }
            }

        }
//if they've hit the left side
            else if (((enemyVect[0][leftmost]->x) - (enemyVect[0][leftmost]->width / 2.0) <= minX)) {
                xDirect = 1;
                for (int i = 0; i < enemyVect.size(); i++) {
                    for (int j = 0; j < enemyVect[i].size(); j++) {
                        enemyVect[i][j]->y -= 0.6; //move each row of enemyVect down to the next level
                    }
                }
            }
        }

    };

```

**How should I go about making it so that the y position of each alien only gets decremented once right after the collision with either side of the screen?**

# Answer
> 0 votes
For anyone that's interested, this is the code that I got to work for moving the enemies:

```
//move the enemies
    for (int i = 0; i < entities.size(); i++) {
        entities[i]->x += elapsed * 4.3 * entities[i]->xDirection;
        if (entities[i]->x >= maxX || entities[i]->x <= minX) {

            for (int k = 0; k < entities.size(); k++) {
                entities[k]->xDirection *= -1;
            }
            for (int j = 0; j < entities.size(); j++) {
                entities[j]->y -= 0.02;
            }
        }
    }

```

I ended up putting the enemies in a vector of entities instead of using a 2d vector which made the code a little less verbose.

# Answer
> 1 votes
After your rightmost enemy hits the right wall you've got to move the whole row back to the left before the end of your update function. As you have it now, the first if statement always fails after you hit a wall because the aliens are in the same place so the first else if runs moving your enemies down.

# Answer
> 1 votes
```
//if the enemies haven't hit the right side
//except you've said to do this, even if they *have* -------------------------v
if (((enemyVect[0][rightmost]->x) + ((enemyVect[0][rightmost]->width) / 2.0) <= maxX))
{
   ... //Move them all xDirect
}
//if they've hit the right side
//'=' case has already been handled this frame and has moved all
//of the enemies past the edge instead of doing this -----------------------------v
else if(((enemyVect[0][rightmost]->x) + ((enemyVect[0][rightmost]->width) / 2.0) >= maxX))
{
   ... //Move down; reverse
}

```

---

I suspect that adding only the outer-most `if` and `else` suggested below would "fix it", but I've also cleaned up and optimized a bit:

```
//Breakpoint 2
if (xDirect == 1) //optimize: only while moving right
{
  //if the enemies haven't hit the right side
  float rightX = (enemyVect[0][rightmost]->x) + ((enemyVect[0][rightmost]->width) / 2.0);
  if (rightX < maxX)
  {
    //optimize: calculate delta-x only once
    //don't move further than the distance to the edge
    float delta = fminf(maxX - rightX, (elapsed * 0.4 * xDirect));
    for (int i = 0; i < enemyVect.size(); i++)
      for (int j = 0; j < enemyVect[i].size(); j++)
         enemyVect[i][j]->x += delta;
  }
  //otherwise (if they've hit the right side)
  else // >=
  {
     ... //Move down; reverse
     //Breakpoint 1///////////////////
     xDirect = -1;
  }
}
else //only while moving left
{
  ...
}

```

# Answer
> 1 votes
The problem is you are not modifying the position of your aliens when they are hitting a side, consider the following pseudo code.

```
if (not hitting right)
  move right
else if (hitting right)
  move down
  change direction

```

Now the problem is that once the aliens hit the right side they are never not hitting it. That is to say the position of the right most alien (or left most) looks something like this.

(1, 0), (2, 0), (3, 0), (4, 0), (4, 1), (4, 2), ... (4, \infty)

There are a number of ways to resolve this issue, one is as follows.

```
if (not hitting right)
  move right
else if (hitting right)
 move down and left
 change direction

```

Now your aliens can break the condition that changes their y direction.

It might be easier to modify your code such that your if statements modify a vector that is applied to all aliens, this may look something as follows.

```
v = <-1, 0> // global, start right, move left

if (hit left)
  v = <1, 1>
else if (hit right)
  v = <-1, 1>

foreach(alien in aliens)
  alien.position += v

v.y = 0

```

Now you have reduced branching, code size, and complexity making your life easier.

---
Tags: opengl, c++, physics, sdl
---


# Question
Title: Unity - Open offline web pages in a browser window by clicking a button?
I currently have a Unity game where the user can click on buttons to open up web pages, I use the following script on the button for this...

```
public void OpenURL(string url)
         {
             Application.OpenURL(url);
         }
     }

```

The URL is then put into the box that this script produces in the inspector and works perfectly.

However what I would now like to do is open the pages OFFLINE instead, so people without an internet connection can see the information. The way I envisage doing this is to save the web pages so they can be opened up locally in a browser offline. However I am stumped as to how to tell the button to open the relevant file and open it - is there a way of doing this? Maybe save the web page file in a local folder and point the button to that file?

This would be way easier that the only alternative I can think of - to save each web page as an image and have them open up as an image popup within the game as opposed to in the browser (there are a lot, so I would rather not have to do this!)

This is for PC Standalone only.

Any help would be greatly appreciated.

Thanks in advance!

# Answer
Problem Solved -

* Add a folder into the build folder and put all the files you want to be opened in there
* Change the Open URL script to say *public void **relative**URL(string url)*
* Now put 'dirname/filename' in the URL field

Hey presto - it now works!
> 2 votes

---
Tags: unity, web
---


title: Java: problem with 2D corner collision

text:
# Question
Title: Java: problem with 2D corner collision
It took me many days to create a working collision detection for a 2D java platformer. I am finally calculating the corners of my player but the system is still buggy and I hope that we can figure out the problem.

This is a part of my Entity class. First, I calculate the movement in which direction the entity is moving or if it is falling or jumping and determine my **dx** and **dy** fields. After that I check the collision by calculating the corners and set dx or dy to zero if something is blocking the entity. Finally, I perform the moving by adding dx and dy to the x and y position:

```
    public abstract class Entity extends GameObject {

    //constants
    private final float GRAVITY = 0.2F;
    private final float MAX_FALLING_SPEED = 2.5F;
    private final float JUMP_START = -3.5F;

    //movement
    protected float dx;
    protected float dy;
    protected float speed;

    //movement action
    protected boolean right;
    protected boolean left;
    protected boolean falling;
    protected boolean jumping;

    //collision
    protected boolean topLeft;
    protected boolean topRight;
    protected boolean bottomLeft;
    protected boolean bottomRight;
    protected boolean midLeft;
    protected boolean midRight;
    protected boolean hasfallen;

    public Entity(float x, float y, int width, int height, float speed) {
        super(x, y, width, height);
        this.speed = speed;
    }

    public void update() {
        calculateMovement(); //1
        calculateCollisions(); //2
        move(); //3
    }

    private void calculateMovement() {
        if(left) dx = -speed;
        if(right) dx = speed;

        if(falling && !jumping) {
            dy += GRAVITY;
            if(dy > MAX_FALLING_SPEED) dy = MAX_FALLING_SPEED;
        }

        if(jumping && !falling) {
            dy = JUMP_START;
            jumping = false;
            falling = true;
        }
    }

    private void calculateCollisions() {

        float tox = x + dx;
        float toy = y + dy;

        //LEFT AND RIGHT COLLISION
        calculateCorners(tox, y);
        if(dx < 0) {
            if(topLeft || bottomLeft || midLeft) {
                dx = 0;
            }
        }

        if(dx > 0) {
            if(topRight || bottomRight || midRight) {
                dx = 0;
            }
        }

        //BOTTOM AND TOP (FALLING) COLLISION
        calculateCorners(x, toy);
        if(bottomLeft || bottomRight && falling) {
            falling = false;
            dy = 0;
        }

        if(!bottomLeft && !bottomRight) {
            falling = true;
        }

        //here's the error, he is constantly switching
        //between false and true for both booleans after
        //the entity hit the ground
        System.out.println(bottomLeft + "   " + bottomRight);
    }

    private void calculateCorners(float x, float y) {
        World world = Playstate.world;
        int leftTile = world.getColTile((int)x);
        int rightTile = world.getColTile((int)x + width - 1);
        int topTile = world.getRowTile((int)y);
        int bottomTile = world.getRowTile((int)y + height - 1);
        int midTile = world.getRowTile((int)y + height / 2);
        topLeft = !world.getBlocks()[topTile][leftTile].getMaterial().isWalkable();
        bottomLeft = !world.getBlocks()[bottomTile][leftTile].getMaterial().isWalkable();
        topRight = !world.getBlocks()[topTile][rightTile].getMaterial().isWalkable();
        bottomRight = !world.getBlocks()[bottomTile][rightTile].getMaterial().isWalkable();
        midLeft = !world.getBlocks()[midTile][leftTile].getMaterial().isWalkable();
        midRight = !world.getBlocks()[midTile][rightTile].getMaterial().isWalkable();
    }

    private void move() {
        x += dx;
        y += dy;
        dx = 0;
    }
}

```

The left and right collision work fine. **The problem occurs when the entity hit the ground and falling stops**. For example after falling my console says my entity is at position y: 44.9 but it should be 50 to fit to the tile. Apart from that, as you can see I checked the **bottomLeft** and **bottomRight** in my `calculateCollisions()` method. The console returns constantly true and false so in conclusion my entity is switching between falling and not falling fastly. Finally this causes a bug that you can't jump sometimes because if the entity is falling, jumping is set to false. So the entity will only jump if you hit the right moment when bottomLeft and bottomRight are true.

# Answer
> 2 votes
You can check the collision before actually moving the entity. Check for collisions of the entity plus DX and DY, if no collisions happen, then move the entity by adding DX and DY to x and y. If a collision happens, then resolve the collision, which might be something like

```
if (collidedObject.isType("block")) {
    entity.x = collidedObject.topX
}

```

This type of check will need to be combined with checks for DX positive or negative and DY positive and negative (so you know to use topX, or botX, or leftY, or rightY)

You also need to be wary of delta movements that might move an object completely past a smaller object.

```
Frame 1:
x     <-

Frame 2: (dx moves x past arrow, bounding boxes do NOT collide)
       <-     x

```

If the dx is large, you might need to subdivide the collision checks into multiple checks per frame.

EDIT: you can also resolve your entity movement to whole integers each frame. EDIT 2: here's a good summary of movement in platformers. http://higherorderfun.com/blog/2012/05/20/the-guide-to-implementing-2d-platformers/

# Answer
> 1 votes
Now it works, I made changes here:

> int bottomTile = world.getRowTile((int)y + height - 1);

I removed the -1 at the end.

> calculateCorners(tox, y **-1**);

And I added a -1 to calculate Corners for right and left collision

---
Tags: java, 2d, collision-detection, platformer
---


# Question
Title: Can I legally remove the default Unity splash screen by removing it from the APK?
While using Unity I export an Android game as an APK. When the APK is run, the first thing that is displayed is the Unity splash screen. I worked out that I could replaced that image by opening the APK like a zip file, looking for the splash screen image (`App.apk/assests/bin/Data/splash.png`) and replacing it with any image I wanted.

Is it legal to publish Unity-powered Android game apps with modified splash screens like this? I remember that some games on PS3, 360 and Wii have been created with Unity but don't display a Unity splash screen when run on their respective consoles.

# Answer
There are several sections of the Unity End-User License Agreement (which is for version 4.x as I write this, although earlier versions are similar) that pertaining to this issue.

The most directly relevant is section 3, which reads (in part):

> You will not delete or in any manner alter any Unity or third-party copyright, trademark or other proprietary rights notices or markings appearing on or in the Software (including the runtime portion thereof).

This is a pretty straightforward answer to your question: *no*, you are not permitted to remove the Unity splash screen from your Unity-based game.

There are other restrictions, such as section 2.f, which reads (in part):

> General Restrictions. Except as expressly specified in this Agreement, you may not: (i) copy (except in the course of loading or installing) or modify or create derivative works of the Software;

and continues

> Accordingly, you agree not to disassemble, decompile or reverse engineer the Software, in whole or in part, or permit or authorize a third party to do so, except to the extent such activities are expressly permitted by law notwithstanding this prohibition.

For the terms of the license, the term "Software" refers to "all 4.x versions and updates of all the Unity software products identified on Unity’s website." Further, the agreement is governed by the laws of Denmark, a fact which probably does not particularly apply to this question but is nonetheless worth noting.

Your technique for digging around in the final binaries of the game and gutting the default splash screen pretty clearly violates the above; your only recourse for splash screen modification is going to be whatever is built-in to the version of Unity you have. Your technique violates the license agreement.
> 59 votes

# Answer
Even though hacking the APK seems easy but it will definitely not run, the other option I believe is to **upgrade to the *Unity Pro* version** and I found on some research onto it.

See links:
> 13 votes

# Answer
Due to the End-User License Agreement, the written authorization is required from Unity Technologies, but it is "possible" to change the Unity's native splash screen.

The way of doing it is to produce your "own version" of the Unity trademark and propose it directly to Unity for the specific IP you're developing. They will require that you own a legal Pro license first and might ask for some adjustments or changes.

An example of a trademark that could be accepted is if you implement the Unity trademark into the main menu (with enough visibility) instead of the native splash screen.

It's not possible to not show the Unity trademark anywhere as you don't own the software, but a license (or more) which include the agreement to let you USE the software for commercial uses.

If they accept, they will send you an official written permission.
> 1 votes

# Answer
If you use the Pro version, you have no obligations to show the Unity splash screen. If you use the free version, it is not modifiable, so it means that you must show it. Removing it "after the build" is plain wrong and considered as a hack.

If it bother you so much; you can get the 30 days trial of the pro version, build your game with that, and remove the splash screen. Then you have to buy the Pro version though, since you can't publish a game with the trial version.

I would not worry to show the splash screen...making a game is not that simple as you may think, Unity won't do all by itself, without a skilled designer, and nobody will think that you are not a good designer/programmer, just because you didn't write your own 3d Engine.
> 0 votes

# Answer
You cannot legally modify the final apk created by unity and display your custom splash screen.

But what probably you can do is create a launcher activity which launches the unity activity(com.unity3d.player.UnityPlayerActivity).

In your launcher activity you can show your image as splash image.

The issue with this approach is that when you launch the unity activity it will still show the Unity logo.

I found the information here http://chikkooos.blogspot.jp/2016/03/a-splash-screen-for-unity.html
> 0 votes

# Answer
As to what you can legally do, the law looks at the terms of the license or the contract to which you have signed. The signing of publishing rights belong to the copyright holder(s). In the case of Unity 3D the run-time license remains the property of Unity 3D and does not transfer to the publisher or end-user.

Instead the publisher is using a piece of code that is still expressly licensed by Unity 3D for the purpose of running your published works. However, there is a problem with this model. If you bought a car and it had a term of condition that you could not modify the way it looks, or some advertising, then you would expect that you do not actually own the right of the transfer of that property aesthetically.

However, this is kind of the same thing when you buy a motor vehicle. The problem is that although the physicality of the situation stipulated you own the vehicle, you in fact do not have the right to claim you own the intellectual property of the design of the motor vehicle. You do however have the right to modify how your vehicle looks. We all be up in arms if there was a law that said, part of your motor vehicle's pricing model is based around the badges the manufacturer puts on the car. You cannot deface the badges on your car? Anyway, I for one fully acknowledge that there should be a credit in there, but not in the first scene of the application. Here is my argument why.

The market gets pretty saturated with crap apps. Or, crApps for short. The problem is with so many crApps that display the Unity Logo in the first couple of seconds of opening, give your application an automatic disadvantage due to prenotions of absolute low budget fruitfulness. A shitfest of waded bloated unoptimized crappy bogware that all bare the same opening logo.

Here is a better idea, choose a point where the credit / badge is shown. Maybe select on Application exit, or a point within the application life-cycle using a smaller placement or simply elect to remove the logo in return for real metrics. If the application calls to the mothership to let it know that the it is has been run, then they can start just focusing on collecting revenues based on the term of the license, rather than any potential advertising returns.... I don't know, maybe they do that already?
> -1 votes

---
Tags: unity, legal, copyright, publishing, google-play
---


# Question
Title: Why is the distance from object to eye irrelevant in illumination models?
For example in Phong model and Blinn model, the light intensity does not change depending on how far away the camera is. Why is that?

# Answer
After initially being puzzled about this question, because it felt natural that objects don't change their brightness depending on the distance to the eye (or camera), but only depending on the distance to the light source, I did a quick google search and found this great article. It is about this exact topic in photography and explains why the distance between the object and the camera is not relevant.

To summarize it: Yes, the arriving energy decreases proportional to `1/r²`. But consider this: As the distance increases the object also appears smaller, as well proportional to `1/r²`. While having less arriving energy, it also covers a smaller area of your field of view. Those two effects cancel each other out. Thus the object-camera distance does not influence the perceived brightness.
> 18 votes

# Answer
That's a question solved by looking at physical units.

The **irradiance** (watt per square metre) on the whole object determines it's illumination, this unit varies with distance between object and light because the "subtended surface" diminishes by `1/r²` with the distance.
(The radiant flux (W) of the light being constant)

For simplicity let's imagine a case where the light is at the camera position and we are looking at a white disc. The **radiance** of the disk is the emitted light by its surface considering our vision angle : in watt per steradian per square metre.

The radiance is necessarily less than its irradiance if the material is diffuse. Why is that ? because the camera only subtends a tiny angle of the total re-emission directions; while the disc re-emits its energy at  steradian (hemisphere).

So the radiance seen by the camera is `irradiance / 2π`. As you can see it does not depend on the distance between the object and the camera. Now, radiance is a unit per square meter, which means it defines "light intensity" per area, so when discretized, it means that it is the pixel value :)

I hope I'm right, this is always confusing.
> 2 votes

---
Tags: shaders, lighting, shading
---


# Question
Title: 2D Game Development Software that can release your game on Steam
Im looking for a game development software that can also publish to steam, I know most can but some come with an additional fee and some without, I think the Cryengine allows you to publish to greenlight without having to pay the fee but for a simple 2D game I do not think cryengine is the way to go. Any advice? :)

# Answer
> 0 votes
I haven't done any research so forgive me, but I'm pretty sure that, as long as you have the rights to commercially use the game engine or whatever you are using, than you will only need to pay the $100 for Greenlight access.

My advice is do a quick google search on the engine you are looking at using, add "commercial use" (gamemaker commercial use). You should find out pretty quickly if it is free for commercial use.

Some examples of game engines which are free for commercial use are: (I know that you said that you feel that cryengine is too complicated so I will stay away from some of the larger engines like UE4 and Unity. Also I will focus on engines which focus on 2D games) PlayN, Adventure Game Studio, Flexible Isometric Free Engine, and Cocos2d.

Another way to quickly find Game Engine licenses is to go to this wikipedia page: https://en.wikipedia.org/wiki/List\_of\_game\_engines

Best of luck, and welcome to the Stack Exchange.

# Answer
> -1 votes
You don't need any specific development software to release games on Steam Greenlight. Any game can be submitted to Steam Greenlight by creating a steam account, "buying" the Greenlight Submission Fee and then uploading the game through the steam greenlight website. It's a one-time fee, so after paying it you can submit as many games as you want.

When you use a software where the fee is already included, you will be paying the fee indirectly by paying for the software. But seriously, 90€? That cost is barely the equivalent of two people-hours development time.

You won't find a way to get on Greenlight completely free of charge. The minuscule fee is an intentional barrier to only get people who are at least a bit serious about professional game development and prevent the complete amateurs from flooding the portal with junk. Valve isn't even doing it to make money: They donate any revenue from Greenlight sumission fees to Child's Play.

---
Tags: 2d, game-design, steam
---


# Question
Title: How do I toggle color writes in SlimDX 11/Direct3D 11 with FeatureLevel 10?
I'm having trouble setting the `RenderTargetWriteMask` field of a `RenderTargetDescription` struct. I simply want to toggle color writes but every time I try to enable the color writes are changed back to zero. Here is the code:

```
BlendState bs = null, bs1 = null;

try
{
    RenderTargetBlendDescription rtBlendDesc = new RenderTargetBlendDescription()
    {
        RenderTargetWriteMask = ColorWriteMaskFlags.All,
        BlendEnable = false,
        BlendOperation = BlendOperation.Add,
        BlendOperationAlpha = BlendOperation.Add,
        DestinationBlend = BlendOption.Zero,
        DestinationBlendAlpha = BlendOption.Zero,
        SourceBlend = BlendOption.One,
        SourceBlendAlpha = BlendOption.One,
    };

    // default blend state
    bs = BlendState.FromDescription(_device, new BlendStateDescription()
        {
            AlphaToCoverageEnable = false,
            IndependentBlendEnable = false,

        });
    for (int i = 0; i < Constants.MaxSimultaneousRenderTargets; ++i)
        bs.Description.RenderTargets[i] = rtBlendDesc;

    // set default blend state
    _device.ImmediateContext.OutputMerger.BlendState = bs;

    // in debug you will see that the RenderTargetWriteMask field of each render target is set to 'None'...
}
catch (Exception e) { e.Handle(); F.DisposeResource(ref bs); F.DisposeResource(ref bs1); }

```

Update: I'm not able to set any of the values stored in `RenderTargetBlendDescription`.

# Answer
I found the answer in this thread which says:

> States are immutable in D3D10. Once created you cannot modify the properties for the state; the Description is essentially read-only, and we allow the language semantics to enforce that for us (the description is a value type, which is why you cannot modify the properties of the description returned by the Description getter).

I had to enable color writes in the BlendStateDescription before instantiating the BlendState. Code:

```
                    RenderTargetBlendDescription rtBlendDesc = new RenderTargetBlendDescription()
                    {
                        RenderTargetWriteMask = ColorWriteMaskFlags.All,
                        BlendEnable = false,
                        BlendOperation = BlendOperation.Add,
                        BlendOperationAlpha = BlendOperation.Add,
                        DestinationBlend = BlendOption.Zero,
                        DestinationBlendAlpha = BlendOption.Zero,
                        SourceBlend = BlendOption.One,
                        SourceBlendAlpha = BlendOption.One,
                    };
                    BlendStateDescription bsDesc = new BlendStateDescription()
                    {
                        AlphaToCoverageEnable = false,
                        IndependentBlendEnable = false
                    };

                    bsDesc.RenderTargets[0] = rtBlendDesc;

                    // default blend state
                    bs = BlendState.FromDescription(_device, bsDesc);

```
> 1 votes

---
Tags: c#, c++, directx11, slimdx, rendertargets
---


# Question
Title: What do "position.transform" and "Input.GetAxis" mean in Unity?
I am making the transition from Game Maker to Unity, but I feel lost when I look at Unity's programming.

When I followed a tutorial to make basic movements, I had this code:

```
public Vector3 playerPos;
void Update ()
{
    float V_X = transform.position.x;
    V_X += Input.GetAxis("Horizontal") / 2;
    playerPos = new Vector3(V_X, 0, 0);
    transform.position = playerPos;
}

```

A few things are confusing me here:

* What is `transform`? And why is `position` something that is a part of it? Why not have the position of the objects represented by just `x` rather than `transform.position.x`?
* Is `GetAxis(...)` a command that has a return value? Why is in "sub-categorized" under `Input`? And why not detect the key presses directly?

# Answer
Well, your first question should be categorised as General question rather than Unity's specific question.

> What is transform? And why is position something that is a part of it? Why not have the position of the objects represented by just x rather than transform.position.x?

There is a term in Computer Graphics called **Transformation** which includes 3 basic attributes of object.

* Translation
* Rotation
* Scaling

**Translation** is you can say the movement of an object. For example an object at position (10,10) and when you move it by some amount and that object's new position becomes (20,10) then you can say that your object is *translated* by (10,0) and the mathematical operation used is *Addition*

Bit similar case is with **Scaling** (with *Multiplication*) and **Rotation** (with both *Multiplication* with sin and cos, and *Addition* ).

Have a look in detail here

Now in Unity the component which represents the *transformation* of an object called Transform, by which you can change all three basic attributes i.e. **Translation**, **Rotation** and **Scaling**.

Now your second question, that is,

> Is GetAxis(...) a command that has a return value? Why is in "sub-categorized" under Input? And why not detect the key presses directly?

What I can say is just the will of Unity Engine Developers. They retain it and so many more different methods in class called Input, which is the part of UnityEngine. To be very honest I can't give you the exact reason for that. May be someone with have more knowledge about it may answer your this question in more detail.
> 2 votes

# Answer
> why do I need to use things like "public" and "float" to declare variables? Where are the variables stored? In Game Maker the variables are specific to the instances or the objects, but in Unity I am not sure if the variables in the scripts are stored in the gameObjects that has the script as a component or what.

Those are access modifiers and data types and don't relate specifically to game development. Unity is strongly-typed and uses inheritance. This is fundamental and I suggest holding off on exploring Unity until you have a working knowledge of it. A basic C# primer should get you on your way.

> Is GetAxis(...) a command that has a return value? Why is in "sub-categorized" under "Input"? and why not detect the key presses directly?

It is a public member of the Input class which does all of the grunt-work processing low-level inputs into higher-level "events" and functions. GetAxis() returns the value of a virtual axis. This is how you can use "D", mouse X+, and joystick X+ to produce the same result (move the player right). Each device has different ways of representing "left" and "right" but they can all be mapped to a 1D coordinate system (vaguely %-like). If the keyboard is the source of input, the value is -1, 0, or 1, because you can't "half push" a keyboard button; they are on or off. If the joystick was the source, the values could be anywhere in-between, because the device, itself, is analog. The script does not require deltaTime as an arugment because GetAxis() is already frame-rate independent (done by the Input class). The -1:1 scale makes it convenient for multiplication with a fixed direction; in other words, "move right -1" is equivalent to "move left" while "move right +1" actually moves right.

> what is "transform"? and why is "position" something that is a part of it? Why not have the position of the objects represented by just x rather than transform.position.x

The "position" of an object describes the relationship between the object and an arbitrary origin (relative translation/movement only). However, objects in 3D-space are frequently scaled, rotated, and translated in varying combinations and degrees. The "transform" represents a specific combination of all 3 (a world matrix) and fully orients an object's "local space" in "world space". An object may be transformed through many spaces (by many Transforms) before even getting to the view and projection stages. The Earth orbits the sun, and the moon orbits Earth; the moon requires two transforms to correctly position it relative to the sun and earth.

If you go to the unity documentation for MonoBehavior (the class your script inherits from), you'll find that transform is "inherited" (from Behavior). If you click on Behavior, you'll see that transform is, again, inherited. If you click on Component, you'll find transform under "Variables" and is not inherited. The type of transform is the Transform class and it is public member of Component, and so, inherited by your script. The transform that "belongs" to this script, can be referenced by other components; for example, the player object. The script updates the transform which the object, then, uses. If you assign this script to multiple objects, they will all respond to the user's input. The Transform class also has many helper functions for converting many types of inputs between local- and world-space.

> what is the difference between new Vector3(...) and just reassigning the variables?

There are *technical* differences, but I don't think that's what you mean and you are correct that:

```
playerPos.x = V_x;
playerPos.y = 0;
playerPos.z = 0;

```

is equivalent.
> 1 votes

# Answer
The `transform` variable is *probably* an instance of the `Transform` type. You don't show the declaration of the variable in your code, but it's pretty safe bet.

`Transform` is a type that's used to represent a position, rotation and scale in Unity. It's a representation of a transformation matrix, which we use in 3D graphics environments like Unity to capture those three basic ways of manipulating some object (moving it around, orienting it, and making it bigger or smaller, respectively).

Unity (and many other APIs) wrap position, rotation and scale up into a single type like `Transform` for a few reasons, but one of them is that it makes it easier to pass that information around. Rather than storing 9 to 11 individual floats (and also having to pass all 9 to 11 of them around to various functions), we pack them into one to save time, typing and sanity.

`Input.GetAxis` is indeed a function that returns a value. It's what is known as a "static" function, one that can be called without an instance of the containing type (which is the `Input` type in this case). Static functions are often used in C# where you would use free or "regular" functions elsewhere, because C# doesn't have the concept of functions that exist at the global scope. They all must be inside a class.

`GetAxis` is being used here to get a mouse input here, not a key, so that's why you don't "get the keys directly." However, the reason it's written like this is primarily to provide an *abstraction*, a way to hide underlying potentially-irrelevant details from you so that you can only be concerned with what you actually care about. In this case such an abstraction might have been written so that you could easily be reading the "horizontal" input axis from a joystick or gamepad's analog stick instead, or so the actual input axis requested could be specified via a variable instead of hard-coded like it is in the example, et cetera. It's simply a (reasonably common) design decision Unity decided to make and part of how their API is built.
> 0 votes

---
Tags: unity
---


# Question
Title: Doubts with results of per-vertex lighting shader
I'm researching simple shaders to add to my DirectX 11 project such as a per-vertex diffuse shader plus specular reflection component.

I'll begin with the results:

Seems specular reflection is working, but do you see the border and upper objects? They don't seem to be lit well, as a shader based on this lighting equation is not supposed to gray-scale the diffuse component (excepting when dot product \< 0 in backfaces,etc).

My HLSL vertex shader rationale is as follows, I dont know at this point of the day, if i'm missing something.

Vertex shader input / Output structs are defined as:

```
// Output and Input Structs
// ------------------------

struct VS_OUTPUT {
    float4 pos       : SV_POSITION;
    float4 color     : COLOR;
};

struct VS_INPUT {
    float4 pos : POSITION;
    float4 norm: NORMAL;
};

```

1) Transform the input position to world coordinates:

```
vo.pos = mul(vi.pos, worldMatrix);

```

2) Transform normal to world and normalize:

```
float4 N = normalize(mul(vi.norm, worldMatrix));

```

3) Calculate the vector from the light position to the current vertex position. Lighting is already in world coordinates. w=1.0, so:

```
 float4 L = float4(normalize(float4(light[0].pos.xyz,1.0f) - vo.pos));

```

I have camera position in world coordinates passed through Cbuffer, so camera minus vertex position yields V vector.

```
float4 V = normalize(cameraPos - vo.pos);

```

4) Use reflect intrinsic to calculate R, negating L since it's pointing towards light.

```
float4 R = reflect(-L, N);

```

5) Finally I calculate the color to pass to the pixel shader, and transform the vertex position with the view/projection matrices.

```
 vo.color = ka + ke + kd * saturate(dot(N, L)) + (ks * pow(saturate(dot(V, R)), specp));
    vo.pos = mul(mul(vo.pos, viewMatrix), projMatrix);
    return vo;

```

Just for completion, here are the constant buffers:

```
#define MAX_LIGHTS 16

cbuffer bufWorldMatrix : register (b0) {
    float4x4 worldMatrix;
}

cbuffer bufViewProjMatrix : register (b1) {
    float4x4 viewMatrix;
    float4x4 projMatrix;
    float4   cameraPos;
}

cbuffer materialProperties : register (b2) {
    float4 kd;
    float4 ka;
    float4 ks;
    float4 ke;
    float  specp; // Specular-power (shininess)
}

struct LightBase {
    float3 pos;
    float3 color;
    float  intensity;
    float  isOn;
};

```

THanks, any help is appreciated. I'm sure normals are OK, but I can recheck in case. I can post additional debugging/ code if it's required.

# Answer
> 0 votes
**I fixed it.** First I fixed the mess I was having with the W-coordinate, for example, I multiply now the normal with worldmatrix but casted to 3x3 to discard the w coordinate.

Also, I was modulating the specular term instead of adding it to the diffuse color output. Seemed to give a metallic appearance instead of a "shiny" one.

For vertex lighting , mesh subdivision is very important to obtain adequate results, I refined the meshes a bit to get more accurate results.

---
Tags: shaders, directx11, hlsl, lighting
---


# Question
Title: How do I render a rounded rectangle in libgdx?
I've been thinking of ways to render a rounded rectangle in libgdx. I haven't found a pre-built way in the documentation. I've looked at:

* `ShapeRenderer`, but that's apparently quite expensive performance-wise and I'll have to compose it of a polygon perhaps or use circles and rectangles.
* The `Mesh` class, which would probably perform well but is complex to use for such a simple shape. Again, I'd have to create the polygon myself with an algorithm for different sizes of rounded rectangles.

Can someone point me in the right direction?

# Answer
You can procedurally generate a rounded rectangle. You should probably use `ShapeRenderer` for this, as its `rect` and `arc` methods provide exactly what you need (five filled rectangles -- or two that overdraw -- and four filled arcs produce a rounded rectangle). I would strongly encourage you to build your rectangle this way and only worry about more complicated solutions if you actually see performance issues.

If you really want to avoid `ShapeRenderer`, you can build the geometry yourself and store it into a `Mesh` for rendering. You'll have to produce actual triangles to do so, so you'll want to approximate the arcs using triangles organized like a triangle fan (you may not want to use *actual* triangle fans, since they are poorly-supported and also because you can't represent the rest of the rounded rectangle with them, so you'd end up with many draw calls per rectangle rather than a single draw call if you were generate the geometry as a single indexed triangle list).

You should then cache this `Mesh` object (or several of them, one for each "resolution" of arc representation) and re-use it for every rectangle you want to draw. This may be more efficient than `ShapeRenderer` if you put the time and effort into it, but it's also going to be more work on your part.

A related option would be to continue to use a ninepatch, but to generate the textures you use for the rounded corners with `ShapeRenderer` once, using very high-resolution calls to `arc` to ensure you have sufficient visual fidelity for your needs (you'll need to tweak the input, but that would be easy). This is likely the most efficient, since a ninepatch uses much less geometry then a mesh would to represent the same thing, unless you have some other needs that make ninepatches unusable.
> 1 votes

# Answer
In case it's useful for anyone, here's my extension of LibGDX's ShapeRenderer to draw rectangles with rounded corners, using Josh Petrie's approach of drawing five rectangles and four arches.

I chose it over the two overlapping rectangles approach because it works well with transparency.

```
public class MyShapeRenderer extends ShapeRenderer{
    /**
    * Draws a rectangle with rounded corners of the given radius.
    */
    public void roundedRect(float x, float y, float width, float height, float radius){
        // Central rectangle
        super.rect(x + radius, y + radius, width - 2*radius, height - 2*radius);

        // Four side rectangles, in clockwise order
        super.rect(x + radius, y, width - 2*radius, radius);
        super.rect(x + width - radius, y + radius, radius, height - 2*radius);
        super.rect(x + radius, y + height - radius, width - 2*radius, radius);
        super.rect(x, y + radius, radius, height - 2*radius);

        // Four arches, clockwise too
        super.arc(x + radius, y + radius, radius, 180f, 90f);
        super.arc(x + width - radius, y + radius, radius, 270f, 90f);
        super.arc(x + width - radius, y + height - radius, radius, 0f, 90f);
        super.arc(x + radius, y + height - radius, radius, 90f, 90f);
    }
}

```
> 8 votes

# Answer
When rendering 3D graphics you are always using a 3D mesh in some form or other. (Ignore the deprecated immediate mode.) So if you have a library that offers you to render a cube or a teapot, the underlying implementation basically has (or generates) a 3D mesh to render the shape.

The straightforward way of rendering any non trivial shape is build the shape in a 3D modeling package, load the shape and render that. (Yes, rounded corners make the shape non trivial.)

My advice is to build the box in a tool like Blender and save the model in either the OBJ or PLY format. These formats are well known and text based and as a result have either prebuilt parses or are trivial to read. The given vertex data can then be fed into the Mesh class you mentioned.

The upside is that, from that point on you can build and render other non-trivial objects.
> 1 votes

---
Tags: libgdx, rendering
---


# Question
Title: Why does Mathf.Log(x) return infinity in this case?
I'm facing an unexpected behavior due to computational limits, I guess.

I have a function `Log(x)` which, for some high value in the Fibonacci series `n 187 = 5.38·10^38` returns `Infinity`.

Is there a way I could follow to avoid this and always have computed numbers?

# Answer
Here is a more numerically stable (for large values) way of getting `Log(Fn)` where `Fn` is the nth Fibonacci number. Let `φ = (1 + sqrt(5)) / 2` and `ψ = (1 - sqrt(5)) / 2`. Then the nth Fibonacci number is:

```
      φⁿ - ψⁿ         1 - (ψ/φ)ⁿ
Fn = —————————  =  φⁿ ——————————
       φ - ψ            φ - ψ

```

The logarithm of `Fn` is therefore:

```
Log(Fn) = Log(φⁿ) + Log(1 - (ψ/φ)ⁿ) - Log(φ - ψ)

```

Which is the same as:

```
Log(Fn) = n Log(φ) + Log(1 - (-ψ/φ)ⁿ) - Log(φ - ψ)

```

This last expression is simple to compute and will not overflow.

You can see some example C# code here, with results up to `Fib(1000)`: http://ideone.com/7VaRrK (the value for `Fib(2)` suffers from a minor rounding error, you could handle 1 and 2 as special cases if it is really important to you)
> 2 votes

# Answer
You're trying to get the floating point logarithm of a number that isn't representable in a (single sized-)float. The limit of floating point numbers is around 3.402823e+38, larger than your number, truncating it to (positive) infinity.

If you want a logarithm for such large numbers you're going to have to use your own implementation.

However if you just want to use the fibonacci sequence you can simply store their logarithms calculated via an arbitrary precision calculator like dc.
> 2 votes

---
Tags: mathematics, unity
---