# Question
Title: How to use Steamworks API before our game is on Steam?
I'm part of a small team working on a game that we plan on distributing through Steam and integrating features which will utilize Steamworks API. We're not sure what the process is at the moment for how we can utilize Steamworks API without our game already being on Steam. Does anyone know where we need to start? I would imagine we will need an `appid` to be able to access Steamworks.

Is there a way that we can setup the game on Steam but not have it released until it's complete?

# Answer
Yes, go through Steam Direct. Get your app set up there, but don't make it public.

https://partner.steamgames.com/steamdirect
> 8 votes

---
Tags: steam
---


# Question
Title: How can I use gui buttons and canvas with 3 different gameobjects when I click on button it will make something else for each gameobject?
Maybe using somehow with IPointer\[...\]Handler interfaces ? Not sure. I have 3 GUI buttons and 3 GameObjects I want to interact with the buttons. The 3 GameObjects are: Robot Kyle , hero , AircraftJet

I have also a canvas and under it as children 3 buttons: Mouse Over , User Call , Allways On

In the Allways On button in the Inspector in the On Click I'm calling a method AllwaysOn and in the Mouse Over button I'm calling a method OnMouseOverMethod

And a script that is attached to the 3 GameObjects:

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

public class OutlinedObject : MonoBehaviour
{
    public Color outlineColor = Color.red;

    //public enum OutlineMode { MouseOver, UserCall, AllwaysOn }
    //public OutlineMode outlineMode = OutlineMode.MouseOver;
    public bool flashing = false;
    [Range(0.5f, 5)]
    public float flashSpeed = 1.5f;
    public float threshold = 1.0f;

    float timeBlink, deltaRate;

    Texture2D maskTexture, maskNone;
    private List<Material> materials = new List<Material>();

    bool ApplyEffect = true;
    bool currentMode = false;
    bool blinkMode = false;

    float andThr;
    Color outAnt;

    private bool mouseOver = false;

    void Awake()
    {

        materials.Clear();
        maskTexture = new Texture2D(2, 2, TextureFormat.ARGB32, false);
        outlineColor.a = 1.0f;
        maskTexture.SetPixel(0, 0, outlineColor);
        maskTexture.SetPixel(1, 0, outlineColor);
        maskTexture.SetPixel(0, 1, outlineColor);
        maskTexture.SetPixel(1, 1, outlineColor);
        maskTexture.Apply();

        foreach (Renderer rend in GetComponentsInChildren<Renderer>())
            materials.Add(rend.material);

        andThr = threshold;
        outAnt = outlineColor;

        maskNone = new Texture2D(2, 2, TextureFormat.ARGB32, false);
        maskNone.SetPixel(0, 0, new Color(0, 0, 0, 0));
        maskNone.SetPixel(1, 0, new Color(0, 0, 0, 0));
        maskNone.SetPixel(0, 1, new Color(0, 0, 0, 0));
        maskNone.SetPixel(1, 1, new Color(0, 0, 0, 0));
        maskNone.Apply();

        AllwaysOn();
        /*if (outlineMode == OutlineMode.AllwaysOn)
            ApplyEffect = true;
        else
            ApplyEffect = false;*/

    }

    void OnEnable()
    {
        if (ApplyEffect)
        {
            foreach (Material material in materials)
                material.SetTexture("_SpriteMask", maskTexture);
        }
        else
        {
            foreach (Material material in materials)
                material.SetTexture("_SpriteMask", maskNone);
        }
        foreach (Material material in materials)
            material.SetFloat("_Threshold", threshold);
    }

    public void OnMouseEnter()
    {
        if (mouseOver == true)
            ApplyEffect = true;

        //if (outlineMode == OutlineMode.MouseOver)
        //  ApplyEffect = true;
    }

    public void UserCall(bool isOn)
    {
        ApplyEffect = isOn;
    }

    public void OnMouseExit()
    {
        if (mouseOver == true)
            ApplyEffect = false;

        //if (outlineMode == OutlineMode.MouseOver)
        //  ApplyEffect = false;
    }

    void LightOn()
    {
        if (currentMode)
            return;
        currentMode = true;
        foreach (Material material in materials)
            material.SetTexture("_SpriteMask", maskTexture);
    }

    void LightOff()
    {
        if (!currentMode)
            return;
        currentMode = false;
        foreach (Material material in materials)
            material.SetTexture("_SpriteMask", maskNone);
    }

    void Update()
    {
        if (flashing && ApplyEffect)
        {
            deltaRate = 1f / (2f * flashSpeed);

            if (Time.time - timeBlink > deltaRate)
            {
                timeBlink = Time.time;
                blinkMode = !blinkMode;
                if (!blinkMode)
                    LightOff();
                else
                    LightOn();
            }
        }
        else
        {
            if (ApplyEffect)
                LightOn();
            else
                LightOff();
        }

        if (andThr != threshold)
        {
            andThr = threshold;
            foreach (Material material in materials)
                material.SetFloat("_Threshold", threshold);
        }

        if (!outAnt.Equals(outlineColor))
        {
            outlineColor.a = 1.0f;
            outAnt = outlineColor;
            maskTexture.SetPixel(0, 0, outlineColor);
            maskTexture.SetPixel(1, 0, outlineColor);
            maskTexture.SetPixel(0, 1, outlineColor);
            maskTexture.SetPixel(1, 1, outlineColor);
            maskTexture.Apply();
            foreach (Material material in materials)
                material.SetTexture("_SpriteMask", maskTexture);
        }
    }

    void OnDisable()
    {
        foreach (Material material in materials)
            material.SetTexture("_SpriteMask", null);
    }

    public void AllwaysOn()
    {
        mouseOver = false;
        ApplyEffect = !ApplyEffect;
    }

    public void OnMouseOverMethod()
    {
        mouseOver = true;
        ApplyEffect = false;
    }
}

```

On the script bottom there is the two methods I'm using in the buttons On Click events.

In this case I dragged over to the On Click in both buttons Allways On and Mouse Over the AircraftJet

Now when I'm clicking the buttons it's applying it only for the AircraftJet. And I want now to make that each GameObject for example the AircraftJet will have it's own buttons events something like enum.

In the script I used enum before but now I want to use canvas and gui buttons. The problem is that there is no gui enum.

In general what I want to do is somehow that I will be able to click on something and select for example the AircraftJet gameobject and then when clicking the buttons it will effect only the aircraft and if i will click on the hero and then the buttons it will effect only the hero. Something like enum idea.

# Answer
Your button code should not be storing the states for your objects. Your objects should be storing the states for your objects (all the button code is get the currently selected object, get the data script, and modify the data).

So the script you have shown should be attached to the camera (or some other neutral object) that knows one thing:

* what object is selected

Then your update function does 1 thing:

* determine if a different object should be selected

Your AlwaysOn / MouseOver / Use Call buttons do one thing:

* take the selected object, call `GetComponent<>()` (for a custom script), and modify the value contained within that script
> 1 votes

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


# Question
Title: What are the meanings of theta and gamma in this equation?
I'm having a bit of trouble understanding the notation from this paper: http://graphics.cs.aueb.gr/graphics/docs/papers/GraphiCon09\_PapadopoulosPapaioannou.pdf

```
float3 surface = exp(dot(-y, d)) * fromSurface;
float3 viewer = exp(dot(-y, d)) * fromViewer;
float3 final = dot(photonIntensity, dot(mie(0), dot(viewer, surface));

```

I know I = intensity, mie is mie scattering, but what does the wierd 0 stand for? And what is y? Is d = distance?

Second go at it:

```
float Attenuation = 130.0;
float MieAnisotropy = 0.7;

float MiePhase(float CosTheta, float Anisotropy)
{
    const float F = 1.0 / (4.0 * PI);
    return F * ((1.0 - pow(Anisotropy, 2.0)) / pow(1.0 - 2.0 * Anisotropy * CosTheta + pow(Anisotropy, 2.0), 1.5));
}

float3 ViewPosition = normalize(WorldPosition - CameraPosition);
float CosViewSunAngle = dot(ViewPosition, SunDirection);
float Mie = MiePhase(CosViewSunAngle, MieAnisotropy);

float FromSurface = exp(dot(-Attenuation, DistanceFromSurface));
float FromViewer = exp(dot(-Attenuation, DistanceFromViewer));
float PhotonIntensity = 1.0;
float Final = dot(PhotonIntensity, dot(Mie, dot(FromViewer, FromSurface));

```

# Answer
Immediately after the first appearance of the equation in the paper, the use of \\$\theta\\$ is described as

> being the angle between the ray direction and the vector from the viewer to the fragment

The use of \\$\gamma\\$ is first described just above; it

> is the medium attenuation parameter

"Medium" in this sense means the substance through which the photon is traveling (not "medium" as in "low, medium, high"), so this is basically a constant for tweaking. Later in the paper, an example value for \\$\gamma\\$ is given (in the "Implementation Details" section).

And yes, \\$d\\$ is distance from the respective points.
> 6 votes

---
Tags: mathematics
---


# Question
Title: Why does my triangle rasterization miss some pixels along one edge?
I am having an issue rasterizing a triangle. The goal is to calculate barycentric coordinates and make the triangle based off those coordinates. I am having an issue with having weird jaggy missing pixels on one of my edges. The code is pretty messy currently but here is what I've got:

```
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
#include "Image.h"

// This allows you to skip the `std::` in front of C++ standard library
// functions. You can also say `using std::cout` to be more selective.
// You should never do this in a header file.
using namespace std;

struct boundingBox{
    int xmin;
    int xmax;
    int ymin;
    int ymax;
} box;

struct Triangle{
    int xCoordA;
    int yCoordA;
    int xCoordB;
    int yCoordB;
    int xCoordC;
    int yCoordC;
} t;

struct Point{
    float x;
    float y;
} P;

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

    if(argc < 19 || argc > 19) {
        cout << "Usage: L02 filename width height Vertex1-x Vertex1-y Vertex1-Red Vertex-1-Green Vertex-1-Blue Vertex2-x Vertex2-y Vertex-2-Red Vertex-2-Green Vertex2-2-Blue Vertex3-x Vertex3-y Vertex-3-Red Vertex-3-Green Vertex-3-Blue" << endl;
        return 0;
    }
    // Output filename
    string filename(argv[1]);
    // Width of image
    int width = atoi(argv[2]);
    // Height of image
    int height = atoi(argv[3]);
    // Coordinates of vertex 1
    t.xCoordA = atoi(argv[4]);
    t.yCoordA = atoi(argv[5]);
    //color of vertex 1
    int red1 = atoi(argv[6]);
    int green1 = atoi(argv[7]);
    int blue1 = atoi(argv[8]);
    //coordinates of vertex 2
    t.xCoordB = atoi(argv[9]);
    t.yCoordB = atoi(argv[10]);
    //color of vertex 2
    int red2 = atoi(argv[11]);
    int green2 = atoi(argv[12]);
    int blue2 = atoi(argv[13]);
    //coordinates of vertex 3
    t.xCoordC = atoi(argv[14]);
    t.yCoordC = atoi(argv[15]);
    //color of vertex 3
    int red3 = atoi(argv[16]);
    int green3 = atoi(argv[17]);
    int blue3 = atoi(argv[18]);

    // Find bounding box values
    int xMaxTemp = max((t.xCoordA), (t.xCoordB));
    box.xmax = max(xMaxTemp, (t.xCoordC));
    int yMaxTemp = max((t.yCoordA), (t.yCoordB));
    box.ymax = max(yMaxTemp, (t.yCoordC));
    int xMinTemp = min((t.xCoordA), (t.xCoordB));
    box.xmin = min(xMinTemp, (t.xCoordC));
    int yMinTemp = min((t.yCoordA), (t.yCoordB));
    box.ymin = min(yMinTemp, (t.yCoordC));
    // Create the image. We're using a `shared_ptr`, a C++11 feature.
    auto image = make_shared<Image>(width, height);

    for (int i = box.xmin; i <= box.xmax; i++)
    {
        for (int j = box.ymin; j <= box.ymax; j++)
        {
            P.x = static_cast<float>(i);
            P.y = static_cast<float>(j);
            float denAlpha = ((t.yCoordB - t.yCoordC) * t.xCoordA + (t.xCoordC - t.xCoordB) * t.yCoordA + (t.xCoordB * t.yCoordC) - (t.xCoordC * t.yCoordB));
            float denBeta = ((t.yCoordC - t.yCoordA) * t.xCoordB + (t.xCoordA - t.xCoordC) * t.yCoordB + (t.xCoordC * t.yCoordA) - (t.xCoordA * t.yCoordC));
            float numAlpha = ((t.yCoordB - t.yCoordC) * P.x + (t.xCoordC - t.xCoordB) * P.y + (t.xCoordB * t.yCoordC) - (t.xCoordC * t.yCoordB));
            float numBeta = ((t.yCoordC - t.yCoordA) * P.x + (t.xCoordA - t.xCoordC) * P.y + (t.xCoordC * t.yCoordA) - (t.xCoordA * t.yCoordC));
            float alpha =  numAlpha / denAlpha;
            float beta = numBeta / denBeta;
            float gamma = 1.0 - alpha - beta;

            if (alpha >= 0.0 && beta >= 0.0 && gamma >= 0.0)
            {
                //Then we are in triangle
                int myRed = (red1 * alpha) + (red2 * beta) + (red3 * gamma);
                int myGreen = (green1 * alpha) + (green2 * beta) + (green3 * gamma);
                int myBlue = (blue1 * alpha) + (blue2 * beta) + (blue3 * gamma);
                image->setPixel(P.x, P.y, myRed, myGreen, myBlue);
            }
            else{
                //we are not in triangle
                image->setPixel(P.x, P.y,  0, 0, 0);
            }
        }
    }
    image->writeToFile(filename);
    return 0;
}

```

I should only need to check if the coordinates are \>= 0 since I am using the bounding box to check the other side.

For some reason when I run it this is what the triangle looks like

The hypotenuse has weird jaggy/ missing pixel edges.

I have been working with my instructor for 2 whole lab sessions now, and changing the way I calculate the bary-coordinates hasn't solved anything.

# Answer
Turns out I needed to fully calculate the Gamma, instead of doing that shortcut.

That solved the issue!
> 2 votes

---
Tags: c++, rasterization, barycentric-coordinates
---


# Question
Title: How to move a player along Waypoints with Rigidbody.MovePosition in Unity?
I have a player with a Rigidbody, I want it to follow along the Waypoints. I have used MoveTowards but it seems also not to work however. I want to use MovePosition to add force while grinding. I commented a code that could maybe work but I got an error on that, check //ADDFORCE lines.

Here is my code:

---

```
public GameObject[] waypoints;

public float grindSpeed;
public float turnSpeed;

public int currentWaypoint;

private Animator anim;
private Rigidbody rb;

public bool isGrinding = false;

void Start()
{
    anim = GetComponent<Animator>();
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    MoveAlongWaypoints();

    if(isGrinding)
        anim.SetBool ("isOnGrinding", true);
    else if(!isGrinding)
        anim.SetBool("isOnGrinding", false);
}

void MoveAlongWaypoints()
{
    if(isGrinding)
    {
        //TRANSLATE
        transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypoint].transform.position, grindSpeed * Time.deltaTime);
        //ADDFORCE
        /*
        Vector3 movePosition = transform.position;
        movePosition = Mathf.MoveTowards(transform.position, waypoints[currentWaypoint].transform.position * grindSpeed * Time.deltaTime);
        rb.MovePosition(movePosition);
        */
        //ROTATE
        var rotation = Quaternion.LookRotation(waypoints[currentWaypoint].transform.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, turnSpeed * Time.deltaTime);

        if(Mathf.Abs(transform.position.x - waypoints[currentWaypoint].transform.position.x) < 1
            && (Mathf.Abs (transform.position.y - waypoints[currentWaypoint].transform.position.y) < 1)
            && (Mathf.Abs (transform.position.z - waypoints[currentWaypoint].transform.position.z) < 1))
        {
            //rb.useGravity = false;
            currentWaypoint++;
        }
    }
}

void OnTriggerEnter(Collider other)
{
    if(other.gameObject.tag == "GrindWayPoint")
    {
        Debug.Log ("Waypoint!!");
        isGrinding = true;
    }
}

```

# Answer
It looks like your code should work... bump. I do have a few tips however.

1) try to work in FixedUpdate when working with Rigidbodies.

2) Use movePosition to move Rigidbodies, rather than setting the position.

The above 2 tips will cause your game to jitter less. If you use fixedUpdate to move a rigidbody, it could move through the collider without being detected in the physicssteps.

3) anim.SetBool ("isOnGrinding", isGrinding); is 3 lines of code less than the ones you already have in your fixedUpdate.

4) Vector3.distance() is also shorter than calculating the offset between all 3 axis of a vector3 seperately.

5) When using moveTowards, don't multiply your targetPosition by a float, this would give you an entirely different position. if you want to move it gradually, use Vector3.Lerp, or calculate the offset first.

Try to provide a bit more information too, it seems like it should work, but i don't really know anything about your setup. Do your waypoints have colliders on them? Or does the gameObject with the waypoints have a collider?
> 1 votes

# Answer
Your Vector3.MoveTowards and Rb.MoveTowards will works same. However you can use Vector3.Distance() instead of

```
if(Mathf.Abs(transform.position.x - waypoints[currentWaypoint].transform.position.x) < 1
        && (Mathf.Abs (transform.position.y - waypoints[currentWaypoint].transform.position.y) < 1)
        && (Mathf.Abs (transform.position.z - waypoints[currentWaypoint].transform.position.z) < 1))
    {
        //rb.useGravity = false;
        currentWaypoint++;
    }

```

You can use it like

```
Vector3.Distance(transform.position,waypoints[currentwaypoint].transfrom.positon)

```

It Will return float you can make a condition out of it. Also You are not considering trasnform.forward in your movement. Your player may not move using forward. You should check out this link.

https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
> 0 votes

---
Tags: unity, c#, rotation, movement, waypoints
---


title: BitmapFont draw nothing on some devices

text:
# Question
Title: BitmapFont draw nothing on some devices
I use libgdx and I draw some text with BitmapFont, it works, but on some devices with Android 5.1 game draw only numbers and punctuation symbols, without any text.

I tried two ways:

1) Font Generator:

```
    mFontGenerator = new FreeTypeFontGenerator(Gdx.files.internal(fontName));
    mFontParameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
    mFontParameter.characters = Font.FONT_CHARS;
    mFontParameter.size = mSizePixels;
    mFontParameter.color = mTextColor;
    mFontParameter.borderWidth = mBorderWidth;
    mFontParameter.borderColor = mBorderColor;
    mBitmapFont = mFontGenerator.generateFont(mFontParameter);
    mBitmapFont.setUseIntegerPositions(false);
    mBitmapFont.getData().setScale(mTextScale);
    mFontGenerator.dispose();

```

2) Font, created in Hiero:

```
    mBitmapFont = new BitmapFont(Gdx.files.internal(fontName));
    mBitmapFont.setUseIntegerPositions(false);
    mBitmapFont.getData().setScale(mTextScale);
    mBitmapFont.setColor(mTextColor);

```

Draw code is the same for both ways:

```
@Override
public void draw(SpriteBatch spriteBatch) {
    mBitmapFont.draw(spriteBatch, mText, mPositionX, mPositionY);
}

```

Both ways works on tablet with Android 7.1.1 and even on phone with Android 2.3.5, but on two devices with Android 5.1 I can see just numbers, no letters.

Thanks for any help!

# Answer
The problem was with localization bundle files charset: files need have UTF-8, but by default in Android Studio it was windows-1251. To change it go to File -\> Settings -\> Editor -\> File Encodings, press plus and choose localization bundle files, after choose UTF-8 at bottom, press OK
> 0 votes

---
Tags: libgdx, android, text
---


title: How would I attack saving a game?

text:
# Question
Title: How would I attack saving a game?
In a lot of games, the player can save their progress. I have no clue how I would approach this and implement it into my game.
My only thought would be to make a new file called "progress," and add anything the player had done without saving, but I don't know how to add this to my game. Any ideas are appreciated.

# Answer
> 1 votes
I'm just a hobbyist, but here's what I might do.

Create a "save game" button in whatever scene you want the player to be able to save from. When clicked, this button calls a `save_game()` method from your game class.

You can design this method to create a file with whatever structure you want. For example, you can store the player's position, current level, inventory, etc.

When loading a game, call a `load_game()` method from the game class which generates the game instance using this saved info.

---
Tags: java, savegame
---


# Question
Title: Changing color of UI Text in Unity into custom values
There are a few objects in the scene as well as a title. I want the title to change its text and color based on the object that is mouse-overed. The script below is added to each object that is intended to change the color and text of the title.

The title changes it's color correctly when values like `Color.red` are assigned but doesn't change color when values like `new Color(254f, 152f, 203f)`.

```
public Text title;

void OnMouseEnter()
{
    switch(name)
    {
    CONDITION1:
        title.color = Color.yellow;  // works well
        break;

    CONDITION2:
        title.color = new Color(254f, 152f, 203f);  // doesn't work
        break;
    }

    title.text = name;
}

void OnMouseExit()
{
    title.text = "DEFAULT VALUE";
    title.color = Color.white;
}

```

Is there a specific reason to the former method to work and latter not to work? How can I change the color of the `Text` element with custom values?

# Answer
> 5 votes
Constructor of Color class takes float parameters from 0 to 1 like this `title.color = new Color(1f, 0.5f, 0.8f);`

# Answer
> 8 votes
You can do this with the code below:

```
title.color = new Color(254.0f/255.0f, 152.0f/255.0f, 203.0f/255.0f);

```

# Answer
> 3 votes
If you'd like to pass RGBA in the common way you can also use Color32 that takes 4 bytes ranged from 0 - 255:

```
title.color = new Color32(254, 152, 203, 255);

```

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


title: Custom 2D physics on unity

text:
# Question
Title: Custom 2D physics on unity
I have seen a lot of people think that for a 2D platformer game, Unity2D physics is not really the best approach, and recommend implementing your own physics.

I found the idea interesting, but I don't know how to approach the issue.

Using 2D Rigidbodies, and setting them as kinematic, allows you to ignore unity's physics. But how would collisions be handled without relying on Unity collision system?

# Answer
The collision detection system doesn't require objects to have non-kinematic rigidbodies. You can set all rigidbodies to kinematic and still detect collisions. All you need are Colliders with appropriate shapes.

You can execute code when the collider of a game object intersects the collider of a different game object by setting the "is Trigger" flag on its collider and implementing the `OnTriggerEnter2D`, `OnTriggerStay2D` and/or `OnTriggerExit2D` events in one of its scripts. This allows you to implement mechanics like contact damage or projectile impacts.

Objects won't block each other's movement anymore, but if you don't want to use Unity's physics engine, then making that happen is your responsibility. Before you move an object, check if there are any obstacles in the way. The static methods for collision detection of the class `Physics2D` can help you to do that.
> 3 votes

# Answer
How old were these peoples thoughts? And why do they think that?

Perhaps in the past, but now that Unity has a tilemap system (released October 2017), I don't see why you wouldn't use Unity2D physics to do this. This is the kind of thing that it is intended for, after all.

A tilemap with a collider attached, as well as a gameobject with a box collider and controller script, and you have a simple platformer in minutes. And if you want to add detail layers, you can just add another tilemap to the grid object, and not attach a collider.

I've also seen a collider merger that can be attached (though not used it myself yet) and that you can create animated tiles as well, as well as tiles that change depending on the tiles around them.
> 1 votes

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


# Question
Title: In a shader, what is the meaning of "<some float>.xy?"
I'm trying to research this in Unity manuals online, and I'm finding plenty of references to `.xy` but not sure what it is. While this is for Unity, I'm assuming this principal is more generic across all shader systems.

When we have a `float3` variable called `b` and we say `b.xy` what are we getting?

Is it X * Y?

Is it a `float2`, with X & Y passed through? If this is the case, I'm also seeing `b.xy / a.xy` and I'm wondering how vector division works in shaders.

# Answer
> 6 votes
Partwise grabbing of each axis.

> When we have a float3 variable called b and we say b.xy what are we getting?

You're getting a float2 that contains \[x,y\]

This can be expanded, twisted and combined in interesting ways, too:

```
float3 tripleX = a.xxx
float3 reverse = a.zyx

```

> If this is the case, I'm also seeing b.xy / a.xy and I'm wondering how vector division works in shaders.

result.x = b.x / a.x

result.y = b.y / a.y

# Answer
> 1 votes
Unity usually uses a hlsl dialect called cg. What you see is basically a selector, so if B is a float3 C = B.xy is a float2 with C.x == B.x and C.y == B.y .

In cg specificationthis is referred to as "swizzle operator". (Kudos to DMGregory for this)

---
Tags: shaders
---


# Question
Title: calculate the offset between a quad and the mouse position Opengl
I am working on a very simple "GUI framework" for my game.

As you can see from the GIF, i have a window object that can be selected when the mouse is inside of it and dragged, when the left mouse button is being pressed.

I tried to solve the problem this way:

Basically i calculate the x and y component of the distance between the center of the window and the mouse cursor. I then add the component values to the window function, which looks something like:

```
//mousePosition is a Vector2() that stores the mouse position
//x_component is a float, calculated by doing:
//float x_component = mousePosition.x - window.getPosition().x;
//same for the y_component variable.

window.setPosition(Vector2(mousePosition.x + x_component, mousePosition.y + y component));//set position takes in a Vector2

```

But for some reason, this is not working. I think that it's because we are not taking in consideration the fact that the x or y component could be negative, in relation to where we press the mouse inside the window.

Can someone help me?

# Answer
If the idea is to click and drag the window then you are assuming that the coordinates of the mouse cursor relative to the upper-left corner of the window will be the same before and after the mouse moves. So when you get a mouse-down event, record that offset: `offset_at_grab_time = mouse_position_in_screen_coordinates - window_position_in_screen_coordinates`. Then, when the mouse moves you can update the window position to have the same relative offset to the mouse as when you grabbed it by setting the position such that `new_window_position_in_screen_coordinates = new_mouse_position_in_screen_coordinates - offset_at_grab_time`

Ignore the center of the window; rather, you are interested in the position of the window in the same coordinate system as the mouse coordinates.
> 0 votes

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


# Question
Title: Detecting on which side of the box a collision occurred
**Explanation**

I have a rectangle with a trigger on it when it's hit by my player game object from the side it's supposed to activate a certain method. Illustration:

And when it's hit from the bottom or top it's supposed to activate an other method. Illustration:

However the way I'm checking what method to use is not working in all cases.

**Problem**

There are some cases where the player is hitting the side of the rectangle but the method being called is the one supposed to be called when the rectangle is hit from the bottom or the top. When the player is hitting the top or bottom everything is working just fine.

**Code**

```
protected override void OnCollision(Collider2D coll, PlayerMovement player)
{
    float playerMaxY = player.YCord + player.Height / 2;
    float playerMinY = player.YCord - player.Height / 2;

    //YCord is the y coordinate of the rectangle
    float thisMaxY = YCord + Height / 2;
    float thisMinY = YCord - Height / 2;

    base.OnCollision(coll, player);

    //This condition here is where i need an improvement
    if ((playerMinY >= thisMaxY && playerMaxY >= thisMaxY) ||
        (playerMinY >= thisMinY && playerMaxY >= thisMinY))
        BounceHorizontal(coll, player);
    else
        BounceVertical(coll, player);
}

```

# Answer
> 1 votes
In case you do need collisions from bot, consider the following graphic:

In these two cases you have a vertical collision. In all the other ones, you have a horizontal one. So you get:

```
if ((playerMinY >= thisMaxY) ||
    (playerMaxY <= thisMinY))
    BounceVertical(coll, player);
else
    BounceHorizontal(coll, player);

```

In case the corner of the player hits exactly the corner of the rectangle, it would bounce vertical.

# Answer
> 1 votes
I'm going to break down this statement:

```
if ((playerMinY >= thisMaxY && playerMaxY >= thisMaxY) ||
    (playerMinY >= thisMinY && playerMaxY >= thisMinY))

```

The first part says "if the bottom of the player is greater than the top of the platform and the top of the player is greater than the top of the platform."

* Hold on: why do we need this AND statement? The top of the player will always be greater than the bottom of the player and the bttom of the player is already known to be greater than the platform's maximum Y.

The second part says "if the bottom of the player is greater than the bottom of the platform and if the top of the player is greater than the top of the platform."

* Again, the second half is unneccessary: the top of the player will always be greater than the bottom of the platform if the bottom of the player is!
* Secondly...this logic will be true when the player collides with the *side* of the platform, but their feet are higher up than the platform is. As in precisely this case!
* Third...because these two statements have been ORed together, the second part will always be true any time the *first one is:* If the player's feet are above the top of the platform, they're clearly above the bottom of it too!

Yikes! Your code isn't distinguishing these two cases at all!

The only statement you can make that would result in your desired outcome is this:

```
if(playerMinY < thisMaxY)

```

The player's feet should never ever be below the top of the platform...unless they've collided with the sides (or bottom, but you haven't asked about collisions from below). Precisely the distinguishing factor you're looking for.

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


# Question
Title: Why do I get this error importing the Chartboost SDK?
I am trying to add chartboost ads, I had added the jar file to my libs but when I am trying to import the chartboost sdk it gives me error and the whole lines of:

```
import com.chartboost.sdk.Chartboost;
import com.chartboost.sdk.CBLocation;
import com.chartboost.sdk.ChartboostDelegate;

```

was red but when I added this code to the gradle

```
compile files('libs/chartboost.jar')

```

only Chartboost , CBLocation, ChartboostDelegate, are red and give me

```
Error:(19, 26) error: package com.chartboost.sdk does not exist

```

How to import the chartboost sdk correctly

here is the code of the build gradle (Project):

```
buildscript {
    repositories {
        mavenCentral()
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
        jcenter()
    }
    dependencies {
        classpath 'de.richsource.gradle.plugins:gwt-gradle-plugin:0.6'
        classpath 'com.android.tools.build:gradle:1.5.0'
        classpath 'org.robovm:robovm-gradle-plugin:1.12.0'
    }
}

allprojects {
    apply plugin: "eclipse"
    apply plugin: "idea"

    version = '1.0'
    ext {
        appName = "FlappyBird"
        gdxVersion = '1.7.2'
        roboVMVersion = '1.12.0'
        box2DLightsVersion = '1.4'
        ashleyVersion = '1.7.0'
        aiVersion = '1.7.0'
    }

    repositories {
        mavenCentral()
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
        maven { url "https://oss.sonatype.org/content/repositories/releases/" }
    }
}

project(":desktop") {
    apply plugin: "java"

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
        compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"
    }
}

project(":android") {
    apply plugin: "android"

    configurations { natives }

    dependencies {
        compile project(":core")

        compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"
        compile 'com.google.android.gms:play-services-ads:9.2.1'
        compile files('libs/chartboost.jar')

    }
}

project(":ios") {
    apply plugin: "java"
    apply plugin: "robovm"

    dependencies {
        compile project(":core")
        compile "org.robovm:robovm-rt:$roboVMVersion"
        compile "org.robovm:robovm-cocoatouch:$roboVMVersion"
        compile "com.badlogicgames.gdx:gdx-backend-robovm:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-ios"
        compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-ios"
    }
}

project(":html") {
    apply plugin: "gwt"
    apply plugin: "war"

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx:$gdxVersion:sources"
        compile "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion:sources"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion:sources"
        compile "com.badlogicgames.gdx:gdx-box2d-gwt:$gdxVersion:sources"
    }
}

project(":core") {
    apply plugin: "java"

    dependencies {
        compile "com.badlogicgames.gdx:gdx:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
    }
}

tasks.eclipse.doLast {
    delete ".project"
}

```

and here the code of build gradle ( module: android):

```
android {
    buildToolsVersion "23.0.3"
    compileSdkVersion 24
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
            jniLibs.srcDirs = ['libs']
        }

        instrumentTest.setRoot('tests')
    }
    defaultConfig {
        applicationId "com.myflappybird.game"
        minSdkVersion 9
        targetSdkVersion 24
    }
}

// called every time gradle gets executed, takes the native dependencies of
// the natives configuration, and extracts them to the proper libs/ folders
// so they get packed with the APK.
task copyAndroidNatives() {
    file("libs/armeabi/").mkdirs();
    file("libs/armeabi-v7a/").mkdirs();
    file("libs/x86/").mkdirs();

    configurations.natives.files.each { jar ->
        def outputDir = null
        if(jar.name.endsWith("natives-armeabi-v7a.jar")) outputDir = file("libs/armeabi-v7a")
        if(jar.name.endsWith("natives-armeabi.jar")) outputDir = file("libs/armeabi")
        if(jar.name.endsWith("natives-x86.jar")) outputDir = file("libs/x86")
        if(outputDir != null) {
            copy {
                from zipTree(jar)
                into outputDir
                include "*.so"
            }
        }
    }
}

task run(type: Exec) {
    def path
    def localProperties = project.file("../local.properties")
    if (localProperties.exists()) {
        Properties properties = new Properties()
        localProperties.withInputStream { instr ->
            properties.load(instr)
        }
        def sdkDir = properties.getProperty('sdk.dir')
        if (sdkDir) {
            path = sdkDir
        } else {
            path = "$System.env.ANDROID_HOME"
        }
    } else {
        path = "$System.env.ANDROID_HOME"
    }

    def adb = path + "/platform-tools/adb"
    commandLine "$adb", 'shell', 'am', 'start', '-n', 'com.myflappybird.game/com.myflappybird.game.AndroidLauncher'
}

// sets up the Android Eclipse project, using the old Ant based build.
eclipse {
    // need to specify Java source sets explicitely, SpringSource Gradle Eclipse plugin
    // ignores any nodes added in classpath.file.withXml
    sourceSets {
        main {
            java.srcDirs "src", 'gen'
        }
    }

    jdt {
        sourceCompatibility = 1.6
        targetCompatibility = 1.6
    }

    classpath {
        plusConfigurations += [ project.configurations.compile ]
        containers 'com.android.ide.eclipse.adt.ANDROID_FRAMEWORK', 'com.android.ide.eclipse.adt.LIBRARIES'
    }

    project {
        name = appName + "-android"
        natures 'com.android.ide.eclipse.adt.AndroidNature'
        buildCommands.clear();
        buildCommand "com.android.ide.eclipse.adt.ResourceManagerBuilder"
        buildCommand "com.android.ide.eclipse.adt.PreCompilerBuilder"
        buildCommand "org.eclipse.jdt.core.javabuilder"
        buildCommand "com.android.ide.eclipse.adt.ApkBuilder"
    }
}

// sets up the Android Idea project, using the old Ant based build.
idea {
    module {
        sourceDirs += file("src");
        scopes = [ COMPILE: [plus:[project.configurations.compile]]]

        iml {
            withXml {
                def node = it.asNode()
                def builder = NodeBuilder.newInstance();
                builder.current = node;
                builder.component(name: "FacetManager") {
                    facet(type: "android", name: "Android") {
                        configuration {
                            option(name: "UPDATE_PROPERTY_FILES", value:"true")
                        }
                    }
                }
            }
        }
    }
}

```

# Answer
I just tried to build a sample from Github that uses Libgdx with Chartboost and had no problems running it on an Android device. Go ahead and clone https://github.com/itsabhiaryan/AdService-LibGDX.git, it should work.
> 0 votes

---
Tags: java, android, libgdx
---


# Question
Title: Combining and drawing 2D lights in OpenGL
I have progressed to the lighting portion of my little framework and I managed to solve a few initial problems so now I'm left with the subtle weirdnesses.

At this stage I just have 2 lights - the ambient daylight and a hard-coded example light in my fragment shader (ultimately, I want to have multiple lights that I loop through adding together, and shadows would be nice too, but 1 step at a time!):

```
        uniform sampler2D u_image;

        varying vec2 v_texCoords;
        varying vec4 v_position;

        uniform vec3 ambient_light; // set as (0.3, 0.3, 0.3), night!

        vec2 point_light_pos = vec2(-0.4, 0.3);
        vec3 point_light_col = vec3(0.999, 0.999, 0.999);
        float point_light_intensity = 0.4;

        void main()
        {
            vec4 frag_color = texture2D(u_image, v_texCoords);
            if(frag_color.a < 1.0)
              discard;

            float distance = distance(point_light_pos, v_position.xy);
            float diffuse = 0.0;

            if (distance <= point_light_intensity)
                diffuse =  1.0 - abs(distance / point_light_intensity);

            gl_FragColor = vec4(min(frag_color.rgb * ((point_light_col * diffuse) + ambient_light), frag_color.rgb), 1.0);
        }

```

Which *almost* does what I want, but there are 2 problems:

The light has a bright ring in it and the light is squashed on the y-axis. I actually like how it looks squashed at this ratio, but I'd much rather do it deliberately.

I the y-axis squashing is down to the window aspect ratio - if the window is square, the light is circular, but I don't know how to fix this in the fragment shader.

I don't know where the bright ring is coming from.

# Answer
When your distance \<= 0.3 you set diffuse to be 1.0 - distance = 0.7, and also add 0.3 ambient, so lighting value will effectively always be 1 for distances \<= 0.3... hence the bright ring in the middle.

As for the stretch I'm guessing you have normalized coordinates mapped to the screen, perhaps take the x/y stretch values into account when calculating your distances.

***edit 1:***

oops I misread the code, but I think a similar effect is happening. I've plugged the numbers into a spreadsheet and get the following:

i've only shown the green channel values, but the first few initial values in this case are 1.0
> 2 votes

# Answer
Excellent catch by DMGregory in that the ring is an optical illusion. If you zoom in really close, you'll see that the ring is not there. You can verify values in an image editor.

Next, in order to have the light look good, make sure you are doing all light calculations in the correct colour space (which is the linear colour space.)

In OpenGL this is best achieved by creating an SRGB capable framebuffer and then doing `glEnable( GL_FRAMEBUFFER_SRGB );`

Lastly, you need to adapt the quad you are drawing for the light: If window aspect ratio changes, you need to use different vertex positions for the quad. If the window has ratio 2:1, then a square covering top to bottom of screen has lowerleft coordinates (-0.5,-1) and upper right (0.5,1). So multiply the x-coords of the quad with (winh/winw).
> 2 votes

# Answer
**In regards to the y-axis squishing** \- The problem, like you said, is caused by the window dimensions. OpenGL works in a different space then you're trying to work in. So to solve this, simply take your y-scale and then divide it by the window's y-scale, then multiply by one hundred. This is your new y-scale. Do the same for the x axis.
> 0 votes

---
Tags: opengl, glsl, lighting
---


title: What's in Nintendo's "Dev Interface?"

text:
# Question
Title: What's in Nintendo's "Dev Interface?"
Not that long ago, Nintendo opened their developer program for access by anyone who registers a Nintendo Developer account, giving equal access to indie and commercial developers. Or, at least thats what the linked page says.

The tools page lists Unity and a HTML5 framework for game development, as well as the "Nintendo Dev Interface (NDI)." Since I am not really interested in developing using Unity (or HTML5, for that matter) I want to know what the NDI contains, at least in general terms.

(I don't doubt that at least some of that information is covered by an NDA, but I'd like to know as much as possible, since I can't register for a while)

I'm especially interested in what sort of compiler/languages are supported, what graphics APIs (and/or abstraction layers, like SDL) are allowed and how play testing works (some sort of compatability layer? Nintendo sanctioned emulation?).

# Answer
> 1 votes
*The following is my understanding of the NDI based on the sources linked below.*

The NDI, is a client software that will allow the user to connect to Nintendo servers to download SDKs, samples, drivers to connect to Nintendo development consoles, and Visual Studio extensions that provide built targets, debug interfaces and emulation environments.

*Note*: I am unaware whatever or not the NDI provides similar tools for a different IDE, other than Visual Studio. It also makes sense that if such tools exist, they would exist for Visual Studio given that Unity is part of the package. In addition, I have no idea of the extents of the debugging and emulation capabilities.

The NDI will allow you to manage different your packages depending on the target console of your projects and keep them up to date.

**Sources**:

**Disclaimers**:

* By making this post, I am not copying or distributing copyrighted content.
* I am currently - at the time of writing - not under a NDA with Nintendo, and I have not been part of their developer program.
* I am not and have not been - at the time of writing - an employee of Nintendo.
* The information in the linked sources did become available NOT at my fault.
* I receive no economic profit by making this post.
* My understanding of the NDI described above is the result of my own personal conjectures based on the information available on the linked sources.
* This post should NOT be considered a replacement for accessing Nintendo developer program or contacting Nintendo.

# Answer
> 0 votes
This is impossible to answer. Since if you have access you are not allowed to tell these details. But what I would recommend you is to call Nintendo directly if you are really interested in developing for a Nintendo system. They might answer your questions.

---
Tags: nintendo
---


# Question
Title: Change the image of sdl window with a new one
I will make a game and it has 3 buttons on its menu. Those buttons supposed to change the picture the background of the menu

When i click on play, another picture should appear like so

I found a solution which is closing the current program and starting another one that has the comming soon picture but what i would like to do is to only change the picture without the need to close the program and start another one , Here is my code for the menu screen:

```
#include <stdlib.h>
#include <stdio.h>
#include <SDL/SDL.h>

  int continuer=1;
  SDL_Event event;

int main(int argc, char *argv[])
{
    SDL_Surface *ecran = NULL, *imageDeFond = NULL, *sapin = NULL;
    int continuer=1;
    SDL_Event event;
    SDL_Rect positionFond,positionSapin;

    positionSapin.x = 0;
    positionSapin.y = 0;
    positionFond.x = 0;
    positionFond.y = 0;

    SDL_Init(SDL_INIT_VIDEO);

    ecran = SDL_SetVideoMode(800, 600, 32, SDL_HWSURFACE);
    SDL_WM_SetCaption("Chargement d'images en SDL", NULL);

    /* Chargement d'une image Bitmap dans une surface */
    imageDeFond = SDL_LoadBMP("menu.bmp");
    /* On blitte par-dessus l'écran */
    SDL_BlitSurface(imageDeFond, NULL, ecran, &positionFond);

    SDL_Flip(ecran);
    SDL_FreeSurface(imageDeFond);

    while(continuer)
 { SDL_WaitEvent(&event);
   switch(event.type)
   {
       case SDL_QUIT:
        continuer=0;
       break ;
       case SDL_KEYDOWN:

     switch (event.key.keysym.sym)

      {

          case SDLK_ESCAPE:

              continuer=0;

          break;

       }

      break;
    case SDL_MOUSEBUTTONUP:
       if (event.button.button == SDL_BUTTON_LEFT)
        {
            positionFond.x = event.button.x;

            positionFond.y = event.button.y;
             if (event.button.x> 150 && event.button.x < 320 && event.button.y > 340 && event.button.y < 415 )
              {
               continuer = 0;
              }
              else if (event.button.x> 150 && event.button.x < 320 && event.button.y > 105 && event.button.y < 180 )
                  {
                     continuer=0;
                      SDL_Quit();
                    int status = system("./cs");

                    }

        }

     break ;

  }
   }

    SDL_Quit();

    return EXIT_SUCCESS;
}

```

Here is my second code when i click on the play button:

```
#include <stdlib.h>
#include <stdio.h>
#include <SDL/SDL.h>

  int continuer=1;
  SDL_Event event;

int main(int argc, char *argv[])
{
    SDL_Surface *ecran = NULL, *imageDeFond = NULL, *sapin = NULL;
    int continuer=1;
    SDL_Event event;
    SDL_Rect positionFond,positionSapin;

    positionSapin.x = 0;
    positionSapin.y = 0;
    positionFond.x = 0;
    positionFond.y = 0;

    SDL_Init(SDL_INIT_VIDEO);

    ecran = SDL_SetVideoMode(800, 600, 32, SDL_HWSURFACE);
    SDL_WM_SetCaption("Chargement d'images en SDL", NULL);

    /* Chargement d'une image Bitmap dans une surface */
    imageDeFond = SDL_LoadBMP("menujouer.bmp");
    /* On blitte par-dessus l'écran */
    SDL_BlitSurface(imageDeFond, NULL, ecran, &positionFond);

    SDL_Flip(ecran);
    SDL_FreeSurface(imageDeFond);

    while(continuer)
 { SDL_WaitEvent(&event);
   switch(event.type)
   {
       case SDL_QUIT:
        continuer=0;
       break ;
       case SDL_KEYDOWN:

     switch (event.key.keysym.sym)

      {

          case SDLK_ESCAPE:

              continuer=0;
                SDL_Quit();
           int status = system("./menu");

          break;

       }
 }
   }

    SDL_Quit();

    return EXIT_SUCCESS;
}

```

Is there any solution to make it in the same program without closing and reopning an other program because when i tried it the problem was the buttons of the first picture(menu image) was still active so when i click on the zone of quit it closes the program even though the menu image is hidden under the second.

# Answer
> 2 votes
You will need to have the program keep track of which screen it is on and respond differently depending on the screen. You can do this similarly to the way your programs are keeping track of whether they should stop running or not, with the `continuer` variable.

So you can add another variable. I will call it `screen_number` but you can call it whatever you like in your code.

First we set it to 1.

```
   int screen_number = 1;

   int continuer=1;

```

Then when we respond to mouse clicks, we make it so that we only do that if `screen_number` is 1. That is we replace this:

```
case SDL_MOUSEBUTTONUP:
       if (event.button.button == SDL_BUTTON_LEFT)
        {
            positionFond.x = event.button.x;

            positionFond.y = event.button.y;
             if (event.button.x> 150 && event.button.x < 320 && event.button.y > 340 && event.button.y < 415 )
              {
               continuer = 0;
              }
              else if (event.button.x> 150 && event.button.x < 320 && event.button.y > 105 && event.button.y < 180 )
                  {
                     continuer=0;
                      SDL_Quit();
                    int status = system("./cs");

                    }

        }

     break ;

```

with something like this:

```
case SDL_MOUSEBUTTONUP:
    if (screen_number == 1) {
       if (event.button.button == SDL_BUTTON_LEFT)
        {
            positionFond.x = event.button.x;

            positionFond.y = event.button.y;
             if (event.button.x> 150 && event.button.x < 320 && event.button.y > 340 && event.button.y < 415 )
              {
               continuer = 0;
              }
              else if (event.button.x> 150 && event.button.x < 320 && event.button.y > 105 && event.button.y < 180 )
                  {
                     continuer=0;
                      SDL_Quit();
                    int status = system("./cs");

                    }

        }
    }
     break ;

```

Then when we switch to the other screen, we set the `screen_number` to 2.

```
  if (event.button.x> 150 && event.button.x < 320 && event.button.y > 340 && event.button.y < 415 )
  {
    screen_number = 2;
  }

```

So now if you click on the button it will only work once and the quit button will do nothing since the `screen_number` is 2.

Now, in order to draw the `"menujouer.bmp"` image at the right time you will need to load both images and in the `while` loop check what `screen_number` is and draw the right image

```
if (screen_number == 1) {
    /* draw "menu.bmp" */
} else if (screen_number == 2) {
    /* draw "menujouer.bmp" */
}

```

It sounds like you were able to draw one image on top of the other before so hopefully you can figure it out from there. If not, you can always ask another question!

This next part isn't strictly necessary, but it is helpful for when you come back to the code after a break.

It can be hard to remember which screen is which, so you can give names to the numbers to help you remember.

```
#define MENU 1
#define MENUJOUER 2

```

with these lines near the top of your program, whenever you write `MENU` it will be exactly as if you had written 1. So you can change everything that looks like `screen_number == 1` to `screen_number == MENU`. Similarly you can change everything that looks like `screen_number == 2` to `screen_number == MENUJOUER`, and the program will act exactly the same. This makes it easier to remember how the program works later. You can change `MENU` or `MENUJOUER` to something else if you like too.

---
Tags: sdl, c
---


title: C# invoke stops unity

text:
# Question
Title: C# invoke stops unity
I'm making a game where in needs to randomly generate objects on a plane, so I setup a code to spawn Food, but whenever I run the code Unity uses up all my computers memory and 40% cpu. I have a fairly good computer and have no issue with anything else in the project. The code has worked when I called it in FixedUpdate but as soon as I try and call it in an invoke it just breaks everything. I have only started working with unity for less than 24 hours so I don't really know what could be wrong, since I didn't get any errors or warnings.

```
using System.Collections;
using UnityEngine;

public class SpawnFood : MonoBehaviour
{
public Rigidbody Food;
public float x;
public float y;
public float z;
public Vector3 pos;
public float spawnTime;

void FixedUpdate()
{
    Start:
    Invoke("FoodSpawn", spawnTime);
    goto Start;
}

void FoodSpawn()
{
    x = (UnityEngine.Random.Range(-110f, 110f));
    z = (UnityEngine.Random.Range(0.50f, 0.51f));
    y = (UnityEngine.Random.Range(-50f, 51f));
    Vector3 pos = new Vector3(x, z, y);
    Instantiate(Food, pos, Quaternion.identity);
}

}

```

# Answer
The `label` and `goto` in your `FixedUpdate` method is an infinite loop equivilent to:

```
while(true)
{
   Invoke("FoodSpawn", spawnTime);
}

```

Once the engine executes this method it would never leave it (and would keep queuing new Invokes).

A better option may be using InvokeRepeating in the `Start` method as indicated in the documentation page.
> 5 votes

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


# Question
Title: How can I get PagedGeometry grass to receive shadows?
I made the switch to Ogre3D (v1.7) and to using PagedGeometry. What I'm trying to do is make a simple scene with a terrain, some trees and grass. In a nutshell, I would like to achieve this kind of effect in Ogre:

Transparent/cut-out shadows are implemented in PagedGeometry demos but I can't find any solution on how to properly cast shadows on grass like the example above.

What technique can I use to accomplish this?

# Answer
This is not my answer, but a reference to what I believe is the solution to the question.

The post I am linking to below (titled "paged geometry trees and shadows") directly describes solving the problem of putting tree shadows on grass with paged geometry. It specifically involves calling m\_sceneMgr-\>setShadowTechnique(SHADOWTYPE\_TEXTURE\_ADDITIVE) with a custom shader for the shadows.

https://www.ogre3d.org/addonforums/14/t-8945.html or Archive.org version.

This tutorial also references paged geometry, trees, grass, and shadows. It applies a lightmap to the grass, use the setColorMap() function.

https://ogrecave.github.io/ogre-pagedgeometry/tut3.html or Archive.org version. It specifically aplplies a lightmap to grass, use the setColorMap() function.
> 3 votes

---
Tags: shadows, ogre, billboarding
---


# Question
Title: lwjgl licence and requirements for commercial use
is it completely legal to use light weight java game library in a commercial 2 dimension game engine like drag and drop not straight code?if yes what are their requirements?if not what are my options? thanks in advance.

# Answer
> 1 votes
I am not a copyright lawyer. This answer is based on a layman interpretation of the license text and on common practices in the software development industry. When you want to be sure, ask a real lawyer.

---

The LWJGL license is a slightly modified 3-clause BSD license.

It is a weak copyleft license. That means you can use it in any program published under any license. The only condition is that you include the license text with the disclaimer in your product. Contrary to strong copyleft licenses like the GNU GPL this does not imply that the license conditions apply to your own work. They only apply to the LWJGL components. Your own work is still licensed under your license terms.

The usual way to do this with tools is by integrating it into your about dialog and also put it as a text file into the program directory. The usual way to do this with games is by putting it into the credits roll.

Also, you are not allowed to use the LWJGL name to endorse or promote your product. So you can not use advertisement slogans like "Jawad 2d Game Engine powered by LWJGL".

When the games created by your game engine also depend on LWJGL, then your users are also obligated to add the LWJGL license text to their games. You might want to do this automatically when building projects.

---
Tags: lwjgl, licensing
---


# Question
Title: Making only one side of a object receive light in Unity
So I want to achieve a visial asthetic in my game that looks like this

Meaning I dont want the outer parts of my dungeon walls to be affected by light. Now I know this is posible if the object itslef is created with 2 materials that way I can make the back material solid black. But I was wondering if there is a easy way to achieve this with a shader.

# Answer
> 2 votes
I know of two main techniques to achieve this, which most games use with some variation between them:

---

# 1) Procedural or voxelized "filler" mesh.

1. Model your walls as simple 1-sided "planes". By design, 1-sided surfaces can only be seen through one side, as faces with opposite normal are ignored in render. Optionally, but highly recommended, is making these in modular sections.
2. Fill the space behind the walls with procedural meshing of some sort, either as "roof" (plane) along the top of the walls, or as solid.
3. Depending on the look&feel you want to achieve, you can give this filler a solid opaque color (IE pitch black), or have it with a material similar to the walls, to "blend in".

This is the technique used in games like **Evil Genius**:

---

# 2) Make your lighting work with the "wall" meshes and the procedural nature of the game by design.

1. Make your "wall" meshes like in the first technique; meaning one-sided, and preferably modular.
2. Don't use global illumination at all. Instead, make lighting be localized to the player, and/or enemies, and/or proceduraly-generated together with the walls, in pieces. Make it never be generated above the top of the walls. And make each light never exceed the "thickness" of it's own section (two corridors running side-by-side shouldn't "bleed" lighting to each-other).
3. Profit. The game gives a "dark theme" to the spaces outside the walls by design.

As far as I can tell, this is the technique used in (some areas of) **Path of Exile**:

# Answer
> 0 votes
Rather than worrying about the color of the back sides of your walls, just put a pure black "roof" above the empty areas.

---
Tags: unity, shaders, lighting
---


# Question
Title: Reduce Blur and headache during gameplay
I am implementing a browser based Javascript game here.

On tougher levels when the speed of the game increases, what we observe is that the user will experience headaches and the view will start to blur when the user stares at the screen for some reason.

How can we find the reason for this reaction in the user and avoid it?

How to simulate the problem -

1. Go the link
2. Click on Play
3. Play the third level for 5 - 10 seconds

# Answer
I tested it quickly on Firefox with an IGPU.

The game was technically playable, but the framerate was poor -- I'd eyeball 15~30 FPS, objects were covering noticeable distances in a single frame.

Combined with the big and relatively complex sprites, and the fast pace of the game, this made the whole scene pretty hard to understand and follow, enough so that it was uncomfortable to play.

The problem was compounded by the fact that the game plays in a narrow band in the middle of the screen. The unused area's background is nonetheless bright and complex, and having it scrolling and stuttering in my peripheral vision was even worse than the part I was trying to concentrate on.

My suggestions would be:

1. Find ways to optimize your game so it runs smoother.
2. Reduce the peripheral noise of your background so it doesn't catch the eye.
3. Maybe switch to a side-scrolling view so more of the screen is actually relevant to the gameplay.
> 2 votes

---
Tags: game-design, game-mechanics, user-experience
---


# Question
Title: Cant set up to get input from second analog stick
So I know for a fact that the stick on my gamepad is working. The problem is I cant set it up in the Input Manager. I tried all possible Axis configurations and still getting a input values of 0. Here is a screenshot of the configuration.

# Answer
Is your controller a XBox360 controller? The different input axis are defined here. Mind you that the axis are not the same for Windows/Mac/Linux.

You can try to set the "Joy Num" to "Joystick 1", to only accept this joysticks inputs.

Alternatively, have you tried to check if buttons are working? You can set it up as (for windows) "Positive Button" - "joystick 1 button 0", cramp up the sensitivity to 1000 to make sure you get the inputs, set the type to "Key or Mouse Button", and read the inputs from the axis to debug (`Input.GetAxis("Right Stick X")`).
> 1 votes

---
Tags: unity, input, joystick
---


title: Help with character turning?

text:
# Question
Title: Help with character turning?
I'm simply trying to make my character turn in his place, whether he's standing still or moving, currently, he isn't turning what-so-ever. Here is the code that I currently have for turning:

## I AM NO LONGER USING THIS TURNING FUNTION vvv

```
void Turning()
{
    Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit floorHit;

    if (Physics.Raycast (camRay, out floorHit, camRayLength, floorMask))
    {
        Vector3 playerToMouse = floorHit.point - transform.position;
        playerToMouse.y = 0f;

        Quaternion newRotation = Quaternion.LookRotation(playerToMouse);
        playerRigidbody.MoveRotation(newRotation);
    }
}

```

So what should be happening is my character should turn and face toward wherever my mouse is pointing, but that isn't happening and I'm not sure why.

Thank you in advance for any assistance.

---

## WHAT I AM USING NOW

I have alternatively tried another bit of code which I will post below, I completely got rid of what is above in place of this:

```
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.LookAt(mousePos);

```

This will actually make the camera follow the mouse, but it goes crazy, the camera seems to spin in circles rapidly : here is actually a gif of what is happening. https://gyazo.com/952da6c28e644b7b0e6500a597b6804e/preview Could anyone help me figure how how to fix it?

# Answer
> 1 votes
I am not sure how to fix this problem but I do know what the problem is, on the back end. It is doing what you want it to do it is looking at the mouse, but as it moves so does the mouse so it is forever looking for that new rotation. It appears as its spinning because it is to the effect the world is moving the player is moving, the mouse is static but being static puts the mouse in a new location as its spinning so it's like a dog trying to catch its own tail. the world is spinning, the dog is spinning, the tail is static.

# Answer
> 1 votes
You need to set the mouse location to the center of the screen when the mouse moves. This is needed so that, like in @DaveBird 's answer, the camera does not chase its tail. you need to set the tail to nowhere until and after the mouse moves. So your second code is fine, you just need to set the mouse position to the center of the screen.

---
Tags: unity
---


title: Approaches to draw multiple objects

text:
# Question
Title: Approaches to draw multiple objects
I'm looking for an efficient way to render multiple object with unique texture sets each.

Right now I combine multiple objects into a single static vertex and index buffers in the way like this:

```
std::vector<Verts> v(m_vsize);
std::vector<uint32_t> ind(m_isize);

// SKIPPED: adding vertex and index data to "v" and "ind" vectors

D3D11_BUFFER_DESC vertexBuffer_desc = {};
vertexBuffer_desc.Usage = D3D11_USAGE_IMMUTABLE;
vertexBuffer_desc.ByteWidth = sizeof(Verts) * m_vsize;
vertexBuffer_desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBuffer_desc.CPUAccessFlags = 0;
vertexBuffer_desc.MiscFlags = 0;
vertexBuffer_desc.StructureByteStride = 0;

D3D11_SUBRESOURCE_DATA vertexData = {};
vertexData.pSysMem = &v[0];
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;

HRESULT hr = m_d3dDevice->CreateBuffer(&vertexBuffer_desc, &vertexData, &m_vertexBuffer);
if (FAILED(hr))
    return;

D3D11_BUFFER_DESC indexBuffer_desc = {};
indexBuffer_desc.Usage = D3D11_USAGE_IMMUTABLE;
indexBuffer_desc.ByteWidth = sizeof(uint32_t) * m_isize;
indexBuffer_desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBuffer_desc.CPUAccessFlags = 0;
indexBuffer_desc.MiscFlags = 0;
indexBuffer_desc.StructureByteStride = 0;

D3D11_SUBRESOURCE_DATA indexData = {};
indexData.pSysMem = &ind[0];
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;

hr = m_d3dDevice->CreateBuffer(&indexBuffer_desc, &indexData, &m_indexBuffer);
if (FAILED(hr))
    return;

```

After that I pass my buffers to `Render()` method and render everything with a single `DrawIndexed()` call:

```
// some stuff
m_d3dContext->IASetVertexBuffers(0, 1, m_vertexBuffer.GetAddressOf(), &stride, &offset);
m_d3dContext->IASetIndexBuffer(m_indexBuffer.Get(), DXGI_FORMAT_R32_UINT, offset);
// some more stuff
m_d3dContext->DrawIndexed(m_isize, 0, 0);

```

Where `m_isize` is a count of total indices. So what I'm looking for is how do I draw multiple objects separately? \- Create individual buffers per each object (object count is unknown at startup)? \- Create dynamic buffers and use those? \- Keep using static buffers with re-assigning pointers to new objects and call `DrawIndexed()` per object instead of per frame? \- A common solution? (Obviously unknown to me).

Basically all I need to find out is the name of pattern/technique commonly used to draw unknown amount of objects effectively. My approach doesn't work because I merge all groups into single vector variable and so I can't give various texture sets to various objects.

# Answer
> 1 votes
You can just create a unique vertex buffer for each mesh as a simple approach. Then for each mesh instance, you would bind the vertex buffer, set some shader constant buffer with per instance properties, set the textures, material and call Draw(). You can also create one big vertex buffer where you would put each mesh's vertices continuously and then the mesh instances would index that vertex buffer with an offset. You can specify an offset as an argument to the Draw() function. The same is true for DrawIndexed, you can specify an offset into an index buffer as well.

You can use instanced rendering (for example DrawIndexedInstanced function) to render each object in a single draw call, but with unique per instance data. But you can't bind unique textures per instance this way. You can however bind a texture array or texture atlas and have the per instance data index those in some way. In DirectX 12, you can do bindless textures and index textures dynamically which also extends instancing easily.

---
Tags: c++, directx, rendering
---


# Question
Title: Unity: Cannot access variable of C# script from another object
I have already found similar questions on *stackexchange.com* related to accessing variables from another object. But my question seems to have a slightly different context and the answers from those questions are not working.

I have the following (stripped off) scene comprising the standard FPS character:

```
Scene001
  |
  |--FPSController
       |
       |--FirstPersonCharacter

```

My (stripped off) Assets hierarchy is as follows (folders are enclosed with \<\> brackets):

```
<Assets>
  |
  |--<Scripts>
  |     |
  |     |--Actions.cs
  |
  |--<Standard Assets>
        |
        |--<Characters>
              |
              |--<FirstPersonCharacter>
                   |
                   |--<Scripts>
                         |
                         |--FirstPersonController.cs

```

Now `FirstPersonController.cs` is attached to `FPSController` by default and `Actions.cs` is attached by me to `FirstPersonCharacter`.

Excerpt from `FirstPersonController.cs` is as follows:

```
...
namespace UnityStandardAssets.Characters.FirstPerson
{
     ...
     public class FirstPersonController : MonoBehaviour
     {
          ...
          private void GetCharacter()
          {
               GameObject _obj = GameObject.Find("FirstPersonCharacter");// ok here
               bool is_acted = _obj.GetComponent<Actions>().is_acted; // error here, please see below
          }
          ...
     }
}

```

Excerpt from `Actions.cs` is as follows:

```
public class Actions: MonoBehaviour {
    ...
    public static bool is_acted;
    ...
}

```

All I want is to access `bool is_acted` variable of `Actions.cs` from `FirstPersonController.cs`.

Error is as follows:

```
Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/
FirstPersonController.cs(63,38):error CS0246: The type or namespace
name `Actions' could not be found. Are you missing an assembly reference?

```

To me this seems to be a problem of namespace or folder location!!?

Any help is highly appreciated. Thanks in advance.

**Updated above**

* Changed *Action* to *Actions*.
* Corrected typo `()`.

Sample project:

https://ufile.io/knmxj

# Answer
# This is caused by Unity

**But it's easy to fix.**

The `Standard Assets` folder is compiled *before* all other scripts (this may be a holdover from when Unity officially supported JavaScript / UnityScript files, which had to be compiled at a different time than C# files, so the Standard Assets were compiled before everything else so that both C# and JS user created scripts could reference it).

All you have to do to fix this is change the name of the folder `Standard Assets` to *anything else* (except another one of the magic keyword names, like `Resources`).

Also, you have another error in your code:

```
public static bool is_acted;
...
GetComponent<Actions>().is_acted;

```

Your field is Static and cannot be accessed via an instance object. Either you should be doing `Actions.is_acted` or remove the static modifier.
> 2 votes

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


title: 360 Orbital Camera Controller

text:
# Question
Title: 360 Orbital Camera Controller
I have a stationary cube in my scene that I'm orbiting a camera around. I have my MainCamera nested under a GameObject that I'm calling 'OrbitalCamera'.

I setup the script so that a click (or tap) and drag will rotate the camera around the object in space so it feels like you're rotating the cube (ie: if I click the top of a face on the cube, and pull down, I'm rotating the X value) but you'll actually be rotating the camera.

For the most part, my script works. However, after rotating the Y so much, the camera is upside down and the X gets inverted. Here's my script:

```
public class OrbitalCamera : MonoBehaviour {
    public bool cameraEnabled;

    [SerializeField] private float touchSensitivity;
    [SerializeField] private float scrollSensitivity;
    [SerializeField] private float orbitDampening;

    protected Transform xFormCamera;
    protected Transform xFormParent;
    protected Vector3 localRotation;
    protected float cameraDistance;

    void Start () {
        cameraEnabled = true;
        xFormCamera = transform;
        xFormParent = transform.parent;
        cameraDistance = transform.position.z * -1;
    }

    void LateUpdate () {
    if (cameraEnabled) {
            // TODO:: FIX PROBLEM WHERE WHEN CAMERA IS ROTATED TO BE UPSIDEDOWN, CONTROLS GET INVERSED
            if (Input.GetMouseButton(0)) {
                if (Input.GetAxis("Mouse X") != 0 || Input.GetAxis("Mouse Y") != 0) {
                    localRotation.x += Input.GetAxis("Mouse X") * touchSensitivity;
                    localRotation.y -= Input.GetAxis("Mouse Y") * touchSensitivity;
                }
            }
        }

        Quaternion qt = Quaternion.Euler(localRotation.y, localRotation.x, 0);
        xFormParent.rotation = Quaternion.Lerp(xFormParent.rotation, qt, Time.deltaTime * orbitDampening);
    }
}

```

Is there a good method to achieve this type of 360 camera? I'd like dragging from right to left to always move the camera left and dragging left to right to always move the camera right -- no matter how the camera is oriented.

# Answer
> 0 votes
Moving question to Stack Overflow (https://stackoverflow.com/questions/48550246/unity3d-c-sharp-360-orbital-camera-controller) as the GameDev Stack Exchange isn't nearly as popular. This question got me the 'tumbleweed' badge.

---
Tags: unity, c#, camera, rotation, orbit
---


# Question
Title: How to rotate directional billboard particle sprites toward the direction the particle is moving
## **Behavior:**

With the following texture

I get a weird behavior when I try to rotate my particles in the direction they are moving. Essentially, the quad seems to rotate, but just barely so that when they bounce on the ground or when they spawn we can clearly see that they are not aligned upward when the particle is going upward.

## **Shader code and process explanation:**

**particle\_billboard.geom:**

```
//This geometry shader takes points as a
//primitive input and return quads built with
//triangle strips

#version 430

layout (points) in;
layout (triangle_strip, max_vertices = 4) out;

layout (std140, binding = 0) uniform CameraInfo {
  mat4  ProjectionView; // Projection * View
  vec3  eye;    // camera position
};

uniform float particle_size;

in  vec4 ex_Color[];
in  vec3 ex_Direction[]; // Only one direction per particle so index is always direction[0]
out vec2 TexCoord;
out vec4 FragColor;

float angle_between_vector(vec3 v1, vec3 v2)
{
  return acos(
    dot(v1, v2)/ length(v1)*length(v2)
  );
}

vec3 project_vector_on_plane(vec3 v, vec3 normalized_plane_normal)
{
  return v - dot(v, normalized_plane_normal) * normalized_plane_normal;
}

vec4 quat_from_axis_angle(vec3 axis, float rad_angle)
{
  vec4 qr;
  float half_angle = 0.5*rad_angle;
  qr.x = axis.x * sin(half_angle);
  qr.y = axis.y * sin(half_angle);
  qr.z = axis.z * sin(half_angle);
  qr.w = cos(half_angle);
  return qr;
}

vec3 rotate_vertex_position(vec3 position, vec3 axis, float rad_angle)
{
  vec4 q = quat_from_axis_angle(axis, rad_angle);
  vec3 v = position.xyz;
  return v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v);
}

void main(void) {
  // Built-in variable "gl_in" of the geometry shader
  // gives us the index in the primitive. Points only
  // have one index, so gl_in[0] it is.

  vec3 wPos = gl_in[0].gl_Position.xyz;
  vec3 wRotatedPos = wPos;
  vec3 originalPos = wPos;
  vec3 wPosToCamera = normalize(eye - wPos);
  vec3 wUp = vec3(0.0, 1.0, 0.0);
  vec3 wRight = cross(wPosToCamera, wUp);

  FragColor = ex_Color[0]; // Points only have one vertex

  // 0.1 - Project ex_Direction on

  // 1- Compute angle between right and direction
  float wDirectionAngle = angle_between_vector(project_vector_on_plane(ex_Direction[0], wPosToCamera), wRight);

  // Lower left corner
  wPos -= (wRight * particle_size/2);
  wPos.y -= particle_size/2;
  wRotatedPos = rotate_vertex_position(wPos - originalPos, wPosToCamera, wDirectionAngle) + originalPos;
  gl_Position = ProjectionView * vec4(wRotatedPos, 1.0);
  TexCoord = vec2(0.0, 0.0);
  EmitVertex();

  // Upper left corner
  wPos.y += particle_size;
  wRotatedPos = rotate_vertex_position(wPos - originalPos, wPosToCamera, wDirectionAngle) + originalPos;
  gl_Position = ProjectionView * vec4(wRotatedPos, 1.0);
  TexCoord = vec2(0.0, 1.0);
  EmitVertex();

  // lower right corner
  wPos.y -= particle_size;
  wPos += wRight * particle_size;
  wRotatedPos = rotate_vertex_position(wPos - originalPos, wPosToCamera, wDirectionAngle) + originalPos;
  gl_Position = ProjectionView * vec4(wRotatedPos, 1.0);
  TexCoord = vec2(1.0, 0.0);
  EmitVertex();

  // Upper right corner
  wPos.y += particle_size;
  wRotatedPos = rotate_vertex_position(wPos - originalPos, wPosToCamera, wDirectionAngle) + originalPos;
  gl_Position = ProjectionView * vec4(wRotatedPos, 1.0);
  TexCoord = vec2(1.0, 1.0);
  EmitVertex();

  EndPrimitive();
}

```

That is pretty much it for the code, I don't really do much else in the vertex and frag shaders... But I can provide them if necessary.

First of all, I draw the particles with quads that I build in the geometry shader from a single point. The quads are built with a `right` and `up` vector a little bit like this tutorial does, mainly for making the quads always face the camera.

Now, I visualize the texture as being aligned with the `right` vector, so I try to compute the angle (`wDirectionAngle`) between this vector and the direction vector of the particle projected on the particle quad. The particle quad being the plane with the normal in the same direction as the *particle\_position-to-camera-vector* "`wPosToCamera`". Finally, I use the `wPosToCamera` as a quaternion vector to rotate my generated quads coordinate around the center of the quad. The rotation around the quaternion and the parameters I use are also heavily inspired on this tutorial.

I've debugged the direction angle and it appears to be correct, although I'm not 100% sure. What could possibly cause this to happen, is there a flaw in the logical process? I couldn't really get any inspiration of similar posts, since they are all about 2D.

**EDIT:**

**tldr;**

ErnieDingo's answer works wonderfully IMO. In my case, I had to swap the parameters for the cross product in order to see the quads. I also used as suggested the up vector coming from the camera and multiplied the vectors by a particle size factor registered as an uniform.

**detailed edit**

Some things I want to say for anyone coming accross this post.

1- Don't use vec3 in an uniform block which can only have std140 definition which rounds up its alignment to vec4 as mentioned here https://www.khronos.org/opengl/wiki/Interface\_Block\_(GLSL)

> Warning: Implementations sometimes get the std140 layout wrong for vec3 components. You are advised to manually pad your structures/arrays out and avoid using vec3 at all. std430: This layout works like std140, except with a few optimizations in the alignment and strides for arrays and structs of scalars and vector elements. Specifically, they are no longer rounded up to a multiple of 16 bytes. So an array of `float`s will match with a C++ array of `float`s. Note that this layout can only be used with shader storage blocks, not uniform blocks.

With a workaround I was able to use the proper upvector in my shader.

2- My workflow was overcomplicated, in fact as mentioned by ErnieDingo the crossproduct of the particle direction and the camera direction is good enough for the quads to always face the camera.

3- Resulting gifs and code

```
//This geometry shader takes points as a
//primitive input and return quads built with
//of triangle strips

#version 430

layout (points) in;
layout (triangle_strip, max_vertices = 4) out;

layout (std140, binding = 0) uniform CameraInfo {
  mat4  ProjectionView; // Projection * View
  vec3  eye;            // camera position
  vec3  target;
  vec3  up_vector;
};

uniform float particle_size;

in  vec4 ex_Color[];
in  vec3 ex_Direction[]; // Only one direction per particle so index is always direction[0]
out vec2 TexCoord;
out vec4 FragColor;

void main(void) {
  vec3 wPos = gl_in[0].gl_Position.xyz;
  vec3 wDirection = ex_Direction[0].xyz;
  vec3 wCameraPlaneNormal = normalize(eye - target);
  vec3 wUp = up_vector;

  float dot = dot(wDirection, wCameraPlaneNormal);
  if (abs(dot) < 1.0f)
  {
    wUp = cross(wCameraPlaneNormal, wDirection);
  }

  wUp = normalize(wUp) * particle_size;
  wDirection *= particle_size;

  FragColor = ex_Color[0]; // Points only have one vertex
  // Lower left corner
  gl_Position = ProjectionView * vec4(wPos + wUp - wDirection, 1.0);
  TexCoord = vec2(0.0, 0.0);
  EmitVertex();

  // Upper left corner
  gl_Position = ProjectionView * vec4(wPos - wUp - wDirection, 1.0);
  TexCoord = vec2(0.0, 1.0);
  EmitVertex();

  // lower right corner
  gl_Position = ProjectionView * vec4(wPos + wUp + wDirection, 1.0);
  TexCoord = vec2(1.0, 0.0);
  EmitVertex();

  // Upper right corner
  gl_Position = ProjectionView * vec4(wPos - wUp + wDirection, 1.0);
  TexCoord = vec2(1.0, 1.0);
  EmitVertex();

  EndPrimitive();
}

```

# Answer
> 2 votes
I've done something similar in my game. So forgive me if my explanation is hazy without diagrams. I take a point and create a quad which is aligned in the direction of the its travel.

But basically as you say, you want to orientate the particle pretty much to the best representation in the direction they are moving. I'm going off my recollections, I may miss a step, but hopefully this just gets your thinking about your solution.

I will list my assumptions here.

* Firstly, you have the camera direction vector available.
* Per particle, you have the direction vector.

So, in 3d world, you need to create a quad aligned along the plane of direction.
So, it can be considered in my example, the left and right of the quad. What you need then is an upvector (could be a downvector depending on cross, but we will use this name). Cross the camera direction Vector with the direction Vector or particle. This gives you a perpendicular vector for both planes, most importantly the direction vector of you particle.

You might need to play with the winding that I have done below.

Edit. Cameradirection is the particle position minus camera position other wise it will not orientate the particle correctly. Sorry!

the pseudo code.

```
direction.normalise()
cameradirection.normalise();

vector3 leftright = direction;

float dot = dot(direction, cameradirection);

vector3 updown = vector3(0,1,0); // just in case the particle is coming at the camera

if (abs(dot) < 1.0f)
{
   updown = cross(direction, cameradirection);
}
Updown.normalise();
// you should multiplye both vectors by 0.5f to ensure you dont have a double size particle.

quadtopleftcorner = position - updown - leftright;
quadtoprightcorner = position - updown + leftright;
quadbottomrighttcorner = position + updown + leftright;
quadbottomleftcorner = position + updown - leftright;

```

This is a variation on something I have done, I hope its a fit for your issue. Good luck.

edit: This is all in world space, so mult by your WVp matrix also.

---
Tags: opengl, c++, 3d, mathematics, glsl
---


# Question
Title: Why do these DirectXMath functions seem like they return column-major matrics?
I know these questions have been asked a million times in various formats, but I'm getting weirdly skeptical about some of the row-major vs. column-major claims about the DirectXMath library.

If I run the following code to get a translation matrix for example:

```
DirectX::XMMATRIX a = DirectX::XMMatrixTranslation(1.0f, 1.0f, -1.0f));

```

I would expect the memory layout to look like the following (with rN indicating some row, but all the numbers contiguously in memory):

```
r1: 1.0   0.0   0.0   1.0      r2: 0.0   1.0   0.0   1.0     r3: 0.0   0.0   1.0  -1.0     r4: 0.0   0.0   0.0   1.0

```

This would correspond to the following matrix (in standard notation) where each *row* is stored as a contiguous array:

```
1.0   0.0   0.0   1.0
0.0   1.0   0.0   1.0
0.0   0.0   1.0  -1.0
0.0   0.0   0.0   1.0

```

Except when I look at the memory, it's the transpose of the above (i.e. the last *array* in memory is the last *column* above) which I'm to understand is "column-major" order. So, in memory, what I'm actually getting is this:

```
r1: 1.0   0.0   0.0   0.0     r2: 0.0   1.0   0.0   0.0     r3: 0.0   0.0   1.0   0.0     r4: 1.0   1.0   -1.0   1.0

```

This leaves me thoroughly confused with all the commentary and documentation around DirectXMath matrices needing to be transposed before putting them into HLSL constant buffers (of which I'm using the default column-major order). Everything states that DirectXMath matrices are stored in row-major order, but when I actually look at the memory (either as an `XMMATRIX` or a more direct `XMFLOAT4X4`) I find myself staring at a translation matrix that looks like it's been stored in column-major order.

So my confusion then lies in the fact that my transformations actually work when I *don't* transpose the matrices prior to putting them into the constant buffer.

Am I missing something here?

# Answer
> 3 votes
You posted a column-major version of the translation matrix for (1,1,-1):

```
1.0   0.0   0.0   1.0
0.0   1.0   0.0   1.0
0.0   0.0   1.0  -1.0
0.0   0.0   0.0   1.0

```

The row-major version is:

```
1.0   0.0   0.0   0.0 [r0]
0.0   1.0   0.0   0.0 [r1]
0.0   0.0   1.0   0.0 [r2]
1.0   1.0  -1.0   1.0 [r3]

```

Which is precisely what you see in `XMMATRIX`.

As noted in the DirectXMath Programmer's Guide:

> DirectXMath uses row-major matrices, row vectors, and pre-multiplication. Handedness is determined by which function version is used (RH vs. LH), otherwise the function works with either left-handed or right-handed view coordinates.
>
> For reference, Direct3D has historically used left-handed coordinate system, row-major matrices, row vectors, and pre-multiplication. Modern Direct3D does not have a strong requirement for left vs. right-handed coordinates, and typically HLSL shaders default to consuming column-major matrices. See HLSL Matrix Ordering for details.

See also DirectXMath GitHub.

---
Tags: directx, directx11, hlsl, matrix
---


# Question
Title: Why is my model rotating opposite direction around the Y axis?
I have a simple scenario. I have a simple scene, and in it I'm drawing a grid and a model, with some axis for orientation.

I noticed when I rotate the model about it's local Y axis, if I rotate the model clockwise, the vertices end up rendering as if they've been rotated counterclockwise. I can see this by rendering the model's local forward vector.

Here's a picture of what I mean. Initially, the world forward, local forward, and model all face the same direction.

However, after I begin rotating the object clockwise, I notice the "world forward vector" is rotating clockwise, but my model rotates counterclockwise?

When I export the model from Blender3D I use the coordinate system "Forward: -Z" and "UP: Y Up", which matches the RHS coordinate system I'm using in opengl.

When I "rotate the object", I mean I multiply the object's rotation matrix like so:

```
float constexpr angle = 1.0f;
glm::vec3 const axis = glm::vec3{0.0, 1.0, 0.0};
object.rotation = glm::angleAxis(glm::radians(angle), axis) * object.rotation;

```

Here's my vertex shader, I'm just multiplying the vertices by the MVP matrix.

vertex shader:

```
in vec4 a_position;
in vec4 a_color;

out vec4 v_color;

uniform mat4 u_mvpmatrix;

void main()
{
  gl_Position = u_mvpmatrix * a_position;
  v_color = a_color;
}

```

The rotation object.rotation 's initial value is the quaternion identity. Here's how I calculate the MVP matrix uniform value:

```
glm::mat4 const tmatrix = glm::translate(glm::mat4{}, this->translation);
glm::mat4 const rmatrix = glm::toMat4(this->rotation);
glm::mat4 const smatrix = glm::scale(glm::mat4{}, this->scale);
glm::mat4 const model_matrix = tmatrix * rmatrix * smatrix;

// camera_xyz are world-coords for the camera
// target_xyz is world-coords of the object
glm::vec3 const UP = glm::vec3{0.0f, 1.0f, 0.0f};
glm::mat4 const view = glm::lookAt(camera_xyz, target_xyz, UP);
glm::mat4 const projection = glm::perspective(fov, aspect_ratio, near, far);
glm::mat4 const mvp_matrix = projection * view * model_matrix;

```

Other relavent calculations:

```
glm::vec3 eye_forward() const { return forward_; }
glm::vec3 eye_up() const { return up_; }
glm::vec3 eye_backward() const { return -eye_forward(); }

glm::vec3 eye_left() const { return -eye_right(); }
glm::vec3 eye_right() const { return glm::normalize(glm::cross(eye_forward(), eye_up())); }
glm::vec3 eye_down() const { return -eye_up(); }

glm::vec3 world_forward() const { return forward_ * orientation(); }
glm::vec3 world_up() const { return up_ * orientation(); }
glm::vec3 world_backward() const { return -world_forward(); }

glm::vec3 world_left() const { return -world_right(); }
glm::vec3 world_right() const { return glm::normalize(glm::cross(world_forward(), world_up())); }
glm::vec3 world_down() const { return -world_up(); }

```

From what I can tell, it seems like I'm doing everything right. Can someone explain it to me? I also have a video showing this in more detail. This is important, because I move the object "forward" based on it's forward vector, so when I rotate the object and move it "forward" it's not moving in the direction it is facing.

edit: Am I calculating the "local forward" correctly with this calculation?

double edit: I just noticed I labeled the "World" and "Object space" vectors backwards. The green arrow is the World forward vector (0, 0, -1) and the light blue is the object's local forward vector.

```
// forward_ is initialized with -Z (0.0, 0.0, -1.0)
glm::vec3 world_forward() const { return forward_ * orientation();
glm::quat const& orientation() const { return object.rotation; }

```

# Answer
> 1 votes
Using the righthand rule -- rotation about the y-axis with a positive angle will rotate your model counterclockwise in the x-z plane. That is how rotation is defined in opengl. You need a negative angle.

---
Tags: opengl, rotation, quaternion, obj
---


# Question
Title: How do I colorize a texture with libGDX?
I'm working on a libGDX implementation for my library which draws ASCII tiles to create a text GUI. My current Swing + `BufferedImage` implementation looks like this:

This works by copying parts of a grayscale texture which has CP437 characters on it and transforming them by adding color to each pixel.

My problem is that my libGDX implementation does not work for some reason:

What I have tried is this:

```
    val backend: TextureRegion = region.getBackend()

    val texture = backend.texture
    if (!texture.textureData.isPrepared) {
        texture.textureData.prepare()
    }
    val pixmap = texture.textureData.consumePixmap()
    (0 until backend.regionWidth).forEach { x ->
        (0 until backend.regionHeight).forEach { y ->
            val color = Color(pixmap.getPixel(backend.regionX + x, backend.regionY + y))

            val ax = color.a
            var rx = color.r
            var gx = color.g
            var bx = color.b
            rx *= r
            gx *= g
            bx *= b
            if (ax < 50) {
                pixmap.drawPixel(backend.regionX + x, backend.regionY + y, textCharacter.getBackgroundColor().toAWTColor().rgb)
            } else {
                pixmap.drawPixel(backend.regionX + x, backend.regionY + y, Color(rx, gx, bx, ax).toIntBits())
            }
        }
    }

    return region

```

I know that I am missing something but I just can't figure out what the problem is here. I've tried with various options like copying the `TextureRegion` but I can't get this to work.

My other implementation uses `BufferedImage`s and it just works:

```
    val r = textCharacter.getForegroundColor().getRed().toFloat() / 255
    val g = textCharacter.getForegroundColor().getGreen().toFloat() / 255
    val b = textCharacter.getForegroundColor().getBlue().toFloat() / 255

    val backend: BufferedImage = region.getBackend()
    (0 until backend.width).forEach { x ->
        (0 until backend.height).forEach { y ->
            val ax = backend.colorModel.getAlpha(backend.raster.getDataElements(x, y, null))
            var rx = backend.colorModel.getRed(backend.raster.getDataElements(x, y, null))
            var gx = backend.colorModel.getGreen(backend.raster.getDataElements(x, y, null))
            var bx = backend.colorModel.getBlue(backend.raster.getDataElements(x, y, null))
            rx = (rx * r).toInt()
            gx = (gx * g).toInt()
            bx = (bx * b).toInt()
            if (ax < 50) {
                backend.setRGB(x, y, textCharacter.getBackgroundColor().toAWTColor().rgb)
            } else {
                backend.setRGB(x, y, (ax shl 24) or (rx shl 16) or (gx shl 8) or (bx shl 0))
            }
        }
    }
    return region

```

What am I doing wrong?

# Answer
Color.toIntBits returns ABGR format. Pixmap.drawPixel takes rgba8888

https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/Pixmap.html#drawPixel-int-int-int- https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/Color.html#toIntBits--

Use Color.rgba8888(color) instead.
> 1 votes

---
Tags: opengl, libgdx, textures
---


# Question
Title: Finding the components of Proportional Navigation in 2D
So, I've been scouring this, the Physics Exchange, Wikipedia, and the general web for information about Proportional Navigation, and I can't seem to wrap my head around how to find the individual terms that make up a PN equation, especially in a 2D environment.

Per Wikipedia:

a = N * lambda * V

Where:

a is the normal acceleration, that's fine. It's how much I should accelerate left or right from the missile's current heading.

N is a scaling factor. Sure. No problem there. Just fiddle with it.

lambda is the line of sight rate... What? It's how much the angle between the missile's heading and the position of the target change in an instant? Or something? Given the position and velocity of the target, and the position and velocity of the missile, I feel like this should be easy to figure out instantaneously, without having to 'save' the previous position of the target, but for the life of me I can't wrap my head around it.

V is the closing velocity. That's how fast I want to be going when I reach the target? Yes? Or is it the component of my velocity in the direction of the target? There's not much explaining this term that I can see.

Wikipedia offers another variation of the equation that involves the cross product, which I don't think works in this situation, since the cross product is explicitly 3D.

Wikipedia Article

Related Questions:

Implementing simple proportional navigation for a homing missile

How to Create an Intercept Missile for a Game

Calculating vector to aim for moving asteroid (3D asteroid game)

# Answer
Few things, according to your wikipedia question, a is actually the perpendicular force, presumably the orthogonal force in N dimensional space. N is a constant, sure, but lambda must be calculated via previous frame versus current frame, or the *predicted next position of the target*. You don't need to keep the previous value if you predict where the target will go. You need the targets velocity any way, so you'll have this information any how.

V, closing velocity is not "how fast I want to be going when I reach the target" though I admit, its not exactly easy to find these terms defined, they are constantly overloaded. I believe closing velocity here is describing the velocity formed by the frame of reference caused by both the moving target and the missile. In the case of the static target, the closing velocity will simply be the velocity (or negated depending on order of missile or target in calculations) of the missile if the missile is moving directly towards the target.

Based upon this forum post http://mathhelpboards.com/calculus-10/calculate-closing-velocities-19402.html closing velocity can be computed in the following way:

Given `V1` = velocity of the missile, `V2` = velocity of the target, `P1` = position of missile, `P2` = position of the target.

`Vclosing = dot((V2 - V1),(P2 - P1)) * (( P2 - P1) / Magnitude(P2 - P1)^2)`

`SpeedClosing = dot((V2 - V1),(P2 - P1))/ Magnitude(P2 - P1)`

> Wikipedia offers another variation of the equation that involves the cross product, which I don't think works in this situation, since the cross product is explicitly 3D.

This is a fundamental misunderstanding of the cross product. The cross product measures the *difference* between vectors, much like the dot product measures the *similarity* between vectors. This difference is represented by a magnitude and a vector orthogonal to the plane represented by the two vectors, which is not restricted to any specific N dimensional space. If the cross product produced a N+1 vector as our output, and that turned out to be impossible to use for our equations, the formula itself would be wrong.

To compute the cross product version, we have new terms, Vr, which is actually the difference between the target velocity and the missile velocity, R, which is the Range vector from missile to target, Omega, the "rotation vector of line of site" which is `cross(R, Vr)/dot(R,R)`. The final formula expanded would be:

```
// target velocity relative to missile
vec2 Vr = Vt - Vm;
// range from missile to target
vec2 R = Rt - Rm;
//some constant
float N = ...;
//rotation vector of line of sight
vec3 Omega = cross(R, Vr)/dot(R,R);

// the cross product of orthogonal vector to R and Vr from previous cross
// product, and Vr again, will produce vector which lies on the plane of R
// and Vr again, hence we can ignore the last dimension of the cross product
// it will be zero anyway for 2d.
vec2 a = N*cross(Vr, Omega);

```

You'll see that because we perform two cross products that both involve a vector that lies on the plane Vr, R, we will end up with a vector in the appropriate dimension for a, even in 2D.
> 1 votes

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