title: Keycodes map to wrong keys

text:
# Question
Title: Keycodes map to wrong keys
I'm working on an Android app/semi-game (API 19-23, Java) and I used this website to help me handle controller input. Overall it looks pretty similar to what the website says for "Process Gamepad Button Presses":

```
public boolean processKeyEvent(int keyCode, String name) {
    boolean handled = false;
    switch (keyCode) {
        case KeyEvent.KEYCODE_BUTTON_L1:
            ...
        case KeyEvent.KEYCODE_BUTTON_R1:
            ...
        case KeyEvent.KEYCODE_BUTTON_A:
            ...
        case KeyEvent.KEYCODE_BUTTON_B:
            ...
        case KeyEvent.KEYCODE_BUTTON_X:
            ...
        case KeyEvent.KEYCODE_BUTTON_Y:
            ...
        case KeyEvent.KEYCODE_BUTTON_START:
            ...
        case KeyEvent.KEYCODE_BACK:
            ...
    }
    if(handled) {
        return true;
    }
    return false;
}

```

and:

```
public boolean dispatchKeyEvent(android.view.KeyEvent event) {
    if(event.getAction() == KeyEvent.ACTION_DOWN) {
        handled = script.processKeyEvent(event.getKeyCode(), event.getDevice().getName());
    }

    if (handled) {
        return true;
    } else {
        return super.dispatchKeyEvent(event);
    }
}

```

It does return the right keycodes (according to this list), so:

* L1: 102
* R1: 103
* A: 96
* B: 97
* X: 99
* Y: 100
* Start: 108
* Back: 4

The problem is that half of the buttons not only activate through their right case but also other ones, which then has side effects of course:

* B activates: X, Y, Start
* X: Y, Start
* Y: Start
* R1: A
* L1: R1, A

At first I thought that maybe the controller (SteelSeries Stratus XL for Android) had broken but I already checked with a second one (MogaPro Power) and I got the same results with it.

Has anyone else experienced this before? Any idea what I could try to fix this?

# Answer
After a quick investigation it looks like you are missing some `break;` statements from your cases which results in flow-trough.
> 7 votes

---
Tags: java, android, gamepad
---


title: RPG Formula - Attack and defense

text:
# Question
Title: RPG Formula - Attack and defense
I'm making a game and I'm struggling with the formula to calculate the real damage the player does. I have skills which can do for example 10 hits of 20% weapon damage each of a total of 200% damage. Or another skill does 200% damage 1 hit.

However the formula I have right now is something like this

```
( 2 * Attack - Defense ) * 0.5

```

As you can see with an equal defense, the attack that does 1 hit 200% weapon damage will actually do more damage than the skill that does 10 hits 20% weapon damage each, because the reduction is greater when dealing low amounts of damage.

Or another case is a weapon does 200 physical damage and 50 fire damage. With this formula a enemy with 100 defense receives 150 physical (ok) and 0 fire damage (negative, not ok)

Can anyone help me get a formula (not too complex)? I don't know what to try. What I want to achieve is to get the same real damage (1 hit @ 200% or 10 hits @ 20%) and make the defense matter, what I mean by that is that it affects the attack.

# Answer
> 18 votes
When you want one hit with 200% attack to be exactly equal to 20 hits with 10% attack, then your only option is to make defense a percent value.

When the defender has 55% defense vs. physical damage, then the total amount of physical damage they receive is reduced to 45%, no matter how large or small the portions in which it gets dished out.

However, percentual defense has its pitfalls, especially in RPGs where you have a continuous progression. You can never allow to go above 100%, because then you have total invulnerability. Even getting very close to 100% is a balancing nightmare. The difference between 97% and 99% means the character can withstand three times as many hits, so an inconspicuous 2% defense buff can turn out to be a game-breaker. On the other hand, there is not much practical difference between having a total of 1% or 3% defense, so it is hard to still have a meaningful progression on lower levels.

A different formula used to calculate damage which you see quite often is:

```
damage = att * att / (att + def)

```

The nice thing about this formula is that it scales without limit:

* When attack and defense are roughly the same, there is roughly half as much damage as attack. This is true no matter how large the values are.
* Even when the defense is pathetic compared to the attack value, there is never more damage than attack. This gives you an upper limit on how much damage a character can inflict, which makes balancing far easier.
* On the other extreme, no matter how high the defense gets, it can never completely mitigate damage (except through rounding errors), so there is always room for improvement for the defender and there is never a completely pointless attack.

But you still have a bias for few, strong attacks over many weak ones. But the bias is lower the less defense the target has compared to your attack. This means that different attack strategies are efficient depending on whether you face an enemy with more or less defense. This usually adds depth to the game while still keeping it intuitive (a heavily armored enemy has to be cracked with a single, very powerful attack while a lightly armored enemy is more vulnerable to a flurry of weaker blows).

Also, you need to be aware that you get a result of `NaN` (or a division by zero error with integer arithmetic) when both attack and defense is 0, so you should not forget to handle that situation separately. You also get weird results when you insert negative values, so your character system should not allow negative attack or defense (when you want healing magic which uses the same formula, invert the sign afterwards).

---
Tags: rpg, mathematics
---


# Question
Title: Unity ball not bouncing off wall correctly
I have been making a brick breaker game in Unity in 2D as my first game. I have got the ball bouncing off the paddle correctly and can bounce it of the paddle at different angles. However, when the ball hits a wall or the roof it always bounces so its either traveling exactly in the X-directon or Y-direction regardless of what angle it hits the wall with instead of bouncing off at 90'.

Im not using any scripts to control the bouncing off the walls or roof just using 2D box colliders on the roof and walls (which are cubes) and a circle collider and 2D rigidbody on the ball (sphere) which Ive given a bouncy material.

Any help would be really appreciated.

Here's a gif of the problem: https://i.stack.imgur.com/xvtgY.jpg

# Answer
Typing up an answer based on our troubleshooting in the comments above:

It looked to me like your ball was suddenly losing a lot of its momentum in the direction parallel to the wall, as soon as it impacted. That could be a sign that the friction value in its PhysicsMaterial2D is too high.

Setting friction to zero on the ball should help.

In 3D, you'd also set FrictionCombine to Minimum or Multiply to ensure it stays zero even if it strikes an object with a high friction value.
> 2 votes

---
Tags: c#, 2d, physics, unity
---


# Question
Title: How do I calculate UV space from world space in the fragment shader?
In my vertex shader I have calculated the world space

```
o.worldSpacePosition = mul(unity_ObjectToWorld, vertIn.vertex);

```

How do I convert that world space into uv space coordinates in my fragment shader?

```
        float4 frag(VertexShaderOutput i) : COLOR //SV_Target0
        {
            // float2 uv = i.worldSpacePosition ???

        }

```

I have tried

```
float4 mvp = UNITY_MATRIX_MVP[3];
float2 uv = mvp.xy /= p.w;

```

but that does not appear to work as the uv is always (0, 0)

EDIT:

I am drawing a mesh on the screen in world space coordinates which needs to lookup into a screen space texture:

The way I am currently solving this is by calculating the uvs for each vertex of the mesh using the following calculation:

```
camera.WorldToViewportPoint(vertices[i]);

```

Unity uses normalised coordinates for the viewport \[0,1\] rather than \[-1,1\].

This works fine but I wasn't sure of the behaviour if part of the polygon is off the screen. I presume I should clamp the uv?

Screen space might not be the correct term for the uv coordinates. Perhaps texture space is a more appropriate term?

# Answer
> 7 votes
Do I understand correctly that you want an effect somewhat like this?

(If I'm way off, you may need to edit your question to include more description of what you're trying to do and why)

Here I have a monochrome blue background image, and a cube with a material that displays a colour version of the same image, using screenspace UV coordinates. (Textures courtesy of Kenney)

Because both textures are looked up in screenspace, they line up no matter how the cube is positioned or rotated in the world. All that matters is which screen pixels it covers.

---

To do this in a **vertex-fragment shader**, you'd add a screen position property to your `VertexShaderOutput`:

```
struct v2f
{
    float4 vertex : SV_POSITION;
    float3 screenPos : TEXCOORD0;
};

```

then in the vertex shader, we'll use it to store our projected vertex coordinates:

```
v2f vert (appdata v)
{
    v2f o;
    o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
    o.screenPos = o.vertex.xyw;

    // Correct flip when rendering with a flipped projection matrix.
    // (I've observed this differing between the Unity scene & game views)
    o.screenPos.y *= _ProjectionParams.x;

    return o;
}

```

Note here I've discarded the z component and stored the w component of the projected vertex in its place. This will probably just get padded out to a full float4 width anyway, but I wanted to show that we only need the three components, in case you have an extra float you need to pack in for whatever reason.

It may look a bit weird to be outputting the same projected vertex data twice, but the `SV_POSITION` semantic means the `vertex` `float4` gets treated a bit specially and doesn't have the same values by the time the interpolator's done its work and it reaches the fragment shader. There might be more efficient ways to work with this - if anyone knows them please post in the comments below!

Lastly, in the fragment shader, we construct our screenspace position like this:

```
fixed4 frag (v2f i) : SV_Target
{
    float2 screenUV = (i.screenPos.xy / i.screenPos.z) * 0.5f + 0.5f;

    // ...rest of your shader goes here.
}

```

The division by z (really vertex.w) here is called a perspective divide. It needs to be done per-fragment if you're using a perspective camera where polygons can be tilted relative to the camera, to prevent artifacts where surfaces appear to crease & slide along their triangle edges.

---

If you're using a **Surface Shader**, you'd modify your Input struct to include the `screenPos` property:

```
 struct Input {
    float2 uv_MainTex;
    float4 screenPos;
 };

```

Then in the shader you'd calculate your screenspace UV using:

```
float2 screenUV = IN.screenPos.xy / IN.screenPos.w;

```

---
Tags: unity, shaders, fragment-shader
---


title: Unity2D: Frost Effect Time scale

text:
# Question
Title: Unity2D: Frost Effect Time scale
I downloaded this package ("Frost Effect by Steven Craeynest") on Unity Asset Store and altered it into making the effect happen once I click on a button (button 1), I first disabled the frost button (button 1) in my inspector before playing the game and created another button (button 2) to activate the frost button(button1). However I'm having issues with the frost effect. You see when I click on button 2 to activate the frost button (button 1) frost effect works for a bit but then stops at delayBeforeUnfreeze like time.timescale is equaled to 0 and the only way of making time.timescale is equaled to 1 is by pressing my pause button and clicking the resume button. Anyway this is my script:

```
private FrostEffect frost;
float duration = 0.2f;
float delayBeforeUnfreeze = 0.34f;
private float previousTimeScale;
public GameObject frostbutton;
public int buttonCount = 0;
int timesActivated =  0;

public void Check() {
    buttonCount ++;
}

// Use this for initialization

void Start () {
    previousTimeScale = Time.timeScale;
}

public void Activate ()
{
    frostbutton.SetActive (true);
}
public void CreateFrost ()
{
    if(timesActivated < buttonCount)
    {
        timesActivated++;

        GameObject.Find ("Main Camera").GetComponent<FrostEffect> ().enabled = true;
        //Slow timescale
        Time.timeScale = 0.06f;
        //Freeze time effect
        DOTween.To (x => FrostEffect.FrostAmount = x, 0.0f, 0.34f, duration)
    .OnComplete (() => {
            //Unfreeze tween effect
            DOTween.To (x => FrostEffect.FrostAmount = x, 0.34f, 0f, duration)
                .SetDelay (delayBeforeUnfreeze);

            //Set timescale back to previous.
            Time.timeScale = previousTimeScale;
        });
    }
}

```

} Thank you. :)

**Second Edit**

This is my panel animation script:

```
public void DisableBoolAnimator(Animator anim)
{
    anim.SetBool ("Shown", false);
}

public void EnableBoolAnimator(Animator anim)
{
    anim.SetBool ("Shown", true);
}

```

This Youtube link will show you what my panel animation looks like: 31:47. Thank you. :)

# Answer
> 1 votes
Taking a quick scan of the DOTween documentation, it looks like by default it uses Unity's time / deltaTime values to advance the tween.

That means when you set timeScale to zero, you not only stop the game, you stop the tween too. Since the tween never finishes, it never runs the OnComplete method that restores the previousTimeScale.

Fortunately, this is literally the third item covered in the library's Frequently Asked Questions:

> **How to ignore Unity's Time.timeScale when tweening?**
>
> Just chain the SetUpdate method to a tween, passing a value of TRUE to the isIndependentUpdate parameter. transform.DOMoveX(2, 1).SetUpdate(true);

So, it looks like your code would become something like this:

```
DOTween.To (x => FrostEffect.FrostAmount = x, 0.0f, 0.34f, duration)
    .OnComplete (() => {
        //Unfreeze tween effect
        DOTween.To (x => FrostEffect.FrostAmount = x, 0.34f, 0f, duration)
            .SetDelay (delayBeforeUnfreeze);

        //Set timescale back to previous.
        Time.timeScale = previousTimeScale;
    })
    .SetUpdate(true);

```

---
Tags: unity
---


# Question
Title: OpenGL shader program per shape or model
I have a program which imports models from `.obj` files and then draws them with OpenGL. I have a model which contains many shapes (meshes?). Not every shape has texcoords defined inside .obj file (it looks like `1//1` instead of `1/1/1`) and I try to use one shader program which depends on texcoords.

What would be the best solution for that problem? Should I use separate programs for shapes that have texcoords and another for shape without texcoords defined?

Maybe there is a way to check if some attributes were passed to shader program?

This is the gist with *.obj*, *.mtl* and *shader* files, maybe that will help you to understand my problem.

# Answer
Make seperate programs, and make sure to split your meshes into two lists: one for the ones with texcoords and one for thise without. Make sure to render first all of one list and then all of the other list, you do not want to switch between the two shaders more than once because of the overhead associated with state changes.

The reason I think this is better is because you're going to have gibberish UV values if you do a general program, so the shaders are probably going to render quite different anyway.

If you want to use the same program, just create an uv buffer even for the .obj shapes missing uv coordinates, and fill it with like, (0.0, 0.0) for every vertice that is part of the shape.
> 1 votes

---
Tags: opengl, c++
---


# Question
Title: How to set up OpenGL for CLion on Windows
Can someone give me a simple step-by-step on how to set up and compile a simple "Hello World!" program on CLion using OpenGl/SDL/Freeglut . I see a lot of tutorials on Visual Studio, but CLion uses CMake so it's a lot different.

# Answer
> 6 votes
Use a CMakeLists.txt file. It would look something like this.

```
cmake_minimum_required(VERSION 3.3)
project(projectname)

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/bin")

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -pthread -fpermissive")

find_package (PkgConfig REQUIRED)
find_package (OpenGL REQUIRED)
find_package (GLUT REQUIRED)

include_directories(${OPENGL_INCLUDE_DIR}  ${GLUT_INCLUDE_DIRS})

file(GLOB SOURCE_FILES
    *.cpp
    *.h
    )

add_executable(main.cpp ${SOURCE_FILES})

target_link_libraries (main.cpp ${OPENGL_LIBRARIES} ${GLUT_LIBRARIES} GL m dl Xinerama Xrandr Xi Xcursor X11 Xxf86vm pthread)

```

I copied this from a test project that I have. It works on Linux and Windows both. It is stripped down to only what is necessary.

This is where I learned https://cmake.org/cmake-tutorial/

---
Tags: opengl, sdl
---


# Question
Title: What version of OpenGL should I target for Steam?
I'm planning on developing a game (targeting towards PC and Linux) and putting it up on Steam in the future but I am not sure of what version of OpenGL to target so that the majority of steam users can be able to play my game.

I know Steam has a hardware survey but I'm still not sure of what OpenGL to use but a lot of people recommend OpenGL 3.0 and to make sure not version OpenGL 3.x since 3.x != 3.0.

# Answer
> 6 votes
For PC, this question looks like a duplicate of What OpenGL version(s) to learn and/or use? so I'm not going to repeat that answer here.

For Mac, Apple provide a nice table at https://developer.apple.com/opengl/capabilities/

Essentially anything newer than 3.3 on a Mac is not going to work on all graphics cards, and you may well want to go with 3.2 (with GLSL 1.5) to support older versions of the operating system.

# Answer
> 1 votes
> What version of OpenGL should I target for Steam?

All of them.

Jokes aside, there is no definite version to target and previous statement holds some truth. Although I would use ~GL3.0 as the minimum *requirement*, everything else is *optional*. This is quite simply, because you obviously can't take use extensions which are not supported while it would also be stupid not to take advantage of the hot new extensions. This requires quite a bit of coding of course because you need to check which extensions are supported and select different ways to acheive a specific goal using said extensions but imo its the way to go. And with some clever abstraction it's not *that* hard.

A good example of this is `GL_ARB_direct_state_access`. Although support is still not that great with some odd 20%, but why wouldn't I take advantage of it on the platforms that *do* support it.

---

**TL:DR**
Around GL3.0 should be the minimum *required* version while still using optional extensions that are available.

# Answer
> 1 votes
If you want it to work on a Mac too then use 3.2. It has most things you need. If you want fancier things like tessellation and don't want to support Macs I suggest you go for 4.3. It is supported by most iGPU-s and should be a valid baseline. DirectX and OpenGL version have no correlation. I would suspect 90%+ of hardware of Steam users to be capable of OpenGL 4.3.

Take a look at https://www.opengl.org/wiki to find out what is the lowest OpenGL version that supports the features that you want.

# Answer
> -3 votes
On PC if you are starting right now I would target 4.5 and possibly even go to vulkan. By the time you get it done most people will have it anyway, if they don't already - and this will make your work much easier.

The next logical place is 3.3, but at this point cards with only 3.3 are about 10 years old or something. Assuming you are still working with this engine in another 10 years do you really want to have 20 year old legacy code dragging it down by then?

---
Tags: opengl
---


# Question
Title: How can I stop the endless output in Unity console?
I want to print the sum of two numbers, but only when I press the enter key. Pressing any other key should give me the message "Invalid Key". Now the output I am getting is an endless loop of "Invalid key", until I press another button.

How do I only produce the output when I press a key?

```
using UnityEngine;
using System.Collections;

public class LearningScript : MonoBehaviour {

    public int number1 = 5;
    public int number2 = 10;
    public bool condition;
    public int answers;

    void Update()
    {
        if (Input.GetKey (KeyCode.Return))
            condition = true;
        else
            condition = false;

        if (condition)
            Debug.Log (answers);
        else
            Debug.Log ("INVALID KEY");
    }

    void Start()
    {
        answers = addTwonumbers (number1, number2);
    }

    int addTwonumbers(int num1,int num2)
    {
        int result = num1 + num2;
        return result;
    }
}

```

# Answer
Modify your `Update` to look like below:

```
void Update ()
{
    if (Input.GetKeyDown(KeyCode.Return))
    {
        condition = true;
        Debug.Log(answers);
    }
    else if (Input.anyKeyDown)
    {
        condition = false;
        Debug.Log("INVALID KEY");
    }
}

```

Printing the "Invalid Key" message without a condition is causing the message to print in every frame, whenever you are not pressing the enter key.

Also use `GetKeyDown` to avoid multiple calls from a single press that spans multiple frames.
> 4 votes

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


# Question
Title: Shader to render objects with distance independent size
I am trying to find a way to render certain objects in my 3d scene without the effects of the perspective projection. E.g. I want them to have the same pixel dimension independent of distance to the camera or the dimensions of the viewport.

Here is what I tried in the vertex shader so far

```
uniform vec2 screen_size;

varying float camera_distance;

void main() {
    mat4 mvp = projectionMatrix * modelViewMatrix;

    float scaleFactor = 2.0 * 50.0 / screen_size.x;
    float w = (mvp * vec4(0.0, 0.0, 0.0, 1.0)).w;
    w = w * scaleFactor;

    gl_Position = mvp * vec4(position.xyz * w, 1.0);
}

```

So far no luck.

# Answer
> -1 votes
Here's the shader code:

```
void main() {

mat4 mvp = projectionMatrix * modelViewMatrix;

vec4 temp = mvp * vec4(position.xyz, 1.0);

gl_Position = vec4(temp.xy*w,temp.zw);
}

```

To adjust the size of the ring just change the size of the quad or triangle.

---
Tags: opengl, glsl, three.js, vertex-shader
---


# Question
Title: Add a random number to an existing number to produce output in Unity
I am trying to add a random number to an existing number. I am able to get the output in Unity console, but in the inspector, I can see that the public variable is on a non stop loop.

I intend to produce the result when I press the enter key. Is this an efficient way, or can I improve on the code? I am a beginner, and passionate to learn.

Here's the code:

```
using UnityEngine;
using System.Collections;

public class LearningScript : MonoBehaviour
{
    public int number1 = 5;
    public int number2 = 10;
    public int number3=20;
    public int finalResult;
    public string statement = "NO KEY PRESSED";

    void Update()
    {
        input ();
        if (Input.GetKeyDown (KeyCode.Return))
            Debug.Log (finalResult);
    }

    void Start(){}

    int addnumbers(int num1,int num2)
    {
        int additionResult = num1 + num2;
        return additionResult;
    }

    void input()
    {
        int randomNumber = Random.Range (1, 10);
        finalResult=    addnumbers (number1, randomNumber);
    }
}

```

# Answer
> 1 votes
As stated, your problem is in calling `input()` on each `Update()`. You would replace your `Update` function as follows (be particularly mindful of the closing brackets on the `if` statement):

```
void Update() {
    if (Input.GetKeyDown (KeyCode.Return)) {
        input ();
        Debug.Log (finalResult);
    }
}

```

Given the context of the question, lets have a closer look at *why* this is the problem.

### The Update Method

The `Update()` method comes from `MonoBehaviour`. You will notice that at the top, your class is called `LearningScript : MonoBehaviour`. The `: MonoBehaviour` offers extension of the original `MonoBehaviour` class that provides most of the functionality, in Unity.

`Update()` is a re-iterating method that will call *on each game update*. You should use this as your main starting point for logic that repeats itself, but use caution: Updating too much can easily lead to freezing. In this case, you are actually not doing anything to freeze your game. You are simply refreshing `finalResult` so quickly that it overrides any real-time changes you may make, often quicker than you would notice.

By ensuring you only update your input *when you need to*, i.e. when the user first presses the Enter button, you ensure that your code is far more efficient.

```
void Update() {
    if (Input.GetKeyDown (KeyCode.Return)) {
        input ();
        Debug.Log (finalResult);
    }
}

```

### Notes on `MonoBehaviour` methods

`Update` is but one of many methods you can implement from the original `MonoBehaviour` class. While it is easily the most common, you will quickly find yourself using other methods, such as `Start`, `FixedUpdate` and `OnCollisionEnter(Collision other)`. You can find a good list, linking you to instructions on each method, under "Messages" in the Unity API listing for `MonoBehaviour`.

`Start` is as commonly used as `Update`, as it provides the entry point for code to set up your class. As a result, it is also provided by default, when you create a new script. In your above code, you set everything up when you declare the variables, and could completely remove the `Start() {..}` function without any change to your script.

### Notes on `if` statements

In your original statement, you write it as follows:

```
if(input)
    doSomething;

```

This is not the wrong way to do it; in fact, it is often a matter of opinion. You will notice that my solution writes it as follows:

```
if(input) {
    doSomething;
    doSomethingElse;
}

```

This part is important: With the use of *multiple* lines, you *must* use enclosing "squiggly brackets" (`{ }`). If you do not, it can cause errors. What is worst; it can cause errors *later* in your class, as your compiler may interpret the statement entirely different to how you intend, and only realise there is a problem when later lines of code do not make sense given its misunderstanding. Long story short, if you have this problem, Unity could very well tell you it is a *completely different* problem, on a *completely different* line. It is important to know that these things do happen, and can lead to some very frustrating moments. Think of it as character building - even the best of us have those stories where we banged our head against a brick wall for hours only to have someone point out the obvious problem after a minute of review.

### Notes on naming conventions

Naming conventions are even more debatable, when it comes down to the semantics of how we should name things. One major thing I will point out is the use of capital letters to start each new word in a name. You seem to be following this standard, except for your classes. While you surely would have no problem interpretting `addnumbers`, most would tell you it should be `addNumbers`.

A personal preference of mine is to start with a lower case, if I am naming a variable, or upper case, if I am naming a method. So I would use `AddNumbers`. This just makes it easier to quickly identify the variables and the methods.

# Answer
> 0 votes
That is because you call `input()` in the Update method, which is called each frame. Put your `input()` in the input-taking `if` block.

```
void Update()
{
     if (Input.GetKeyDown (KeyCode.Return))
     {
        input ();
        Debug.Log (finalResult);
     }
}

```

Now input only gets called once you press down Return.

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


# Question
Title: Unity2D: Don't Destroy On Load UI button
I have a UI button as a child under my background canvas. What I want to do is to save the button through out scene, I tried using DontDestroy OnLoad but It saved ay canvas and everything under my canvas, rather than saving just the button. Anyway this is my DontDestroyOnLoad script:

```
void Awake()
{
    DontDestroyOnLoad(transform.root.gameObject);
}

```

Thank you. :)

# Answer
> 2 votes
Well I wiped up a script that does this but the solution seem janky. Use it at your own risk.

```
using UnityEngine;
using UnityEngine.SceneManagement;

public class TestButtonPersist : MonoBehaviour
{
    void Awake()
    {
        //We subscribe to  the event for  loading a scene
        SceneManager.sceneLoaded += MyOnLoad;
    }

    void MyOnLoad(Scene scene,LoadSceneMode sceneMode)
    {
        //if our button does not have a parent then we will find it a Canvas.
        if (gameObject.transform.parent == null)
        {
            gameObject.transform.SetParent(
                    GameObject.Find("Canvas").gameObject.transform, false);
            // You might want to use Find with tag here to make sure you will find a canvas
        }
    }

    // This is where the magic happens
    public void LoadLevel()
    {
        // Before we call the code for loading the level,
        //we make sure to set the button as a root object
        gameObject.transform.SetParent(null,false);
        DontDestroyOnLoad(gameObject);
        SceneManager.LoadScene(1);
    }
}

```

The thing is you need to call `transform.SetParent(null,false)` for the object before the scene changes so you will have to do this from your code that loads a new scene.

---
Tags: unity
---


# Question
Title: My 2D Sprite/Diffuse material is not lighting when I start the game
I put a Sprite/Diffuse Material on my Player.

In the scene, before starting the game it looks ok (1st screenshot).

After starting the game it still works fine, but when I am starting to move the player on x-axis the it becomes black (2nd screenshot).

Why?

This is the script I use to transform the Player's position and scale:

```
void Update()
{
    Move();
    {
        float moving = Input.GetAxis("Horizontal");
        characterAnim.SetFloat("Speed", moving);
    }
}

void Move()
{
    if (Input.GetKey("right"))
    {
        transform.localScale = new Vector2(1, 1);
        transform.Translate(Vector2.right * speed * Time.deltaTime);
    }
    if (Input.GetKey("left"))
    {
        transform.localScale = new Vector2(-1, 1);
        transform.Translate(Vector2.right * speed * Time.deltaTime);
    }
    //    rb2D.AddForce(transform.up * 20);
}

```

# Answer
It's not an issue form Lighting or Material. Modifying `localScale` with a 2D vector is making the Z value zero is causing the issue.

`transform.localScale = new Vector3(1, 1, 1);`

Also correct you Translate direction when taking input for Left.

```
void Move()
{
    if (Input.GetKey("right"))
    {
        transform.localScale = new Vector3(1, 1, 1);
        transform.Translate(Vector2.right * speed * Time.deltaTime);
    }
    if (Input.GetKey("left"))
    {
        transform.localScale = new Vector3(-1, 1, 1);
        transform.Translate(Vector2.left * speed * Time.deltaTime);
    }
}

```

Use `Sprites-Default` material unless you have other purpose. You also don't need a light to illuminate objects with `Sprites-Default` material in them.
> 0 votes

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


# Question
Title: Do I need to initialize a public List variable in Unity?
I want to create a list of horses and print the name of the Horses that are stored in the list. Although I got the answer correct as I desired, there's one thing that is puzzling me when I declare a list variable.

I declared it as:

`public List<string> myFavouriteHorses;`

and in an example I have seen it's declared like this:

`public List<string> myFavouriteHorses = new List<string> ();`

Despite this difference, both of them worked. What's the difference between these two approaches? Does it matter which one I use?

Here's the entire code which i tried:

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

public class LearningScript : MonoBehaviour {

    public List<string> myFavouriteHorses = new List<string> ();

    void Start(){
        myHorses ();
        }

    void Update(){
        if (Input.GetKeyDown (KeyCode.Return)) {
            Print ();

        }

    }

    void myHorses(){

        myFavouriteHorses.Add ("Grey Horse");
        myFavouriteHorses.Add ("Black Horse");
        myFavouriteHorses.Add ("Rudolph Horse");
        myFavouriteHorses.Add ("Biting Horse");
    }

    void Print(){
        Debug.Log ("This list has " + myFavouriteHorses.Count + " horses");

        Debug.Log ("The horse at index 1 is " + myFavouriteHorses [1]);
        Debug.Log ("The horse at index 2 is " + myFavouriteHorses [2]);
        Debug.Log ("The horse at index 3 is" + myFavouriteHorses [3]);

    }

}

```

Here's the output

Why doesn't it make a difference whether or not I initialize the `List` with `new` before using it?

# Answer
> 2 votes
Unity's editor automatically creates the `new List ()` part when generating the game. That's how you can already populate it with data in the editor. Things assigned in the editor will be added to the gameobject even BEFORE `Awake()` and `Start()` so if you assign the variable somewhere in `Awake()` or `Start()` (or in a function called during one of them, such as `myHorses()`) it will override the assignment done in the editor.

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


# Question
Title: Picking a specific point of a map in Direct 3D
I'm trying to pick a specific point on a randomly generated terrain with bunch of tiny triangles. Right now, I'm just iterating through every triangle and picking a intersected triangle using D3DXIntersect function. It serves its function but the performance is just not tolerable.

Is there a way to pick a triangle without millions of iteration?

# Answer
Do you know how the triangles are created? If you have access to that, you could choose a random triangle at creation and store that. I don't see a reason you should need to use the GPU or DirectX for this task unless they are sent to the GPU in code you don't have access to.
> 1 votes

---
Tags: directx9
---


# Question
Title: Dealing with AI in a simple strategy game
Hi I am currently working on a small real-time strategy game.

The game consists in discovering and exploring planets to get knowledge and resource points. Every Unit of Time (UoT) in the game those points are adjusted based on a various factors. Basically the more planets you have explored the more points are generated, yet the more planets you get the greater the expenses per UoT, so it is a balance. There are a variety of planet types, some which allow to discover planets in a greater area, but produce little points, whilst others produce a lot of points. The longer the players lasts before running out of resource points and the more planets they explore the higher their score is.

I kind of got a decent game at the moment, but I wanted to add an AI to have other explorers competing against the player. I don't really know how to handle it.

So far my thoughts are to add weights to various parameters (like the number of points provided by each planet, the cost in points to explore it, the fact that it has been already explored, etc...). Those weights would be adjusted based on a variety of conditions, say if the player resource points drop below x then the weight attributed to the number of resource points provided would be greater than that of knowledge points.

I was wondering if anyone had any thoughts on this, is it likely that I'm going to get myself tangled in all of it if I do it this way.

Also one important thing to note is that the game space is randomly generated, i.e every time a UoT passes or an explorer explores a planet there is a chance that 2 new planets are being randomly generated. Which means I can't really use methods which are based on calculating a few turns ahead to make the best decision.

Finally, the game is relatively peaceful, I don't have a combat system, and the only risk of exploring a planet already explored by another explorer would be that, if that explorer is nearby, he might just re-explore it as soon as you have left meaning you have spent valuable resource points for no benefits, since all the point generation will go to the most recent explorer.

# Answer
Having the AI generate a list with all possible decisions, rating each one based on a set of predetermined and pre-weighted factors and then picking the decision with the best rating is a good way to get a pretty decent AI.

At least as long as the number of decisions is manageable and you have enough understanding of your own game and its strategy to come up with an effective rating algorithm for decisions.

Difficulty can be adjusted by having the AI not take all possible factors into account or just plain cheating (give the AI more resources than the player or have it ignore restrictions which apply to the player). The last is the most popular with developers, while players usually expect the first, but rarely get it.

The main problem with such an AI is that it is very sensitive to slight balancing changes. A slight change in the game rules can affect which decisions are good in which situation. When you forget to adjust your AI rules accordingly, then the AI can become very weak. This is especially problematic when you allow your players to mod the game in ways which changes game mechanics but doesn't provide a way to tell the AI about those changes.
> 3 votes

---
Tags: ai, strategy
---


# Question
Title: How do I move the camera in full pixel intervals?
Basically I want to stop the camera from moving in subpixels, as I think this leads to sprites visibly changing their dimensions if just ever so slightly. (Is there a better term for that?) Note that this is a pixel-art game where I want to have crisp pixelated graphics. Here's a gif that shows the problem:

Now what I tried was this: Move the camera, project the current position (so it's screen coordinates) and then round or cast to int. After that convert it back to world coordinates and use that as the new camera position. As far as I know, this should lock the camera to actual screen coordinates, not fractions thereof.

For some reason, however, the `y` value of the new position just explodes. In a matter of seconds it increases to something like `334756315000`.

Here is a SSCCE (or an MCVE) based on the code in the LibGDX wiki:

```
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.badlogic.gdx.utils.viewport.Viewport;

public class PixelMoveCameraTest implements ApplicationListener {

    static final int WORLD_WIDTH = 100;
    static final int WORLD_HEIGHT = 100;

    private OrthographicCamera cam;
    private SpriteBatch batch;

    private Sprite mapSprite;
    private float rotationSpeed;

    private Viewport viewport;
    private Sprite playerSprite;
    private Vector3 newCamPosition;

    @Override
    public void create() {
        rotationSpeed = 0.5f;

        playerSprite = new Sprite(new Texture("/path/to/dungeon_guy.png"));
        playerSprite.setSize(1f, 1f);

        mapSprite = new Sprite(new Texture("/path/to/sc_map.jpg"));
        mapSprite.setPosition(0, 0);
        mapSprite.setSize(WORLD_WIDTH, WORLD_HEIGHT);

        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();

        // Constructs a new OrthographicCamera, using the given viewport width and height
        // Height is multiplied by aspect ratio.
        cam = new OrthographicCamera();

        cam.position.set(0, 0, 0);
        cam.update();
        newCamPosition = cam.position.cpy();

        viewport = new ExtendViewport(32, 20, cam);
        batch = new SpriteBatch();
    }

    @Override
    public void render() {
        handleInput();
        cam.update();
        batch.setProjectionMatrix(cam.combined);

        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();
        mapSprite.draw(batch);
        playerSprite.draw(batch);
        batch.end();
    }

    private static float MOVEMENT_SPEED = 0.2f;

    private void handleInput() {
        if (Gdx.input.isKeyPressed(Input.Keys.A)) {
            cam.zoom += 0.02;
        }
        if (Gdx.input.isKeyPressed(Input.Keys.Q)) {
            cam.zoom -= 0.02;
        }
        if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
            newCamPosition.add(-MOVEMENT_SPEED, 0, 0);
        }
        if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
            newCamPosition.add(MOVEMENT_SPEED, 0, 0);
        }
        if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
            newCamPosition.add(0, -MOVEMENT_SPEED, 0);
        }
        if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
            newCamPosition.add(0, MOVEMENT_SPEED, 0);
        }
        if (Gdx.input.isKeyPressed(Input.Keys.W)) {
            cam.rotate(-rotationSpeed, 0, 0, 1);
        }
        if (Gdx.input.isKeyPressed(Input.Keys.E)) {
            cam.rotate(rotationSpeed, 0, 0, 1);
        }

        cam.zoom = MathUtils.clamp(cam.zoom, 0.1f, 100 / cam.viewportWidth);

        float effectiveViewportWidth = cam.viewportWidth * cam.zoom;
        float effectiveViewportHeight = cam.viewportHeight * cam.zoom;

        cam.position.lerp(newCamPosition, 0.02f);
        cam.position.x = MathUtils.clamp(cam.position.x,
                effectiveViewportWidth / 2f, 100 - effectiveViewportWidth / 2f);
        cam.position.y = MathUtils.clamp(cam.position.y,
                effectiveViewportHeight / 2f, 100 - effectiveViewportHeight / 2f);

        // if this is false, the "bug" (y increasing a lot) doesn't appear
        if (true) {
            Vector3 v = viewport.project(cam.position.cpy());
            System.out.println(v);
            v = viewport.unproject(new Vector3((int) v.x, (int) v.y, v.z));
            cam.position.set(v);
        }
        playerSprite.setPosition(newCamPosition.x, newCamPosition.y);
    }

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

    @Override
    public void resume() {
    }

    @Override
    public void dispose() {
        mapSprite.getTexture().dispose();
        batch.dispose();
    }

    @Override
    public void pause() {
    }

    public static void main(String[] args) {
        new Lwjgl3Application(new PixelMoveCameraTest(), new Lwjgl3ApplicationConfiguration());
    }
}

```

and here's the `sc_map.jpg` and the `dungeon_guy.png`

I'd also be interested to learn about simpler and/or better ways to fix this problem.

# Answer
**Your problem isn't moving the camera in full-pixel increments. It's that your texel-to-pixel ratio is slightly non-integer**. I'll borrow some examples from this similar question I answered on StackExchange.

Here's two copies of Mario - both are moving across the screen at the same rate (either by the sprites moving right in the world, or the camera moving left - it ends up equivalent), but only the top one shows these rippling artifacts and the bottom one doesn't:

The reason is that I slightly scaled the top Mario by 1 factor of 1.01x - that extra tiny fraction means he no longer lines up with the screen's pixel grid.

A small *translational* misalignment isn't a problem - "Nearest" texture filtering will snap to the closest texel anyway without us doing anything special.

But a *scale* mismatch means this snapping isn't always in the same direction. In one spot a pixel looking up the nearest texel will pick one slightly to the right, while another pixel picks one slightly to the left - and now a column of texels has either been omitted or duplicated in-between, creating a ripple or shimmer that moves over the sprite as it travels across the screen.

Here's a closer look. I've animated a translucent mushroom sprite moving smoothly, as though we could render it with unlimited sub-pixel resolution. Then I've overlaid a pixel grid using nearest-neighbour sampling. The whole pixel changes colour to match the part of the sprite under the sampling point (the dot in the center).

1:1 Scaling

Even though the sprite moves smoothly to sub-pixel coordinates, its rendered image still snaps correctly each time it travels a full pixel. We don't need to do anything special to make this work.

1:1.0625 Scaling

In this example, the 16x16 texel mushroom sprite has been scaled up to 17x17 screen pixels, and so the snapping happens differently from one part of the image to another, creating the ripple or wave that stretches & squashes it as it moves.

So, the trick is to adjust your camera size/field of view so that your assets' source texels map to an integer number of screen pixels. It doesn't have to be 1:1 - any whole number works great:

1:3 Scaling

You'll need to do this a bit differently depending on your target resolution - simply scaling up to fit the window will almost always result in a fractional scale. Some amount of padding at the edges of the screen may be needed for certain resolutions.
> 27 votes

# Answer
here a small checklist:

1. Seperate "current camera position" with "aim camera position". (like ndenarodev mentioned) If for example the "current camera position" is 1.1 - make the "aim camera position" 1.0

And only change the current camera position if the camera should move.
If the aim camera position is something else than transform.position - set transform.position (of your camera) to "aim camera position".

```
aim_camera_position = Mathf.Round(current_camera_position)

if (transform.position != aim_camera_position)
{
  transform.position = aim_camera_position;
}

```

this should solve your problem. If not: tell me. However you should consider doing those things too:

1. set "camera projection" to "ortographic" (for your abnormally increasing y-problem) (from now on, you should only zoom with the "Field of View")
2. set the camera rotation in 90° - steps (0° or 90° or 180°)
3. do not generate mipmaps if you dont know if you should.
4. use enough size for your sprites and dont use bilinear or trilinear filter
5.

If 1 unit is not a pixel-unit maybe its screen-resolution dependent. Do you have access to field of view? Depending on your field of view: Find out how much resolution is 1 unit.

```
float tan2Fov = tan(radians( Field of view / 2));
float xScrWidth = _CamNear*tan2Fov*_CamAspect * 2;
float xScrHeight = _CamNear*tan2Fov * 2;
float onePixel(width) = xWidth / screenResolutionX
float onePixel(height) = yHeight / screenResolutionY

```

^ And now if onePixel(width) and onePixel(height) are not 1.0000f , just move in those units to left and right with your camera.
> 1 votes

# Answer
I'm not familiar with libgdx but have experience similar problems elsewhere. I think the problem lies in the fact that you are using lerp and potentially error in floating point values. I think a possible solution to your problem is to create your own camera location object. Use this object for your movement code and update it accordingly and then set the camera's position to the nearest wanted (integer?) value of your location object.
> 0 votes

---
Tags: libgdx, pixel
---


# Question
Title: Unity2D: Don't Destroy On Load UI button Error
I have two UI buttons, an activation button, and a frost button. The activation button activates my frost button when I click on it , using `OnClick`. I have this script that saves my UI button when a new scene is loaded, however when I click on the activation button to activate my frost button it works a first time, but when I click on the button again (still running the game) I get this error:

> MissingReferenceException: The object of type 'FrostScriptButton' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. FrostScriptButton.MyOnLoad (Scene scene, LoadSceneMode sceneMode) (at Assets/Script/FrostScriptButton.cs:34) UnityEngine.SceneManagement.SceneManager.Internal\_SceneLoaded (Scene scene, LoadSceneMode mode) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/SceneManagerBindings.gen.cs:198)

And not showing the button anymore. Anyway this is my script:

```
void Awake()
{
    //We subscribe to  the event for  loading a scene
    SceneManager.sceneLoaded += MyOnLoad;
}

void MyOnLoad(Scene scene,LoadSceneMode sceneMode)
{
    //if our button does not have a parent then we will find it a Canvas.
    if (gameObject.transform.parent == null)
    {
        gameObject.transform.SetParent(
            GameObject.Find("BackGround Canvas").gameObject.transform, false);
        // You might want to use Find with tag here to make sure you will find a canvas
    }
}

// Use this for initialization

public void Activate ()
{
    frostbutton.SetActive (true);
}

public void LoadLevel()
{
    // Before we call the code for loading the level,
    //we make sure to set the button as a root object
    gameObject.transform.SetParent(null,false);
    DontDestroyOnLoad(gameObject);
    SceneManager.LoadScene(1);
}

```

Thank you. :)

# Answer
If your game is not UI intense and have couple of Canvases already with hundreds of UI objects in the scene, you can use this solution.

Keep a Canvas that holds all the buttons you don't want to destroy. Make sure it's screen space is overlaid. Give it the highest `Sort Order` value so it renders over all canvases as well as other overlaid canvases if there are some.

Now add a script which is assigned to the canvas that holding the buttons you don't want to destroy. Put `DontDestroyOnLoad(gameObject);` at `Awake()` in this script.
> 0 votes

---
Tags: unity
---


# Question
Title: MonoGame - scale down a sprite from the middle
I want to animate a texture's scale. First it's scaled up to 10, and then it gradually goes down to 1. However the texture is drawn at `Vector2(0, 0)` so it doesn't animate as I had imagined it would - it should scale down from the center of the texture. I'm sure the `origin` has something to do with it but I just can't figure out the math I need to use. So the texture is 1366x768 pixels, just as the entire screen. So here's what I tried:

```
private Texture2D texture;
private Vector2 origin;
private float scale = 10.0f;

public void Update(GameTime gameTime)
{
    scale -= 0.05f;
    if (scale <= 1.0f)
    {
        scale = 1.0f;
    }
    origin = new Vector2(texture.Width * scale / 2, texture.Height * scale / 2);
}

public void Draw(SpriteBatch spriteBatch)
{
    spriteBatch.Draw(texture, Vector2.Zero, null, Color.White, 0.0f, origin, scale, SpriteEffects.None, 1.0f);
}

```

When I debug this, I can't even see the image (the game is fullscreen). Any help is appreciated.

# Answer
Don't apply the scale to your origin calculation. Just as the texture has fixed dimensions- the center of the texture remains at the center as wel.

I wrote an extensive answer about spritebatch and the role of the origin parameter as answer to this question.
> 0 votes

---
Tags: c#, monogame, vector, scale
---


# Question
Title: How to handle keyup events in game loop?
I'm writing a simple game in JavaScript, which already handles basic keyboard input like so:

```
var input = {};
while (!done) {
    handleInput(input);
    update();
    render();
}

document.onkeydown = function(e) {
    input[e.keyCode] = true;
}
document.onkeyup = function(e) {
    input[e.keyCode] = false;
}

```

Now I need the game to handle key combos (like CTRL+X for example). I would like it to accept such combos **on `keyup` only**.

Two possible solutions that come into my mind are:

* exposing an array containing a list of `keyup` events (object with "main" key plus modifiers). The `handleInput` function would be responsible for draining the queue every time it polls it
* keeping track of possible key combos inside `handleInput` (watching for held down modifier keys) and trigger the combo behavior when the "main" key goes up (I actually don't like this that much)

Would you suggest me an elegant way to extend the current functionality?

# Answer
It sounds like you need a enum for state rather than boolean. My suggestion is something like \[NONE (or something else), PRESSED, HELD, RELEASED\]. And in the game loop create a function to switch any keys that are pressed to held and any keys that are released to none.
Also you might run into issues (especially with this implementation) where your input changes mid handleInput() and I suggest adding a queue to "lock" input to the beginning or end of the loop.
> 1 votes

---
Tags: javascript, input, game-loop, keyboard
---


title: Python collision problem

text:
# Question
Title: Python collision problem
I have a hero character with jumping physics that I am trying to figure out the collision detection for. Right now, the problem that I am running into is as soon as the character hits the floor (while I'm pressing left on the left side of the screen) the rect that it recognizes that it is colliding with is the ground. Which is to be expected.

However, based on the checks that I have,

```
for sprite in self.group.sprites():
        wall_collide = sprite.feet.collidelist(self.walls)
        if wall_collide > -1:
            print wall_collide
            if self.col_ground(sprite, wall_collide):
                self.hero.jumping = False
                sprite.move_back_y(dt)
            if self.col_left(sprite, wall_collide):
                sprite.move_back_x(dt)
            if self.col_right(sprite, wall_collide):
                sprite.move_back_x(dt)
            print ""

```

since the character is colliding with the ground, the check to see if the character's rect is inside the colliding rect fails for 2 reasons:

1: The current collision rect is the ground which the character is above, so the test fails

2: Because of #1, the character will keep moving left until it realizes it's colliding with the left side, at which point it will have already gone too far into the wall.

What's the best collision solution?

# Note: the character starts to the right of the left wall, on the ground but isn't colliding with the ground since the start position is right above it. Also, I realize that my code is a bit jumbled and I'm not taking care of every sprite in the group. I'll fix that once I have this fixed.

I can provide more code/pictures if necessary

Edit:

More code

```
def col_ground(self, sprite, wall):
    if self.walls[wall].collidepoint(sprite.feet.midbottom):
        return True
    return False

def col_left(self, sprite, wall):
    if self.walls[wall].collidepoint(sprite.feet.midleft):
        return True
    return False
def col_right(self, sprite, wall):
    if self.walls[wall].collidepoint(sprite.feet.midright):
    return True
return False

```

# Answer
> 1 votes
The collidelist() method returns an index of the first collision.

You could use the collidelistall() method which returns a list of indices that collide with the Rect. In that case, you could use the indices for your collision code instead of using 'self.col\_\*' since you already know they are colliding.

To solve your collision issue with going into the wall: in your move code, check if the next position will be inside the wall. You can do this by using the collidepoint() method. If it returns true, do not move the sprite in that direction and if returns false, you can continue moving.

EDIT: Upon seeing your collision code edit, I would recommend checking collisions with the whole sprite rather than cuts of it. Rather than

```
if self.walls[wall].collidepoint(sprite.feet.midleft):

```

you would do

```
if self.walls[wall].colliderect(sprite):

```

---
Tags: collision-detection, python, pygame
---


# Question
Title: Migrating from OpenGL to XNA (MonoGame)?
I just started working in MonoGame with 3D code. I've used OpenGL before in the past, and I've also built engines with 2D Sprites/SpriteBatch's in MonoGame.

However, I'm getting extremely stumped with going from GL to XNA, likely due to the fact that I believe XNA is no longer a "state" machine like GL is.

I've looked thru the tutorials by RB Whitaker and Riemers -- but most of the stuff they have written covers models, etc. I've already migrated some of my code to build procedural meshes into a VertexBuffer. I'd like to test it now, but I'm getting very confused as to how to setup the World, View, Projection matrices, etc.

Are there any good tutorials that either show how to move from GL to XNA -- or optionally -- any good tutorials that assume you're not using Models, etc? I'm looking to write something fairly low-level when it comes to primitives.

# Answer
> 2 votes
The three matrices are used regardless you use models or draw primitives. They have a specific purpose:

The **camera** matrix defines the point of view in the 3D world, it has a position and a target where the camera is pointed at.

The **projection** matrix defined what your screen looks like- where you want to *project* the 3D scene to. It contains the aspect ratio and dimensions of the target you want to render to. It also has a field of view (wide angle or narrow view).

The **world** matrix defines where an object is located in the 3D world. It contains rotations, translations and scale.

In the most *simple* application you define your projection matrix for your screen once per *game*. Your camera once per *frame* and world matrix per *frame and object*.

In XNA the BasicEffect has the shader basics needed to draw in 3D. As per Whitaker tutorial:

```
 BasicEffect basicEffect;
 Matrix world = Matrix.CreateTranslation(0, 0, 0);
 Matrix view = Matrix.CreateLookAt(new Vector3(0, 0, 3), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
 Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), 800f / 480f, 0.01f, 100f);

```

When you use these matrices to draw anything the object will be at the origin (world matrix sets a translation at 0,0,0) sets the camera at 0,0,3 looking at 0,0,0 where 0,1,0 defines the *up* direction. Finally the projection has a viewing angle of 45 degrees, sets the aspect ratio for a 800/480 viewport, where the minimum distance is 0.1 and the max distance to render is 100.

Use these matrices to test draw some vertices (both Riemers and Whitaker have a basic triangle as starting point).

---
Tags: opengl, xna, monogame
---


# Question
Title: Saving Unity Custom Inspector state to a text / save file?
For the basic values I know how to do it like:

* Item name (Simple string value)
* Amount (Simple int value)
* isNormalDrop (Simple bool value)

The problem is saving the Reflection variable (The script part near the bottom) which is of type 'UnityEngine.Object' and the GameObject variable how would I do this?

# Answer
I figured out how to do this its using Unity's Asset Database and saving the scripts name as well as the Gameobjects name in order to retrieve them. keep in mind that AssetDatabase is UnityEditor only so to load assets during game time you need to put them in Resources and use Resources.Load

I save the Inspectors data in a XML File on a button click and then Load the data on button click and OnEnable. Here is the doc for XML Writing and Reading

Here is my Load and Save code just so you get an Idea:

Loading Data:

```
private void LoadItems(){
    var Path = Application.persistentDataPath + "//XMLSaves/data.xml";
    XmlDocument Document = new XmlDocument();
    Document.Load(Path);

    List<string> NamesL = new List<string>();

    Names.Clear();
    Prefabs.Clear();
    Script.Clear();
    isDropNormal.Clear();

    XmlNodeList XmlItems = Document.DocumentElement.SelectNodes("//Items/Item");
    foreach (XmlNode Node in XmlItems){
        Names.Add(Node.SelectSingleNode("Name").InnerText);

        string Prefab = Node.SelectSingleNode("Prefab").InnerText;
        string[] Folders = new string[]{"Assets/Scripts/Drops/Prefabs"};
        string AssetPath = GetAssetPath(Prefab, Folders);
        GameObject Asset = (GameObject)AssetDatabase.LoadAssetAtPath(AssetPath,typeof(GameObject));
        Prefabs.Add(Asset);

        string ScriptName = Node.SelectSingleNode("Script").InnerText;
        string ScriptPath = GetAssetPath(ScriptName + " t:MonoScript");
        MonoScript MonoScriptPath = (MonoScript)AssetDatabase.LoadAssetAtPath(ScriptPath, typeof(MonoScript));
        Script.Add(MonoScriptPath);

        Methods.Add(Node.SelectSingleNode("Methods").InnerText);

        bool isDropNormalT = bool.Parse(Node.SelectSingleNode("isDropNormal").InnerText);
        isDropNormal.Add(isDropNormalT);
    }
    SizeProp = XmlItems.Count;

}

```

Saving Data:

```
private void WriteItemsToFile(){
    var Path = Application.persistentDataPath + "//XMLSaves";
    System.IO.Directory.CreateDirectory(Path);

    if (System.IO.File.Exists(Path + "//data.xml")){
        System.IO.File.Delete(Path + "//data.xml");
    }

    XmlWriterSettings settings = new XmlWriterSettings
    {
        Indent = true,
        IndentChars = "  ",
        NewLineChars = "\r\n",
        NewLineHandling = NewLineHandling.Replace
    };

    XmlWriter Writer = XmlWriter.Create(Path + "//data.xml", settings);

    Writer.WriteStartDocument();
    Writer.WriteStartElement("Items");
    for (int I = 0;I < SizeProp; I++){
        Writer.WriteStartElement("Item");
        Writer.WriteElementString("Name", Names[I]);
        Writer.WriteElementString("Prefab", Prefabs[I].name);
        Writer.WriteElementString("Script", Script[I].name);
        Writer.WriteElementString("Methods", Methods[I]);
        Writer.WriteElementString("isDropNormal", isDropNormal[I].ToString());
        Writer.WriteEndElement();
    }
    Writer.WriteEndElement();
    Writer.WriteEndDocument();

    Writer.Close();
}

```
> 1 votes

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


title: Snake game collision problem in Unity

text:
# Question
Title: Snake game collision problem in Unity
I am learning to create a snake game (from this tutorial) .

The problem is arising when the object(Snake) collides with the borders,nothing happens and it moves out of the box (white square on the left).

I have added `BoxCollider2D` components on the bounds.

For the player (Snake), I've added `BoxCollider2D` component and `Rigidbody2D`.

Here's the script attached to the snake

```
using UnityEngine;
using System.Collections;

public class Snake : MonoBehaviour {

    Vector2 dir=Vector2.left;

    // Use this for initialization
    void Start () {
        InvokeRepeating ("Move", 0.3f, 0.3f);

    }

    // Update is called once per frame
    void Update () {

    }

    void Move(){
        transform.Translate (dir);
    }
}

```

# Answer
> 1 votes
Assuming you are following the tutorial, to collision detection does not occur for the snake through Unity's normal physics engine since those options are turned off. Instead, what you do in the tutorial (and in many cases outside of it), is use the OnTriggerEnter2D function to react to the collision.

In that function, you check for collisions with the food objects and the bounding boxes. In the event you are colliding with a bounding box, you program the "lose" function in your game. An example of that would be (in pseudocode):

```
if collide with food:
    growTail();
else
    loseGame();

```

The tutorial leaves it up to the reader to create the lose game function.

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


# Question
Title: What is the best PBR real time Fresnel function?
I'm working on a physically-based renderer, and I've come to a sort of crossroads regarding the Fresnel factor. I'm having trouble finding the best way to represent it. I know that Schlick's Fresnel approximation is based off IOR, but IORs can go up to 38.6 for a meta-material, and 4.05 for a natural element, which will make representing these in a 0-1 image difficult and confusing. I also noticed that no one really uses IOR maps.

I also read a paper on Unreal's PBR integration, and I discovered that they initially wanted to use a F0 of 0.4, for non-metals. What would be the F0 for metals, in this case, and isn't the static value of 0.4 worth the limitations for that tiny bit of memory? I believe the F0 tends to the base color, as it becomes more metallic, but I'd like confirmation.

Finally, there's reflectivity or specular, as is used in modern PBR equations. Is there a standard for this, in regard to getting an F0? It seems arbitrary; is it a float value up to that directly maps to F0?

I am not sure if there are any real reasons to *not* combine specular color and base color, as Unreal has done this, before. I can't think of a single real reason, even for more stylized implementations.

What is the best PBR real time Fresnel function?

# Answer
> 0 votes
I cross-posted on gamedev.net, for anyone who is interested in an answer: http://www.gamedev.net/topic/681857-what-is-the-best-pbr-real-time-fresnel-function/.

Basically, I've received the following answers:

* IOR Is not used for F0 directly, usually, because it varies so much.
* The metalness workflow usually combine diffuse and specular into a base color. That is the main point of a metalness workflow. It limits inputs, and prevents people from going crazy with some inputs, as well as takes less resources on the G-Buffer, but also may give way to bugs, and fails to replicate some more eccentric materials.
* The specular workflow simply demands that the user makes MOST dielectrics have a black specular, and most metals have a black diffuse, except for more eccentric subtances. This is basically what metalness does.
* The metalness uses 0.4 for dielectrics (nonmetals), and base color for metals for the F0 usually.

I didn't ask this, but it's it's useful to remember glossiness=1-roughness.

So in summary, don't use IOR, Specular is a bit more complex and uses more resources, but is more accurate than metalness.

---
Tags: rendering, lighting, deferred-rendering
---


# Question
Title: Libgdx SpriteBatch won't position correctly on Screen
I have been trying to position my spritebatch correctly regardless of screen size but it simply wont scale..This is what I want to achieve on every screen size..I want my Sprite Object to be positioned at the center of the x-axis on every screen size and on the first half of the screen (above dotted line) and have it scale as well..I have also noticed that spritebatch doesn't respect my gameheight and gamewidth instead opting for screenwidth and screenheight. The dimensions for my sprite anim are 900 by 700 and I am hoping it can scale for lower resolutions

Code :

```
batch.draw(animation.getKeyFrame(elapsedTime, true), 20, app.midPointY + 350, app.screenWidth, 465);

```

# Answer
> 0 votes
The problem I see in your code is that you have hard coded values (20, 350 and 465). These values don't take into account the resolution of the screen. Then, when you have different resolutions, you'll have different results... You won't have automatic scaling with hard coded values.

To resolve your problem, you need to take into account the screen dimensions in your code, using `Gdx.graphics.getWidth()` and `Gdx.graphics.getHeight()`.

Let's say you want to position your animation on the top half of the screen, a space of 5% of the screen width on the left and on the right of your animation. Your code will become :

```
batch.draw(animation.getKeyFrame(elapsedTime, true),
           0.05f * Gdx.graphics.getWidth(),    //Leave a space of 5% of the screen width to the left of the animation
           Gdx.graphics.getHeight()/2 + (0.9f * Gdx.graphics.getWidth() * animation.getKeyFrame(elapsedTime, true).getRegionHeight() / animation.getKeyFrame(elapsedTime, true).getRegionWidth()),    //For this, see explanation below the code
           0.9f * Gdx.graphics.getWidth(),    //Since in this example I decided to leave a space of 5% the screen width on each side, the width of the animation is 90% of the screen width
           0.9f * Gdx.graphics.getWidth() * animation.getKeyFrame(elapsedTime, true).getRegionHeight() / animation.getKeyFrame(elapsedTime, true).getRegionWidth());   //With this term, I keep the original proportions of the animation. The protportion being 900/700

```

You'll notice that the 3rd term is very long, and looks scary :

```
Gdx.graphics.getHeight()/2 + (0.9f * Gdx.graphics.getWidth() * animation.getKeyFrame(elapsedTime, true).getRegionHeight() / animation.getKeyFrame(elapsedTime, true).getRegionWidth())

```

Actually this code line is there because you want to automatically scale your animation to the screen. The term `0.9f * Gdx.graphics.getWidth() * animation.getKeyFrame(elapsedTime, true).getRegionHeight() / animation.getKeyFrame(elapsedTime, true).getRegionWidth()` is only the definition of the height of your image based on the width of the image, that you can find as a last term of the `batch.draw();`

Actually, we could simplify the code by defining an `animationRatio` in the `create()` of your method. We could simply put `animationRatio = 700/900` but once again, we have hard-coded values, and if one day for any reason you change your animation, and use an animation with different size, it will mess everything up. To resolve this problem, in your `create()`, just add this line

```
animationRatio = animation.getKeyFrame(elapsedTime, true).getRegionHeight() / animation.getKeyFrame(elapsedTime, true).getRegionWidth()

```

Then your code becomes much simpler and readable :

```
batch.draw(animation.getKeyFrame(elapsedTime, true),
           0.05f * Gdx.graphics.getWidth()
           Gdx.graphics.getHeight()/2 + 0.9f * Gdx.graphics.getWidth() * animationRatio,
           0.9f * Gdx.graphics.getWidth(),
           0.9f * Gdx.graphics.getWidth() * animationRatio);

```

---
Tags: libgdx, spritebatch
---


# Question
Title: What is the lowest-level way of making graphics from scratch?
I am currently trying to get into game development and trying to understand 3D games. I would like to learn to code from scratch without any 3D engines. Some of the things I found was libraries like SDL and graphics.h in C. How does a game actually access the screen at the lowest-level? So how would one move a square rightwards on the screen on say Windows. Is the lowest level OpenGL and Direct3D or is there lower-level ways of doing it?

# Answer
The lowest-level practical way on modern computers is to use OpenGL/Vulkan/Mantle/Direct3D.

Technically you could write yourself a driver, replacing the ones supplied by your GPU manufacturer, because the above APIs ultimately talk to that driver at some point. This is exceedingly tedious and difficult and not worth the effort.

You could also find an old computer that runs and older operating system that would let you directly access attached video RAM and do everything in software. Or you could buy a Raspberry Pi or some other piece of DIY computing hardware and build the whole hardware *and* software stack yourself.

Or you could machine your own hardware components and wiring and build your own hardware stack, and then build your software stack on that...

...and so on. You can see that beyond a certain point trying to get "lower level" becomes exceedingly tedious, so stick to D3D, et cetera. D3D12 and Vulkan both provide more direct, less abstracted access to the GPU than earlier versions of D3D and than OpenGL, so you might consider those, although they are biting off quite a lot if you're a relative newbie to the field of computer graphics.

---

If your goal is to experience what graphics programming *used to be like*, though, when you did have direct access to a buffer of bytes that just represented colors... there's a couple reasonable options:

* use D3D/OpenGL to render a single full-screen quad with a texture. Then, treat the bytes of that texture like "video RAM," so you can poke and prod them however you like. You can write sprite blitters and other sorts of old-school effects this way. Barring weird hardware-specific idiosyncrasies this can give you a pretty reasonable approximation of the old "low level" approaches to graphics.
* get some old console hardware that's reasonably open to home-brew work. The GBA is an excellent candidate, as is the PSP. Both of these machines are fairly limited and still let you to direct hardware access tricks for graphics. Because of the specialized hardware involved, these techniques may be different than the ones you'd have seen in old DOS or Classic MacOS games.
* build or buy an old PC and install DOS or whatnot on it. I mentioned this in the first section as a bit of a joke, but out of all those "unrealistic" options (like writing your own driver), this is actually reasonably practical to do, assuming you can tolerate working on such an old machine.
> 6 votes

# Answer
I am not a game developer, but I recently came across an old file from 10 years ago which was part of my undergrad Computer Science course. Since you mentioned Windows and accessing the screen at a low level, I am going to leave you with the minimal code of what I believe would work for your "moving a square to the right" example.

I am assuming you are going to use an old computer with Windows XP (or even an older one, it should include an MS-DOS terminal, I don't know anything about Windows after XP). I am assuming this old computer can run the old 'Mode 19' (or Mode13H, look it up on Wikipedia). According to wikipedia,

> Mode 13h is an IBM VGA BIOS mode. It is the specific standard 256-color mode on IBM's VGA graphics hardware. It features a resolution of 320×200 pixels. It was used extensively in computer games and art/animation software of the late 1980s and early to mid-1990s

Indeed, in this minimal example I used the default VGA standard palette of 8-bit colors.

I am also assuming the special address **0xA0000000** and that you understand that if you modify beyond the 320x200=64000 positions you might corrupt your system. So either make sure this address is correct and that you don't modify beyond this limit, or that you are using an old computer that you don't mind \[potentially\] screwing up.

One final note: I did not try this minimal example. I just copied/modified the essential parts from my own project. I might have missed something or it may contain typos.

Another final note: I recently modified this 10-year old project to work with SDL instead of modifying the special memory address. I then used an Xcode-ios template from SDL and I successfully compiled it and installed it on my own Iphone. I am happy on the outcome and how easy it was to give this old project a new life.

```
#include <dos.h> // For windows, I guess
#include <conio.h> //MS-DOS console i/o

typedef unsigned short int byte; //Definition of an unsigned short int type

//Let's say this is your 'square', it actually looks like a bomb, I took it from my own class project.
byte bomba[7][5]=
{
   {48,48,40,48,48},
   {48,40,40,40,48},
   {40,40,44,40,40},
   {40,44,44,44,40},
   {40,44,42,44,40},
   {40,44,44,44,40},
   {40,40,40,40,40}
};

byte backup[35]; //This will be used as a 'backup' of what is behind the bomb in the background (should you use one), so that when you move the sprite we can redraw these pixels to the screen.

void modovideo(byte type) //this function will take you to mode 19 (or other modes if you wish to)
{
  REGS m,f;
  m.h.ah=0;
  m.h.al=type;
  int86(0x10,&m,&f);
}

void getbackup(int bx, int by)   //this function will save the background to memory before we draw the bomb at position bx, by
{
 char far *p=(char far *)0xA0000000+bx+(320*by);

    for(int i=0;i<35;i++,p++)
        {
          if(i%5==0 && i!=0)  //New line
              p+=(320-5);

            backup[i]=*p;
        }
}

void draw(int bx, int by,byte r)   //This function will render the sprite on screen at position (bx,by), or will draw the 'backup', depending on the value of 'r'
{
    //Pointer to 0xA0000000 + the corresponding pixel position in a vectorized form (320 is the screen width)
    char far *p=(char far *)0xA0000000+bx+(320*by);
byte m[5];
//7 and 5 are the dimensions of the sprite
for(int i=0;i<7;i++,p+=(320-5))
  {
        if(r==0) //Draws bomb
           { for(int a=0;a<5;a++,p++)
              {
        //I am using 48 as a background for the sprite (48 is a greenish color, I guess I used it so that it could literally be a 'green screen')
                if(bomba[i][a]!=48)
                  *p=bomba[i][a];   //Assigns the value of the pixel to the correct memory address
              }
            }
        else
         {
          for(int j=0;j<5;j++)
                m[j]=backup[j+(i*5)];

            for(int b=0;b<5;b++,p++)
                if(m[b]!=48)
                  *p=m[b];  //Draws the backup pixel

         }
   }
}

//Main function
void main()
{

    modovideo(19); //Starts mode 19

    int posx=50, posy=50; //Initial position of your square
    int dx=1, dy=0; //Constant velocity for your square
    int count=0; //Count for main loop in this minimal example

    getbackup(posx,posy); //Gets a backup of the background

    //Main time loop
    do
    {
    delay(30); //Delay in milliseconds, up to you

    draw(posx, posy, 1); //Draws the sprite backup at previous location

    posx+=dx; //sprite moves
    posy+=dy;

    getbackup(posx,posy); //Gets new backup (at new location)
    draw(posx,posy, 0); //Draws sprite at new location

    count++;
    }while(count<50); //We will move it 50 times in this minimal example.
}

```
> 1 votes

# Answer
The answer depends largely on what you want to accomplish.

OpenGL has a lot of advantages, mainly that it's supported to at least some level on virtually any graphics card today without any additional libraries strictly required.

It's also pretty easy to get the basics going, but in spite of what many would say it's actually fairly high level in many respects. A huge amount is just done for you more or less like magic. I don't think a lot of developers using it even realize this is the case. Things like rasterizing, anti-aliasing, generating mip-maps, the list goes on and on.

So if you are doing this as a learning exercise and really want to go to a lower level then consider looking at creating a basic software renderer. You will still probably have to use OpenGL or DirectX but you would be using it simply to put your already created images onto the graphics card.

The flipcode archives talk about this quite a bit and are a good place to start learning the basics of how graphics work. Otherwise you will probably wind up taking a sort of magic carpet ride where you can get things going but become mystified when it comes to making truly new stuff or understanding performance issues properly.

http://flipcode.com/archives/articles.shtml
> 1 votes

---
Tags: opengl, c++, graphics-programming, c
---


title: How to play sound effects on iOS?

text:
# Question
Title: How to play sound effects on iOS?
I have a game that plays sounds when some events occur.

Currently, I am using `AVAudioPlayer` for the purpose of playing the sound. But just the bare `AVAudioPlayer` has a noticeable lag time before the first playback and it stops music played by other apps.

Also, it stops the ongoing playback when a new playback is ordered. Surely, I could use a list of `AVAudioPlayer`s for each of the effects, but that feels clunky.

I want something that will play effects mixed, one on top of another; and I want them to be played on top of background music, if there is any. I do not use any sorts of frameworks, like `SpriteKit` or Unity. So, how do I do this?

# Answer
> 1 votes
Settled to a queue of AVAudioPlayers for each sound effect.

Not pausing music achieved with this: https://stackoverflow.com/a/29027722

# Answer
> 1 votes
You have to change your `AVAudioSession` to `Category` rather than the default (`Solo`).

`[[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryAmbient error:nil];` should do the trick.

If this doesn't work for you, the AVAudioSession documentation has a lot of information on Audio Session Categories, Modes, etc.

---
Tags: ios, objective-c
---


# Question
Title: Calculating the weights of matrices/bones in opengl/glsl
I have a basic shape that I want to render. Nothing too complex, just a tall cube. And I want to attach 2 bones to it. Not only that, but I also want one of the bones/matrices to influence the cube more than the other bone, say 60-40 ratio. Can someone show or explain how to do this? I've been trying to find an explanation for this the past few days without luck. How to calculate the weight of a bone/matrix and how (much) effect it will have on the vertex transformation.

Im just using basic c++/opengl for this, looking for an explanation about how weights are calculated in, especially if there are multiple bones.

# Answer
> 5 votes
You need to add together all the end results of each weighted bone for the vertex. The weights should add up to 1 in total for the weights to be correct. So basically:

```
float weight1 = 60.0f;
float weight2 = 40.0f;
float totalWeights = weight1 + weight2;
// Make them be from 0 to 1, and 1 in total.
weight1 = weight1 / totalWeights;
weight2 = weight2 / totalWeights;

```

And then in the shader:

```
vec4 vPos = bone1matrix * vertex * weight1 + bone2matrix * vertex * weight2;

```

The same applies for normals and other vertex data you want to animate with the bones.

A better example copy pasted from the OpenGL Wiki:

```
//[Vertex Shader]
attribute vec4 Vertex;
attribute vec3 Normal;
attribute vec2 TexCoord;
attribute vec2 Index;
attribute vec2 Weight;
uniform mat4 ModelviewMatrix;
uniform mat4 ProjectionModelviewMatrix;
uniform mat4 Bone[10];  //Array of bones that you compute (animate) on the CPU and you upload to the shader
//-----------------------
varying vec2 TexCoord0;
varying vec3 EyeNormal;
//-----------------------
void main()
{
  vec4 newVertex;
  vec4 newNormal;
  int index;
  //-----------------------
  index=int(Index.x);    //Cast to int
  newVertex = (Bone[index] * Vertex) * Weight.x;
  newNormal = (Bone[index] * vec4(Normal, 0.0)) * Weight.x;
  index=int(Index.y);    //Cast to int
  newVertex = (Bone[index] * Vertex) * Weight.y + newVertex;
  newNormal = (Bone[index] * vec4(Normal, 0.0)) * Weight.y + newNormal;
  EyeNormal = vec3(ModelviewMatrix * newNormal);
  gl_Position = ProjectionModelviewMatrix * newVertex;
  TexCoord0 = TexCoord;
}

```

---
Tags: opengl, glsl
---


# Question
Title: Drawcall Batching with Ambient Occlusion
I'm creating a low poly 4X game that will likely have upwards of 200 unique hex tile models once everything is said and done. The colour palette consists of 16 different colours. I understand that if I want to reduce the number of draw calls I could simply UV map each individual model to the palette and there wouldn't be a problem.

However, I want to add an ambient occlusion effect which is best achieved by baking it on in Blender. This precludes me from using a single material for all my models since each model will have a different pattern baked onto the palette. I'm going to go out on a limb and say that having a different material for each model could create a pretty severe CPU bottleneck.

So, what would my best solution be? Should I abandon AO altogether? Perhaps I should try lightmapping in Unity (though I've heard AO baking in modelling software yields better effects)?

Any help is appreciated!

# Answer
Use Unity's AO when baking. Should be working fine in general.

If it's a high end game then you may also use SSAO which is runtime. There is a cheap SSAO Pro package in Unity Asset Store too.
> 0 votes

---
Tags: unity, ambient-occlusion
---


# Question
Title: To Unity Rigidbody move like Character Controller on collision
I want to a blue ball moving like a figure.

in CharacterController, it was possible.

but in Rigidbody, object was stucked.

help me.

# Answer
a best way is using low-friction physics material.
> 1 votes

# Answer
this is c# code for creating an old school style fps character. First using the ball, attach this script to it.

```
using UnityEngine;
using System.Collections;

[RequireComponent (typeof (Rigidbody))]
[RequireComponent (typeof (CapsuleCollider))]

public class CharacterControls : MonoBehaviour {

    public float speed = 10.0f;
    public float gravity = 10.0f;
    public float maxVelocityChange = 10.0f;
    public bool canJump = true;
    public float jumpHeight = 2.0f;
    private bool grounded = false;

    void Awake () {
        rigidbody.freezeRotation = true;
        rigidbody.useGravity = false;
    }

    void FixedUpdate () {
        if (grounded) {
            // Calculate how fast we should be moving
            Vector3 targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            targetVelocity = transform.TransformDirection(targetVelocity);
            targetVelocity *= speed;

            // Apply a force that attempts to reach our target velocity
            Vector3 velocity = rigidbody.velocity;
            Vector3 velocityChange = (targetVelocity - velocity);
            velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
            velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
            velocityChange.y = 0;
            rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);

            // Jump
            if (canJump && Input.GetButton("Jump")) {
                rigidbody.velocity = new Vector3(velocity.x, CalculateJumpVerticalSpeed(), velocity.z);
            }
        }

        // We apply gravity manually for more tuning control
        rigidbody.AddForce(new Vector3 (0, -gravity * rigidbody.mass, 0));

        grounded = false;
    }

    void OnCollisionStay () {
        grounded = true;
    }

    float CalculateJumpVerticalSpeed () {
        // From the jump height and gravity we deduce the upwards speed
        // for the character to reach at the apex.
        return Mathf.Sqrt(2 * jumpHeight * gravity);
    }
}

```

Then, create a camera that is a child of the ball object, and attach this code to the ball's camera.

```
using UnityEngine;

// Very simple smooth mouselook modifier for the MainCamera in Unity

[AddComponentMenu("Camera/Simple Smooth Mouse Look ")]
public class SimpleSmoothMouseLook : MonoBehaviour
{
    Vector2 _mouseAbsolute;
    Vector2 _smoothMouse;

    public Vector2 clampInDegrees = new Vector2(360, 180);
    public bool lockCursor;
    public Vector2 sensitivity = new Vector2(2, 2);
    public Vector2 smoothing = new Vector2(3, 3);
    public Vector2 targetDirection;
    public Vector2 targetCharacterDirection;

    // Assign this if there's a parent object controlling motion, such as a Character Controller.
    // Yaw rotation will affect this object instead of the camera if set.
    public GameObject characterBody;

    void Start()
    {
        // Set target direction to the camera's initial orientation.
        targetDirection = transform.localRotation.eulerAngles;

        // Set target direction for the character body to its inital state.
        if (characterBody) targetCharacterDirection = characterBody.transform.localRotation.eulerAngles;
    }

    void Update()
    {
        // Ensure the cursor is always locked when set
        Screen.lockCursor = lockCursor;

        // Allow the script to clamp based on a desired target value.
        var targetOrientation = Quaternion.Euler(targetDirection);
        var targetCharacterOrientation = Quaternion.Euler(targetCharacterDirection);

        // Get raw mouse input for a cleaner reading on more sensitive mice.
        var mouseDelta = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));

        // Scale input against the sensitivity setting and multiply that against the smoothing value.
        mouseDelta = Vector2.Scale(mouseDelta, new Vector2(sensitivity.x * smoothing.x, sensitivity.y * smoothing.y));

        // Interpolate mouse movement over time to apply smoothing delta.
        _smoothMouse.x = Mathf.Lerp(_smoothMouse.x, mouseDelta.x, 1f / smoothing.x);
        _smoothMouse.y = Mathf.Lerp(_smoothMouse.y, mouseDelta.y, 1f / smoothing.y);

        // Find the absolute mouse movement value from point zero.
        _mouseAbsolute += _smoothMouse;

        // Clamp and apply the local x value first, so as not to be affected by world transforms.
        if (clampInDegrees.x < 360)
            _mouseAbsolute.x = Mathf.Clamp(_mouseAbsolute.x, -clampInDegrees.x * 0.5f, clampInDegrees.x * 0.5f);

        var xRotation = Quaternion.AngleAxis(-_mouseAbsolute.y, targetOrientation * Vector3.right);
        transform.localRotation = xRotation;

        // Then clamp and apply the global y value.
        if (clampInDegrees.y < 360)
            _mouseAbsolute.y = Mathf.Clamp(_mouseAbsolute.y, -clampInDegrees.y * 0.5f, clampInDegrees.y * 0.5f);

        transform.localRotation *= targetOrientation;

        // If there's a character body that acts as a parent to the camera
        if (characterBody)
        {
            var yRotation = Quaternion.AngleAxis(_mouseAbsolute.x, characterBody.transform.up);
            characterBody.transform.localRotation = yRotation;
            characterBody.transform.localRotation *= targetCharacterOrientation;
        }
        else
        {
            var yRotation = Quaternion.AngleAxis(_mouseAbsolute.x, transform.InverseTransformDirection(Vector3.up));
            transform.localRotation *= yRotation;
        }
    }

```

This is a very basic first person controller, and is built what the old unity controller was like. i would advise you modify this and build from it.

Hope this helps.
> 0 votes

---
Tags: unity, collision-detection, rigidbody
---


# Question
Title: lightmap equivalent with realtime shadow
i'm using in Unity free edition.

I try to bake a lightmap which equivalent feeling with Unity's real time light map and shadowing, like left figure.

But the result is the right figure.

How can i set a paremters of lighting window to get result like left figure?

--added--

here's all of screenshots.

# Answer
> 0 votes
i found a solution. a problem was ambient occlusion

---
Tags: unity, lightmap
---


title: UDP+RUDP or UDP+TCP?

text:
# Question
Title: UDP+RUDP or UDP+TCP?
I made a library that enables client-server communication using both TCP and UDP protocols. When game developers on the #gamedev IRC channel (Freenode) knew that, they totally refused the idea. They recommended RUDP instead of TCP. Should I remove the TCP communication and use RUDP instead?

# Answer
RUDP is a very exotic non-standard transport-layer protocol which is not supported on any mainstream networking hardware or operating system.

However, there are libraries which implement protocols on top of UDP which have additional TCP-like reliability features but still fulfill the requirements of real-time games. One such library is ENet. The Unity engine also does something similar when requested.

But TCP should not be totally dismissed for game development. Sure, it is unsuitable for real-time games where latency matters, but it is still a very useful protocol for turn-based games.
> 1 votes

---
Tags: networking, protocol
---


# Question
Title: How to organize a fallback system for older GPUs in OpenGL?
I don't want to make this question too broad or opinion based, but I really need some help about good practices.

The scenario:

I created a particle engine with functions which require at least OpenGL 4.3. But some GPUs don't support this version, so I want to try to implement a fallback system for it.

But it's not only the particle system. There are many features in 3D engines that can't be simply replaced by a different function name. Some features need different logic behind them and it can go quite complex.

What are the best practices to manage fallback rendering in OpenGL?

# Answer
> 2 votes
A valid option is: Don't do a fallback.

If you look at the system requirements for released games, even indie games, you'll see that they invariably set a minimum and don't support anything below that. These games don't have fallbacks.

Wanting to run on all hardware is an unrealistic objective. It's a truth that you're going to come across hardware that just won't run your game, and implementing fallbacks involves more than just features. Does the older GPU have enough video memory for your textures? If not you'll need to provide lower res alternate texture sets. Is it fast enough to process your geometry? If not you'll need to provide lower detail meshes. Can it handle your lighting, your shading, the number of blend passes you do, your post processing? Any of these can choke an older GPU even if you limit yourself to GL 2.1 features.

That's why coding fallbacks for older or weaker hardware might not actually be what you want. You could easily risk doubling your development time and creating complex, fragile code, and for what? An extra few percent can run your game. Only you can decide if that's a tradeoff you want; I suggest it may not be.

# Answer
> 1 votes
In essence, your fallback system is very easy to do because you are the one creating every single shader and feeding it to the card.

When you initialize OpenGL in SDL for example, you have to pass in the version in major and minor form. If you don't get an error, it worked. If if fails, try again with the next lowest supported version. Save this information on startup you will need it later.

Then when you create the shaders to send to the card, generate the proper shader programs based on these versions. How you do that exactly is up to you. You can have different methods for each version, or else have separate shader files, or else have a section of the shader that gets a different section based on how different it is. It all depends on the situation.

If you would generate compute shaders in 4.3 for one method and not the other, then this should still apply fine. Just alter your program shader object that contains your shader info to also hold compute shaders...and don't use a compute shader for the lower versions.

You don't need a fancy 'shader manager' or anything like that. You should be able to have the shader program object be more or less self contained.

---
Tags: opengl, c++, compatibility
---


# Question
Title: Converting real-life perspective photos into orthographic view for texture creation
I'm struggling to find software that will enable me to take real life photos and make them "flat" (orthographic) for use in textures.

Does anyone know of a reliable way to take perspective photos and make them orthographic? The simpler it is the better. I've tried using Photoshop's adaptive wide angle filter with no luck. Here is an example photo. The perspective is obvious, because the straight lines (in real life) are not straight (in the photo)

# Answer
GIMP has a "Lens Distortion" filter under Filters / Distorts.

But clearly that is not the preferred option as it leads to data loss. There are cameras (cheap ones too) with lenses that don't produce such strong distortion.
> 3 votes

---
Tags: textures, perspective
---


# Question
Title: Unity 5 - Accurate logic for 2D projectile deflection
I'm looking for ideas on how to simulate accurate (as possible) deflection for a projectile moving with a certain velocity in a tile-based 2D game.

The player is able to shoot a projectile to any direction. Right now, I'm casting a ray from the top, bottom, left and right sides of the BoxCollider2D of the projectile and - for example, if the top ray hits a wall - I use Vector2.Reflect to set the new velocity for the projectile (see the upper part of the image).

The problem I'm trying to solve (see the bottom part of the image) happens when the projectile approaches the corner of a BoxCollider2D. That particular situation causes unwanted behavior and I'm thinking of adding 4 additional raycasts (top-left, top-right etc.) for the projectile to check the diagonal collisions (trying it soon).

I'm fairly new to dealing with 2D collision - so I'm interested in hearing about your solutions or ideas, especially if you have dealt with 2D collision / deflection before. Any alternative or more simple solutions are welcome! Maybe this can be done much easier with CircleColliders?

# Answer
> 1 votes
Use `CircleCollider2D` in circular object and `BoxCollider2D` in rectangular objects.

Use a `Physics2D Material` in both colliders. Set `Friction = 0` and `Bounce = 1`.

Use force to shoot the projectile. Use `Impulse`as `ForceMode2D`.

If the circular object is using gravity then it will lose it's exact path after deflection but depends on amount of force applied.

If the circular object is not using gravity then intended path won't change. But this isn't defined as projectile.

In both case you are getting precise angle after deflection cause of zero friction and full bouncy physics material. But the path depends on gravity.

---
Tags: unity, 2d, collision-detection
---