# Question
Title: Estimated cost of calling glAttachShader() and glUseProgram()
My program doesn't contain many vertices (about 200 vertices total, and all are animated), and I was wondering if it would be worth it to create two different sets of fragment and vertex shaders -- one for vertices that all share a color, and another for vertices that all have different colors. The problem is that I can't determine whether or not this would be a good idea if I have no idea what the typical cost off glAttachShader() and alUseProgram() is across devices. I know that the program I'm using currently practically doesn't use the GPU, but I find that this information is still very useful to know (and why not optimize anyways?).

# Answer
> 1 votes
> (and why not optimize anyways?)

Because when you actually have a performance issue, the answer is going to depend on the specifics of the situation. So premature optimization could lead you to the wrong answer.

But generally speaking, re-compiling shader programs is very slow. Switching shaders is also slow. For your situation, I'd guess that using a single shader would be almost guaranteed to be faster.

# Answer
> 0 votes
I profiled the efficiency of glUseProgram() by calling it multiple times in a loop, while drawing about 24 vertices (that each use 2 draw calls, in order to see if lag occurs) per frame.

I then ran the program with varying numbers of glUseProgram() calls per frame until I got a number that visibly produced occasional lag in drawing. I then subtracted 5,000 from this number (getting 75,000), in order to make sure that I was not missing any millisecond-long lag spikes (I repeated multiple times with that number of calls to make sure that the number I got was not just due to some random CPU speed-up), and deemed this to be the number of glUseProgramCalls() in a frame in order for the time of all the calls put together to take longer than a sixtieth of a second (which I'm guessing was the frame rate).

I was not multithreading and the speed of the phone gpu I was using was 1.4GHz. I divided 1.4 by 60 to get 23,333,333.3333 clock cycles per frame (or sixtieth of a second), and then divided that number by 75,000, to get (roughly) 311.1111 clock cycles per glUseProgram() call. What's even more astonishing is that 75,000 calls to glUniform(this, specifically: glUniform2fv(translateHandle, 1, (const GLfloat\[2\]) { .0F, .0F }) actually caused a considerable amount of lag (significantly more lag than even calling glUseProgram 90,000 times per frame).

I used an ASUS Zenfone 3 for this test, so this applies to recent devices.

---
Tags: opengl-es2
---


# Question
Title: Why when getting the waypoints objects in script the order in the array is not the same as in the hierarchy?
At the top

```
public GameObject[] waypoints;

```

In Start

```
void Start()
    {
        waypoints = GameObject.FindGameObjectsWithTag("Waypoint");
    }

```

In the Hierarchy i have 5 Spheres: In this order:

But when using a break point i see in the variable waypoints:

Why when getting the waypoints in the script they are not in the same order ?

# Answer
The scene hierarchy can be reordered by dragging things around. However the *default* ordering (the order in which the objects were created) still applies.

The `GameObject.FindGameObjectsWithTag()` method makes no claims about what order the objects *should* or *will* be returned in. Presumably the order of instantiation (or even possibly, the order in which they exist in memory, or god forbid, *randomly*) is the order of the array when that function returns.

Your only solution is to sort the array after you get it.
> 7 votes

# Answer
If we need to sort by name for example array of GameObject:

```
GameObject[] waypoints = GameObject.FindGameObjectsWithTag("Waypoint").OrderBy(go => go.name).ToArray();

```

The result will be: Sphere , Sphere (1) , Sphere (2)

Then if we want to reverse the array after sorted: We add the line:

```
Array.Reverse(waypoints);

```

The result: Sphere (2) , Sphere (1) , Sphere

If we have array of int or float for example:

```
    float[] test = new float[5];
    test[0] = 1f;
    test[1] = 2.5f;
    test[2] = 1.1f;
    test[3] = 0.5656f;
    test[4] = 66f;

    Array.Sort(test);
    Array.Reverse(test);

```
> 3 votes

# Answer
As mentioned on this page the order of objects returned from `FindGameObjectsWithTag` is unspecified, so you can't rely on it returning objects in any specific order.

You could manually set the waypoints to the array in the inspector, or sort them by their waypoint index after getting them with `FindGameObjectsWithTag`.
> 1 votes

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


title: Screen objects sometimes not rendering

text:
# Question
Title: Screen objects sometimes not rendering
I am a mildly experienced programmer who has created several game engine templates and small 2D games in Java. I am currently expanding to 3D game engines and I am re-writing a previous engine to be more adaptive and Object-oriented.

My issue is, and has been periodically, that the objects are only sometimes rendered. This causes me to have to constantly re-run the program just to display any images.

I have not found any direct answers to this question, and nobody else seems to have this same issue (even when observing sources with the exact same code setup). The problem apparently lies within the render() method sometimes not properly creating or utilizing the Graphics & BufferStrategy objects while inside a thread called from the main method.

Here is some code of the 'Main' class:

```
public Main() {
    addScreenAndFrame();
}

public static void main(String[] args) {
     main = new Main();
     frame.add(main);
     thread =

new Thread(main);
         running = true;
         thread.start();
     }
public void run() {
    while (running) {
        render();
        tick();
    }
}
public void tick() {
    screen.tick();
}
public void render() {
    bs = getBufferStrategy();
    if (bs == null) {
        createBufferStrategy(3);
        return;
    }
    g = bs.getDrawGraphics();
    screen.paintComponent(g);
    g.dispose();
    bs.show();
}

```

Here is some code from the Screen class:

```
public Screen(int width, int height) {
    this.width = width;
    this.height = height;
    addEntities();
}
public void paintComponent(Graphics g) {
    p.render(g);
}
public void tick() {
    KeyInput.tick();
    renderInput();
}
public void addEntities() {
    p = new PolygonObject(new double[] {50,200,50}, new double[] {50,200, 200} );
}

```

And finally here is the PolygonObject class:

```
    public PolygonObject(double x[], double y[]) {
        Screen.polygonSize ++;
        polygon = new Polygon();
        for (int i=0; i < x.length; i++) {
            polygon.addPoint((int)x[i], (int)y[i]);
        }
    }
    public void render(Graphics g) {
        g.fillPolygon(polygon);
        g.setColor(Color.black);
        g.drawPolygon(polygon);
    }

```

I don't know why calling `render()` while within a thread would yield inconsistent results when drawing images to the screen. I have seen many source codes for game templates and tutorials with the exact same code without any rendering issues. The only way rendering works consistently is when I draw images with the paintComponent() method of the Canvas class outside of a thread which limits my program functionality and is poor design of a game engine.

I would like an explanation of this and any possible solutions. There is NO accurate way for me to build the game engine without the use of a thread in order to have controlled time-based functionality.

# Answer
> 1 votes
The `run()` method called by the 3rd thread was unstable and sometimes did not properly construct each object due to encapsulation issues.

I have removed the extra thread and have re-structured the engine to do all rendering within the JPanel's `paintComponent()` method in the `Screen` class. The `Main` class has been re-structured to only create the frame then add the `Screen` and `KeyInput` objects to the frame while managing the game logic and input.

The engine now renders with 100% success and all objects work as they should.

---
Tags: java, graphics, game-loop
---


title: Collision detection in SFML

text:
# Question
Title: Collision detection in SFML
I am building a simple 2D game with SFML and have a GameState object that contains a Plane and a vector of Enemies. THe plane is represented by a triangle and the enemies by a rectangle. The plane object has bullets and I am wondering what is the most appropriate way of handling collision between the bullets and the enemies. The structure of the code is the following :

```
 GameState
    /\
   /  \
Plane Enemies
  /
Bullets

```

Every object has **Render** and **Update** and possibly **HandleInput** methods. The way I think that this could work is if I pass the enemies vector to the plane's update method which in turn calls the bullets update method and there I do the check. Is this ok ? Is there an easier and more solid method of doing it ?

# Answer
If you're making a basic game, passing in the vector of bullets to the enemies isn't a huge problem. Is it particularly nice? I don't think so. This is the kind of issue that will scale with the complexity of the game.

Using the KISS approach, I think the best way you could solve this would be to implement a collide() method in which the actor/entity/gameobject can test its collision against another actor/entity/gameobject. Using this, you could iterate over them inside of your GameStates update(). Something like...

```
    // for every enemy, test against every bullet..
    for(auto enemy : _enemies) {
        for(auto bullet : _bullets) {
            if(enemy->collides(bullet)) {
                // handle behaviour..
            }
        }
    }

```

In terms of performance, this will scale badly depending on how many enemies and bullets you have.. but at least the logic will be in the GameState (where it should be), and not inside of an entity.

This approach is not wonderful practice, but it'll work. If you'd like to look into more complex collision systems then have a look into Box2D, or try making one yourself using quadtrees/spatial partitioning. The latter is, of course, more complicated.
> 0 votes

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


# Question
Title: Modifying Alpha in Unity Standard Shader
I'm trying to create a shader in Unity with a slider that can adjust the transparency. (This is the first step toward something more sophisticated.) I try to do this by setting the alpha of the SurfaceOutputStandard struct to the texture alpha times a value between 0 and 1:

```
Shader "Custom/MakeVisible" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _TransparencyMult ("Transparency Mulitplier", Range(0,1)) = 1
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
    }
    SubShader {
        Tags { "RenderType"="Transparent" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;
        half _TransparencyMult;

        UNITY_INSTANCING_CBUFFER_START(Props)
        UNITY_INSTANCING_CBUFFER_END

        void surf (Input IN, inout SurfaceOutputStandard o) {
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;

            //Multiply alpha by value between 0 and 1
            o.Alpha = c.a * _TransparencyMult;
        }
        ENDCG
    }
}

```

This seems like it should work, since Alpha is an available property. But it doesn't. Here's a screenshot:

**EDIT:**

I realized after reading closer that I needed to add the alpha:fade parameter for that to work, however, when I add that it is always transparent no matter what:

**EDIT:** I changed the shader code according to Draco's answer:

```
Shader "Custom/MakeVisible" {
    Properties{
        _Color("Color", Color) = (1,1,1,1)
        _TransparencyMult("Transparency Mulitplier", Range(0,1)) = 1
        _MainTex("Albedo (RGB)", 2D) = "white" {}
        _Glossiness("Smoothness", Range(0,1)) = 0.5
        _Metallic("Metallic", Range(0,1)) = 0.0
    }
    SubShader {
        Tags {
            "IgnoreProjector" = "True"
            "RenderType" = "Transparent"
            "Queue" = "Transparent"
        }
        LOD 200
        Blend SrcAlpha OneMinusSrcAlpha
        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows alpha
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;
        half _TransparencyMult;

        UNITY_INSTANCING_CBUFFER_START(Props)
        UNITY_INSTANCING_CBUFFER_END

        void surf(Input IN, inout SurfaceOutputStandard o) {
            fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;

            //Multiply alpha by value between 0 and 1
            o.Alpha = c.a * _TransparencyMult;
        }
        ENDCG
    }
}

```

Now it is always the same transparency with no texture:

# Answer
You need to make 3 small changes to your shader:

1. You need to have the Queue properly set to Transparent or it won't render at all:

```
Tags{
    "IgnoreProjector" = "True"
    "RenderType" = "Transparent"
    "Queue" = "Transparent"
}

```
2. You need to set up a Blend Mode (this goes in the same place as Tags and LOD), if left out, this will be assumed (there are other blend modes):

```
Blend SrcAlpha OneMinusSrcAlpha

```
3. You need to include the #pragma alpha in the #pragma declaration, this is what allows the alpha value to mean something:

```
#pragma surface surf Standard fullforwardshadows alpha

```
> 2 votes

---
Tags: unity, shaders, cg, alpha
---


# Question
Title: How to stop an anmation and a loop in relation to a timer? Phaser javascript
I am not ajavascript or phaser expert, I just got stuck with this problem. I'll try to explain it. In this game; is a 21 second timer in all this: which starts AFTER a beginning 3 second animatiton.

```
var maxTime = 21; //in SECOND

```

There is a wheel (station) that spins over and over (loops) and scales up and down:

```
var init_station_scale = 0.5;
var scale_station = 0.40;

```

When the game resets the station (wheel) resets

```
function resetGame(){

station.scale.setTo(init_station_scale);

//station(middle anchor point).

  station = game.add.sprite(750,195,"station");
  station.anchor.setTo(.75,.75);
  station.scale.setTo(init_station_scale);
  station.animations.add("anim"); //Init animations
  station.animations.play("anim",15,true);  //play Animations "anim" with 30fps, loop true

```

Not to confuse you, but there is a lot going on in this 21 seconds, such as:

//hint (this is hooked up with the station (wheel)

```
      hint = game.add.sprite(game.world.centerX+50,game.world.centerY+100,"hint");
  hint.anchor.setTo(0.5);
  hint.animations.add("anim");
  hint.animations.play("anim",15,true);
  hint.visible = false;

```

Playing a 3 second animation that only plays once at the very beginning of the game (including if game resets); also starting .play ("anim",15, true); //(above (station/wheel) code and looping it)

after that 3 second animation; console.log("FINISH ANIMATION and ADD TIMER"); TIMER is referring to the 21 second timer

```
timerEvent = game.time.events.add(Phaser.Timer.SECOND * maxTime,  moveToEndGame, this);  //(also the 21 second timer)

function moveToEndGame(){
  console.log("TIMER END");
  var twn = game.add.tween(bg).to({alpha:0},tween_speed,"Linear",true);
  twn.onComplete.addOnce(function(){flagGameover = true;},this);
}

 if(!flagGameover && !star.visible && idx_bullet < bullet_array.length)
        initBullet();
      else{
        if(flagGameover){
          console.log("GOTO GAMEOVER");
          window.location = "../EndGame.html";
        }
      }
    }

  }

```

Everything works up until the end of the 21 second timer, but station/wheel keeps spinning creating an 'infinite loop" So there is nothing to stop the 'loop in the station" after the 21 second timer finishes. Coder left out a line that would do that? Some line of code needs to be added to that last block of code (or somewhere else?)to stop the loop on the station timed with the end of the 21 second timer. I think????

Or some kind of javascript kill switch: i.e. stop all javascript then go to endgame.html

Anyone know the answer?

# Answer
I found out what it was.

It was missing a callover, as in:

```
var callGameover = false;

```

and......

```
  if(flagGameover){
      if(callGameover == false){
        callGameover = true;
         console.log("GOTO GAMEOVER");
         window.location = "endgame.html";

```

I didn't know that was enough to cause an "infinite loop" but apparently it was. Put the above in and loop gone!
> 1 votes

---
Tags: javascript, timer
---


# Question
Title: Can I create custom framebuffer and render to it in cocos2dx?
I want to do post processing effects so I was thinking If I could just make custom framebuffer in cocos2dx like OpenGL and render the ALL SCENES objects in it. I want a single frame buffer for all scenes. Is there any way? Thanks.

# Answer
Here is some theory and practise on framebuffers:https://learnopengl.com/#!Advanced-OpenGL/Framebuffers it also explaines how to implement some very simple post-processing effects
> 2 votes

# Answer
Framebuffers will be your friend. You can create as many as you wish with `glCreateFramebuffers()`. Here is a documentation page, which lists all the handy functions for doing that in "raw" OpenGL.

cocos2d has the `RenderTexture` class, which will fit also your needs.
> 0 votes

---
Tags: opengl, c++, cocos2d-x, frame-buffer
---


# Question
Title: How do I reload an object back to its original state?
I have a game where a wall is destroyed. I would like to click a button to reload the wall back to its initial state. I have only managed to reload the scene, using `Application.LoadLevel(Application.loadedLevel))`, but it takes to long.

How do I reload an object back to its original state?

# Answer
> 1 votes
I assume you have an object in your hierarchy called "wall" with all of your bricks as children of this gameobject. I also think you are not going to move this gameobject at runtime since it is a wall. You could solve this problem by taking the "wall" gameobject as a parameter in a script. Now you could access all the children via that script, create a Vector3\[\] called something like "positions" and another array for the gameobjects. Now you assign the gameobjects.tranform.position\[i\] = positions\[i\]; (the code is not tested). Basically you make a "backup" of all the cube positions, in order to reset them when you press the button. You can see a similar example here, it's made by Brackeys(https://youtu.be/eqlHpPzS22U)

# Answer
> 0 votes
I solved it so: I was able to remove all the pieces of the wall. And I want to insert a new, ready wall on the scene. How can I put a ready-made object on the scene during the runtime?

---
Tags: unity
---


# Question
Title: glVertexAttribPointer alters completely different shader program
My program contains two shader programs in it. The following code is for preparing one of the shader program's attributes:

```
int positionHandle2 = glGetAttribLocation(programAColorUTranslate, "vPosition");
glEnableVertexAttribArray(positionHandle2);
glVertexAttribPointer(positionHandle2, 2, GL_FLOAT, GL_TRUE, 2 * sizeof(float), 0);
translateHandleAColorUTranslate = glGetUniformLocation(programAColorUTranslate, "vTranslate");

int aColorHandle = glGetAttribLocation(programAColorUTranslate, "aColor");
glEnableVertexAttribArray(aColorHandle);
/*glVertexAttribPointer(aColorHandle, 3, GL_FLOAT, GL_TRUE, 5 * sizeof(float), 0);*/

```

At this point, the program works fine, except that the vertices drawn by the above shader program are not colored, since the line above is commented out. However, if I uncomment the line above (and change the stride of position handle to 5 * sizeof(float)) to try to add colors to the above shader program's vertices, random shapes appear in my program. Supposedly, the above line should only alter triangles rendered by one of the shader programs, not both. However, every single vertex in my program is being rendered incorrectly after uncommenting the about line, to the point that the program becomes unrecognizable from before.

# Answer
In OpenGL ES 2.0 a program object does not contain the vertex array state (which you are modifying in your question). That data is global, so it applies to whatever the current program is. The program object does have state that controls which attributes are active (but note this is not the state that `glEnableVertexAttribArray` is modifying), and the size/type/etc of the attributes, but not the state that controls what data is bound to them.

For details on exactly what state is covered under a particular GL object, see section 6.2 *State Tables* in the ES 2.0 spec. Anything not listed in a table for *X Object State* is global state. Specifically in this case, see Tables 6.2 *Vertex Array Data* and 6.15 *Program Object State*.
> 2 votes

---
Tags: opengl-es2
---


# Question
Title: Direction between objects (shortest distance around sphere)
I have two objects rotating around a sphere. One is controlled by the user (object A), another is simulating a user but controlled by the computer (object B). At random intervals of time I'd like object B to start moving towards object A.

I can get this to work using this formula to determine the movement direction between two points:

```
public Vector3 DirectionTowards(Vector3 from, Vector3 to)
{
    return (to - from).normalized;
}

```

This gives me a normalized direction vector to update the x/y movement with. Since this is momentum based, if the objects need to move in an opposite direction I update their movement direction vector like so: (notice the "+=" instead of just "=" to give the effect of momentum/acceleration, more on this below)

```
// This code runs when  I need to move object B toward object A
var newDirection = DirectionTowards(transform.position, target.transform.position);
xMove = newDirection.x;
yMove = newDirection.y;

...

// This code runs in my update method
_moveVector.x += xMove * _acceleration;
_moveVector.y += yMove * _acceleration;

```

The problem I'm having is that when the objects are at opposite sides of the sphere, sometimes object B will start moving in the direction that is not the shortest distance to object A. Is there a way I can determine the direction in a similar way, but force it to choose the shortest distance around the sphere?

Also, to go along with this. By using "+=" vs "=" when I update the `_moveVector` sometimes that causes the direction to get changed slightly because it does an arc as it slows down its momentum before moving in the new direction. Does anyone know why that might be, or if I'm doing that incorrectly? Basically object B will start moving "almost" in the right direction due to this, but eventually after a while the whole things gets screwed up. If I use "=" only, this works perfectly every time except for the issue of shortest distance as I mentioned above.

Thanks! Let me know if any other information is needed.

# Answer
> 2 votes
A few issues come to mind as I read this:

1. Your movement is on the surface of a sphere, so travel direction should be a tangent to this surface, not just a (to-from) normalized, as that would point into the sphere.
2. You mention acceleration and movement, but nowhere "velocity" or "speed." Use standardized terms, to make your intentions and code clearer. I think you call it moveVector instead? Just use acceleration, velocity, position, as a physicist would. Force changes Acceleration. Acceleration changes Velocity, Velocity changes Position.

To address (1): the computation of your Acceleration needs to be a tangent to the sphere. You can use something like this:

```
targetdir = targetpos - position;
surfacenormal = position.normalized();
crossed = z.crossProd( x );
crossed.normalize();
traveldir = crossed.crossProd( surfacenormal );

```

Now you have a travel direction to where you can steer towards. We use this to accelerate (or push) your object towards. A fancy way would be to now use PID controller for steering by setting forces/acceleration, but we can make it easy by just interpolating the current velocity and the traveldir, which is a desired velocity.

```
s = 3 * dt; // higher values for less momentum.
t = 1 - s;
velocity = t * velocity + s * traveldir;
position = position + dt * traveldir;

```

---
Tags: unity, vector, sphere, direction, orbit
---


# Question
Title: Process for converting unity asset to scenekit scene/resource
Has anyone successfully figured out a method for converting a unity3d asset to a 3d SceneKit model/scene? I imagine it would require exporting the asset into some third party file type, and then importing into scene kit. If you have any knowledge that can help me, would you kindly explain the process?

Unity3d has a fantastic asset store, and I want to import some of these things to a project that requires scenekit (unfortunately, "just use unity" is not really an answer to my problem-set).

# Answer
> 1 votes
Sounds like you need the Collada exporter which you can find on the Unity Asset Store to convert your models and scenes to .dae format for importing into SceneKit. There is one exporter for Unity 5.x and one for Unity 2017.

---
Tags: unity, scenekit
---


title: One Giant Shader VS Many Small Shaders

text:
# Question
Title: One Giant Shader VS Many Small Shaders
I am building forward rendering engine combined with atlas shadow map technique.

My goal is to build an engine that is capable of rendering similar scenes from games such as.. Doom  Overwatch

So I wonder, do I need to write one giant shader that does all? or do I have many different shaders for each different materials?

# Answer
> 2 votes
Counting the shaders in my current application, there are 90 of which 37 perform screen rendering. The rest perform preparation of various tasks for those 37 shaders, or execute GPGPU. Practically all shaders are invoked during application run, a little bit depending on situation.

I don't see any great advantage with doing the screen render with such an ubershader. The only advantage would imho be enforcing strictness in the architecture and hardware usage, by intentionally limiting. This may be a good thing under certain circumstances, where such strictness is needed.

Such a shader may perform faster because of it's strictness, but today's hardware + (graphics drivers, OS) should gain little from it. Branching by sent-in boolean in the shader is fast but so is shader-switching and branching by calculation result or even texture lookup inside the shader. After all, we talk about hugely minor time slices.

Imho, the reasons for using such an ubershader are more architecture- and development policy-related than performance- and visual quality-related. It is probably the last thing i would personally go for, as I am usually worried about painting myself into a corner. To me, an ubershader sounds like a nightmare.

This doesn't mean that there should be a separate shader for every single bit. One shader takes care of something that not any other shader takes care of, or something coming from a time and space mismatch with other shaders.

---
Tags: shaders, graphics, software-engineering, graphics-programming
---


# Question
Title: 2D Lighting Problem with Black Backgrounds
I'm currently experimenting with simple lighting in my game made with SFML and C++ (though I don't think that's relevant to the question). It's my first time messing with lighting in 2D, and my basic system is to:

1. Create a lightmap
2. Every frame, clear the lightmap and add all lights back to it (they move).
3. Every frame, draw the lightmap to the window on top of the game and multiply the colors from both textures (the game texture and the lightmap texture). In SFML I do this by:

`window.draw(lightMap, sf::BlendMultiply);`

My issue is that my lights don't show up against a black background, which doesn't seem to make sense. It's as if that specific color (and colors close to it) just can't be illuminated. Is this because of how color multiplication works? If so, is there a workaround?

Thanks!

# Answer
> 1 votes
Yes, Black has a value of 0 for all color components, and your use of `BlendMultiply` means that anything multiplied by 0 is still 0. Try using a different blend mode -- Additive Blending tends to look reasonable for glow effects like these.

---
Tags: c++, 2d, lighting, sfml, lightmap
---


# Question
Title: Unity - Sprite disappears completely when just a part of it is outside the camera's FOV
I'm making a game in Unity, and when the player walks past a sprite, the sprite disappears, and when the player walks back toward it, it reappears. You can see a video of the problem here https://www.youtube.com/watch?v=jgLN3m94tBo

I've also included my camera script below if anyone wants to check that out. Any help on this matter would be more than appreciated.

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

public class Camera : MonoBehaviour {

private Transform target;

private float minX = 7.99f;
private float minY = -19.09f;

public float maxX, maxY;

void Start()
{
    target = GameObject.Find("Player").transform;
}

void LateUpdate()
{

    transform.position = new Vector3(Mathf.Clamp(target.position.x, minX, maxX), Mathf.Clamp(target.position.y, minY, maxY), transform.position.z);
}
}

```

Here's a screenshot of my camera's settings

# Answer
It seems that the issue had to do with a plugin I was using to import my .tmx file into Unity. I switched to Tiled2Unity and the problem no longer persists.
> 0 votes

---
Tags: unity, sprites, camera, frustum-culling
---


# Question
Title: How to make OpenGL rendering resolution independent from its window context resolution?
Can the rendering resolution of OpenGL and the window size (at least for the Windows OS) be separated? For example, I may only want to render at 400x300 resolution, but I want my window size to be 800x600. If so, how is this done?

# Answer
> 7 votes
Yes, but keep in mind the default frame buffer will always be the same size of the window. What you can do is to render your scenes internally into an off-screen (400x300) frame buffer, and then up-scale it to (800x600), you can do this by rendering this into a texture and applying it on a full screen quad, the advantage you will get is your shaders will run less often than with higher resolution. But you will lose quality due to scaling up which will need interpolating the original data in order to fill the bigger image.

# Answer
> 0 votes
One approach to this requirement is to adjust the projection matrix according to the different dimensions. To me you are describing a device dimension (i.e. 800x600) and virtual dimension (400x300)

**Note: I use the word dimension instead of resolution and I am assuming an orthographic projection**.

If this is the case, and you want to code for the virtual dimension, then you can do this by applying an aspect ratio correction to the projection matrix, *without modifying the viewport matrix as I have seen in other examples*.

For example:

```
// Calc ratio correction based on the two dimensions
float correction;
float deviceRatio = deviceWidth / deviceHeight;
float virtualRatio = virtualWidth / virtualHeight;
float xCorrection = deviceWidth / virtualWidth;
float yCorrection = deviceHeight / virtualHeight;

if (virtualRatio < deviceRatio) {
   correction = yCorrection;
} else {
   correction = xCorrection;
}

// Now when you calc your ortho projection--in this case centered--
// just divide by the correction
float left = -width / 2.0f / correction;
float right = width / 2.0f / correction;
float bottom = -height / 2.0f / correction;
float top = height / 2.0f / correction;

// Now set matrix which includes correction.
glm::mat4 projMatrix = glm::ortho(left, right, bottom, top, 0.1, 100.0f);

// Your viewport remains unchanged and is simply lower-left aligned
// For example
glViewport(0, 0, deviceWidth, deviceHeight);

// For your view matrix I simply "pull it back" a bit.
viewMatrix = glm::translate(viewMatrix, glm::vec3(0, 0, -1.0);

// And then finally you would multiply all your matrices together
// when rendering.
// For example
glm::mat4 mvp = projMatrx * viewMatrix * triangleModelMatrix;

// Then send "mvp" to your shader via some uniform
glUniformMatrix4fv(_mvpLocId, 1, GL_FALSE, glm::value_ptr(mvp));

// Now draw your object etc....

```

What the above code does is adjust the projection so that everything remains "square" rather than incorrectly stretched. I have seen examples where they manipulate the viewport instead.

My test code clears the background to orange and then renders a grey square that is the size of the virtual dimensions, this way I can see how the grey area adjusts when the device dimensions change, for example, moving between a phone and tablet. If your device is different than your virtual you should see some orange border(s) and if they are equal your grey virtual area should cover the orange exactly.

---
Tags: opengl, windows, resolution
---


# Question
Title: LibGDX trying to create a matrix of circles
I am trying to create a circular stage like so:

But I can only make a square:

# Answer
Each layer adds 2 * π circles (you can derive this from the circumference = 2 * r * π formula). What you should do is create an array of positions and put the position of the circles in it.

First loop between 0 (inclusively) and R (exclusively) where R is the amount of layers you want and let r be the current layer's index. Then each time create floor(2 * r * π) circles. You can get the positiom of the i-th circle in a specific layer, by using the

```
x = cos(2 * π / floor(2 * r * π) * i) * r
y = sin(2 * π / floor(2 * r * π) * i) * r

```

formula.

Together the whole code is

```
int getPoints(int R) {
    points = []

    for each r between 0 and R, do
        x = cos(2 * π / floor(2 * r * π) * i) * r
        y = sin(2 * π / floor(2 * r * π) * i) * r

        for each i between 0 and floor(2 * r * π) do
            points.push((x, y))
        end
    end

    return points
}

```
> 1 votes

---
Tags: libgdx, matrix
---


# Question
Title: 3D objects with animated bones Monogame in the year 2017, is it possible?
I've been working on a game for quite some time now and suddenly it seems that I've hit the great wall of..

In the earlier XNA there were possibilities to use animation exported with the 3D object .fbx files, but this was in the old XNA with SkinningData and AnimationPlayer etc.

I can't use these old samples that I've found on the Internet. How can I in the year 2017 animate an animated 3D object exported from Blender .fbx animate it in Monogame by the use of them bones?

I'm using Monogame in C# VS2017 but the Microsoft.Xna.Framework.Content.Pipeline.Processors and everything else doesn't exist.

The closest thing to an animation that I've made is to split up my object into pieces in Blender and animate each part with CreateTranslation and CreateRotation.. But that's old school to do it that way.

Or, I misunderstood the whole thing?

* I'm not going to use Unity.

# Answer
Finally I've found the solution to my problem.

First I've created a new content pipeline by following this blog: http://community.monogame.net/t/tutorial-how-to-get-xnas-skinnedsample-working-with-monogame/7609

You will not need the special Blender plugin/extension to be able to export to XNA/Monogame, you can use the ordinary FBX exporter. Instead of Apply Scale "All Local" change to "All FBX" and much about everything will work when importing it into the pipline tool.

Sometimes some certain things will be deformed anyway but that's the way it's always been.
> 5 votes

---
Tags: c#, 3d, monogame, monogame-extended
---


# Question
Title: SDL2 C++ Program Behaves Badly if FullScreen Mode
I'm making an app with SDL2. I've gotten everything to work so far, including SDL\_TTF. When I run my program in a normal window, everything works great!

However, now I'm trying to add fullscreen functionality... and I've run into the problem. On fullscreen mode ONLY, the program APPEARS to look fine at first, however, one of my functions (A text rendering function) causes problems. On fullscreen, this function momentarily removes or "flickers" the image behind it, revealing the previous image underneath. Why would this function cause an error on fullscreen vs. regular window sizing? I assume it's some kind of strange sizing issue...

```
void drawDialog(const char* content) {
//Draws a dialog box with set text
TTF_Font* font = TTF_OpenFont("assets/times.ttf", 30);
SDL_Color textColor = { 255, 255, 255 };
SDL_Surface* message = TTF_RenderText_Solid(font, content, textColor);
SDL_Texture* dialogTex;
SDL_Rect destRect;

destRect.x = 50;
destRect.y = 730;

destRect.w = 300;
destRect.h = 30;

dialogTex = SDL_CreateTextureFromSurface(renderer, message);
SDL_FreeSurface(message);
SDL_RenderCopy(renderer, dialogTex, NULL, &destRect);
SDL_RenderPresent(renderer);

```

}

Any help would be super! Thanks!

# Answer
I fixed it! Before, when I created the window in the main function, I passed SDL\_WINDOW\_FULLSCREEN to the window creation. However, the other mode of fullscreen is SDL\_WINDOW\_FULLSCREEN\_DESKTOP which creates a "fake" fullscreen appearance by sizing the window to the screen size. This works perfectly!
> 0 votes

---
Tags: c++, rendering, sdl, fullscreen
---


title: SDL2 dragging a sprite with mouse

text:
# Question
Title: SDL2 dragging a sprite with mouse
I am trying to figure out how to drag a sprite. I know when the mouse is being hovered, pressed, or released over a sprite. I don't know how to tell if the mouse is being pressed **and** moved at the same time. Every time I try to use `event.type`, I only get one mouse event back (`SDL_MOUSEMOTION`, `SDL_MOUSEBUTTONUP`, or `SDL_MOUSEBUTTONDOWN`). I tried doing something like (pseudo-code):

```
if(event.type == SDL_MOUSEMOTION && event.type == SDL_MOUSEBUTTONDOWN && mouse_in_sprite && left_button_pressed) {
    /* Never goes in here */
}

```

However, it never goes inside that if statement because the `event.type` is never more than one of the above mentioned every frame (unless I'm doing it wrong).

In the picture below, I am trying to make it so the scrollbar on the right moves up and down like a normal scrollbar would when pressing the left mouse button on the sprite and moving the mouse up or down.

Unfortunately, I don't know how to proceed further than getting the mouse position when the mouse is pressed on the sprite (pseudo-code):

```
if (mousePressed(SDL_BUTTON_LEFT)) {
   currentMousePosition = getMousePosition();

   /* Do something with currentMousePosition.x, currentMousePosition.y */
}

```

Any help would be appreciated! Thank you!

# Answer
> 3 votes
"Pressed" and "Released" are usually treated as events, rather than states. (ie. "Became Pressed" rather than "Is Still Pressed")

So processing a drag can be as simple as:

1. When the Pressed event fires for a given sprite, set a "isBeingDragged" variable to true (or set the "draggedObject" to point at that sprite, depending on how you're implementing this)
2. When a Move event fires, if "isBeingDragged" is true (or "draggedObject" is not null), move the sprite.
3. When the Released event fires, set "isBeingDragged" back to false (or "draggedObject" to null)

---
Tags: sprites, sdl, mouse
---


# Question
Title: Any idea why my openGL camera is stuttering only on the X axis? and only when using nvidia drivers?
As part of my assignment, I've been building a scene graph framework in C++/OpenGL.

My camera works absolutely fine going backwards and forwards, but when I strafe / move on the X axis, the camera just starts stuttering. It doesn't make much sense to me, because it's the same principle to move back/forward as it is to move right/left.

Everything is also normalised and being applied by deltaTime, so that's not an issue. Interestingly, this didn't happen when I was using my intel built in gpu, but only started occurring when I forced my nvidia card to handle the program.

Here is a video of the aforementioned stutter: https://www.youtube.com/watch?v=DyTIv0yiaP0&feature=youtu.be

My scene graph is available for viewing on my GitHub:

1. The repo: https://github.com/charliegillies/fullmetal.
2. The camera https://github.com/charliegillies/fullmetal/blob/master/fullmetal.cpp (line 503-730, mostly get/set methods.)
3. The camera controller https://github.com/charliegillies/fullmetal/blob/master/fullmetal-helpers.cpp (line 14-204)

Please note that this framework is still in its early days.

Let me know what you think, and I'll be sure to post a fix if I find it.

# Answer
> 0 votes
Fixed!

Turns out I the look at was being simply calculated in the wrong order, the eye variable and position variable were out of sync, which was causing the stutter.

---
Tags: opengl, c++, camera, windows, nvidia
---


title: Is Opengl 2.x still usable?

text:
# Question
Title: Is Opengl 2.x still usable?
i've used opengl core profile for a while now and i was wondering if it was possible to create a "decent" application (like a game/game engine) with good graphics. I have a machine which can run only OpenGl 2.1(raspberry pi3), i already know the advantages of core profile, but is Opengl 2.x still usable for today's standards?

# Answer
> 7 votes
First of all, you are very confused.

There is OpenGL ***ES*** 2.0, and there is *desktop* OpenGL 2.0 and 2.1. These are *very different things*, which run on entirely different platforms. ES runs on primarily mobile hardware, while desktop GL runs primarily on desktop hardware.

The core/compatibility distinction only exists for desktop GL, not OpenGL ES.

Raspberry Pi, of any version, does not support desktop OpenGL *of any version*. It only supports OpenGL ES 2.0.

As for what you can do with ES 2.0, a lot. You'll find Raspberry Pi's GPU to be limiting from a performance point of view, but you will have access to basic shader functionality. You can do a lot with that.

---
Tags: opengl-es
---


# Question
Title: Why does Unity editor freeze up if left unfocused for a while?
If Unity editor loses focus for too long (such as because I'm tabbed out into my browser or Blender), then I find that it needs about 15-30 seconds until I can interact with it again when it gets focus again. It seems like it is paused.

Is this a bug or my fault?

# Answer
It is related to a model which I am editing in blender and use in unity, each time if I save the model, then unity is stucked, because unity has to import the new model. There is not always a loading bar or other indicator that an import is going on, so this was confusing and unclear.
> 0 votes

---
Tags: unity
---


# Question
Title: How can I use OpenGL and D3D to render to the same window at the same time?
I have main render loop in which initial drawing is done via OpenGL to an SDL window, and after that the same window handle is passed to a Direct3D device, which does subsequent rendering.

Once I execute the program it will initially draw the OpenGL scene, and then do Direct3D drawing but that latter drawing overwrites the OpenGL work.

What I want to see is both drawings in parallel. How can I accomplish that?

# Answer
You cannot do this directly. Both OpenGL and Direct3D operate under the assumption that they are the only things writing to the window.

Furthermore, most of their actual rendering is done in in-memory back buffers and not directly onto the presentation window. It's only once all rendering commands are complete for a particular frame that the back buffer contents is transferred, wholesale, to the front buffer (the presentation window). This transfer is done without regard to what currently exists in that front buffer, and so D3D and GL are totally ignorant of the render results of the other.

There are two ways to achieve what you want, and you can choose between them based on whether or not you want the respective scenes to ever overlap.

In the simple case, where you want only the D3D stuff on the left half of the screen and the OpenGL stuff on the right (for example), you can simply adjust the viewport of both APIs accordingly (using `glViewport` in OpenGL or `RSSetViewports` in D3D).

However, if you want the scenes to potentially overlap (as it sort of sounds like you do), you have to instead render your scenes to textures in both APIs (potentially outdated OpenGL example, D3D example). Then you'll need to recover the bits of those textures manually and composite them into a final scene.

You can do this composition and final presentation via a third graphics API (likely GDI), if you wish, but that would probably be unpleasantly inefficient. Instead, I would suggest you do the final composition with D3D or GL itself again. You can pick either, but for the sake of demonstration I'll assume you prefer GL.

That means you will, every frame:

* perform your OpenGL rendering into a texture
* perform your D3D rendering into a different texture
* copy the contents of the D3D texture into CPU memory and from there into GPU memory of a second OpenGL texture.
* render a fullscreen quad in OpenGL using both your OpenGL textures and a shader or with appropriate blend mode settings enabled to handle composition however you'd like
> 8 votes

# Answer
You can also use the OpenGL Extensions WGL\_NV\_DX\_interop and WGL\_NV\_DX\_interop2

The first one is well supported by Nvidia and AMD and even Intel chips but works only with D3D9 objects. If you want to use DXGI (DirectX 10 and 11) you need to use the second one which only works with Nvidia and some AMD GPUs.

By using these extensions you can render to a surface or texture as Josh suggested, but you don't need to perform the expensive GPU -\> CPU -\> GPU copies that would slow down your program substantially.
> 6 votes

# Answer
I think I will use ANGLE to convert opengl calls to DirectX. The transferring of framebuffer to the RAM and then construct a backbuffer in DirectX from it, is time-consuming involving DMA and releasing resource from Opengl to hand over the gpu to DirectX. I am trying to use ANGLE and will update my answer when I know exactly how
> -2 votes

---
Tags: opengl, directx
---


# Question
Title: how to control units in a game using scripts
I'm looking to create a game like screeps, in which the user controls their units using javascript. I am planning on using lua as the scripting language that controls the units in my game, as it is supposedly easily embeddable. After doing some research, I decided that I should code the game in C++ and allow the player to access the objects (or the C++ equivalent of Lua's tables) in C++ that represent the units in the game through lua.

So far I have been able to send C++ functions to a Lua environment using LuaBridge. However, I'm not sure how to expose unit objects to the player through lua. The player should only be able to change certain attributes of the object (for example, they shouldn't be allowed to change the object's position to anywhere on the map, but they should be able to view the unit's position). The user should also be allowed to run functions like `unit1.forward` that can change the units position.

What is the best way to implement this behavior?

# Answer
> 1 votes
There is never a best way to do something in software development, only the way which works best for *you*.

But what I would do is not expose the whole `Unit` object to the Lua engine. I would expose only a façade which exposes only those functions which are supposed to be available to the scripting engine and also does internal plausibility and permission checks before forwarding it to the actual Unit object wrapped by it.

I would also make a difference between those units the player controls and those they do not control. For example, if a player-controlled unit has a function like `getNearbyEnemies()`, it would return an ~~array~~ table of units, but the enemy units would be represented by a *different* façade which only exposes those methods the player-unit should be able to call (`getPosition()` but not `selfDestruct()`)

That façade on the C++ side should also create and cache the lua table for its own representation on the Lua side. Rebuilding the lua table from an object whenever you call the scripting engine is an expensive operation, so you should keep the table for each unit in C++ memory (if you properly encapsulate your classes, it will only contain pointers to member functions, so it will never change during the unit lifetime). This means you actually have *three* representations of a unit on the C++ layer: The actual unit, the façade and the lua table. This might seem as if the façade C++ class is redundant, because it can be represented by the table alone. But I would still keep the façade, because it gives you a clean separation of the scripting interface from the internal representation of your Unit. This will become especially useful if you ever decide to switch the scripting backend.

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


title: Quaternion Rotation Weird Rotation

text:
# Question
Title: Quaternion Rotation Weird Rotation
I have an fps camera, and i am representing rotation with quaternions. every frame i grab how much the mouse moved that frame and then i simply do

```
Quat DeltaQ = Quat::CreateRotationXYZ(MouseYDelta, MouseXDelta, 0);
m_CurrentRotationQ = DeltaQ * m_CurrentRotationQ;

```

however, everything works until i rotate 90 degrees to the right. when i do that i cannot rotate up and down. also, moving the direction i am facing works, however, depending on where i am looking strafing left and right moves me in different directions, I've tried many things such as reversing order of multiplication, i'm really at a loss. Any help would be greatly appreciated.

# Answer
Thanks DMGregory. The article you mentioned didn't answer my question directly, however, it did in fact get me to start thinking about transformation space differently, which ultimately led me to implement a solution, Cheers!

Ok, so i've solved my issue. what i've done is allow my Camera's Rotate() method to accept a Space parameter such as

```
Camera::Rotate(Quat,ESpace = Local|World);

```

I then control camera rotation like this

```
Camera::Rotate(Quat::CreateRotation(DeltaY, Vec3(0,1,0)), ESpace::World);
Camera::Rotate(Quat::CreateRotation(DeltaX, Vec3(1,0,0)), ESpace::Local);

```

This allowed me to independently set the space per rotation, this works as expected. Quaternions are pretty difficult to get used to lol. PS, the Camera::Rotate() Method Looks Like This

```
void CFlyingCamera::Rotate( const CQuaternion& Rotation, ETransformSpace Space )
{
    if( Space == ETransformSpace::Local )
        m_Rotation = m_Rotation * Rotation;
    if( Space == ETransformSpace::World )
        m_Rotation = Rotation * m_Rotation;
}

```
> 1 votes

---
Tags: opengl, c++, quaternion, glm
---


# Question
Title: Efficient way to load chunks of a 2d level to prevent game from loading stutters
I am building a 2D sidescroller game in Unity3D.

It's tile-based. To get better performance I divided the level into chunks. I activate these chunks when the player enters 2D Triggers and deactivate it again when he exits the 2d trigger. So I normally only have a max of 2 chunks loaded. This works good BUT I do have some loading stutters of a few frames when I load a new chunk. How can I prevent that from happening?

Thank you!

# Answer
> 0 votes
Assuming you're using the Tilemap features new in Unity 2017:

If you structure each Chunk as a `Grid` with multiple child `Tilemap` layers, you can let them all load at SceneLoad, and let the `Camera` frustum cull any of them that aren't in view.

This may not be ideal for target platforms with limited memory if your map is very large.

---
Tags: unity, 2d, performance, side-scroller, levels
---


title: Non-Grid Based Movement in a Tile Map

text:
# Question
Title: Non-Grid Based Movement in a Tile Map
I'm making a dungeon game, and I'm doing input. When I move left or down until the code stops the player, I can no longer move any way except opposite the way I moved. Let's say I moved all the way left. The `canmovethere()` method stops the player from moving anymore. The player is now "stuck" in the wall; I can't move it up or down, only right. This also happens for moving down, but not up or right.

Here's the code:

```
public class PlayerInputProcessor {
   private PlayerCharacter player;
   private Dungeon dungeon;

   private final int NORTH = 0, SOUTH = 1, WEST = 2, EAST = 3;

   public PlayerInputProcessor(PlayerCharacter player, Dungeon dungeon) {
   this.player = player;
      this.dungeon = dungeon;
   }

   public void HandleInput() {
      if(Gdx.input.isKeyPressed(Keys.UP)) {
         if(canmovethere(player.getGridPos(), NORTH)) {
            player.setVectorPosY(player.getVectorPosY() + 3);
         }
      }
      if(Gdx.input.isKeyPressed(Keys.DOWN)) {
         if(canmovethere(player.getGridPos(), SOUTH)) {
            player.setVectorPosY(player.getVectorPosY() - 3);
         }
      }
      if(Gdx.input.isKeyPressed(Keys.RIGHT)) {
         if(canmovethere(player.getGridPos(), EAST)) {
            player.setVectorPosX(player.getVectorPosX() + 3);
         }
      }
      if(Gdx.input.isKeyPressed(Keys.LEFT)) {
         if(canmovethere(player.getGridPos(), WEST)) {
            player.setVectorPosX(player.getVectorPosX() - 3);
         }
      }
      System.out.println("Grid Pos " + player.getGridPos());

      player.setGridPos(new GridPoint2((int) player.getVectorPosX() / player.getWidth(),
         (int) player.getVectorPosY() / player.getHight()));

      if(dungeon.getTile(player.getGridPos()) instanceof FloorTile) {
         System.out.println("On A Floor Tile");
      }
   }

   private Boolean canmovethere(GridPoint2 newpos, int die) {
      GridPoint2 nextpos = new GridPoint2();

      if(die == NORTH) {
         nextpos.x = newpos.x;
         nextpos.y = (newpos.y + 1);
         if(dungeon.getTile(nextpos).isPassable()) {
            return true;
         }
      }
      if(die == SOUTH) {
         nextpos.x = newpos.x;
         nextpos.y = (newpos.y);
         if(dungeon.getTile(nextpos).isPassable()) {
            return true;
         }
      }
      if(die == EAST) {
         nextpos.x = newpos.x + 1;
         nextpos.y = newpos.y;
            if(dungeon.getTile(nextpos).isPassable()) {
               return true;
            }
      }
      if(die == WEST) {
         nextpos.x = (newpos.x + player.getWidth() / player.getWidth()) - 1;
         nextpos.y = newpos.y;
         if(dungeon.getTile(nextpos).isPassable()) {
            return true;
         }
      }
      return false;
   }
}

```

# Answer
> 0 votes
Thanks to @Balint for the idea

I needed to check where the player was going to be not the tile in front of it.

so i changed `if(canmovethere(player.getGridPos(), WEST))` too
`if(canmovethere(new GridPoint2( (int) (player.getVectorPosX() - 3) / 64, (int)player.getVectorPosY() / 64), WEST))`

Again I would not have fixed my problem if not for @Balint's comments.

# Answer
> 1 votes
When you checking if you can move onto another tile, you are sometimes just giving the player's current location. Balint point out one, and the other is when you go try to go south.

Change `nextpos.y = (newpos.y);` to `nextpos.y = newpos.y - 1;` and change `nextpos.x = (newpos.x + player.getWidth() / player.getWidth()) - 1;` to `nextpos.x = newpos.x - 1;`. I'm not sure why it was block disabling movement when looking at the player's position (Maybe something in the `isPassable()` method?), but if it works with two directions, this should let it work for the other two.

---
Tags: java, libgdx, collision-detection, movement
---


# Question
Title: Iterating through all animator layers in Unity Mecanim
I'm aware of how SetAnimatorLayerWeight works, I'm looking for a way to iterate through all layers of my controller at runtime.

I've four layers and expect more, and need to update them at once, in essence, what I'm trying to do is something like this.

To clarify: The code below is boilerplate of what I'm trying to do.

```
    void SetCurrentWeaponLayerWeight(int index)
    {
        _animator.SetLayerWeight(index, 1);

        foreach(AnimatorLayer l in Animator.Layers)
        {
            if (l.index != index)
                _animator.SetLayerWeight(l.index, 0);
        }
    }

```

# Answer
The problem lies in your use of `Animator` instead of `_animator` in your iterator. (I've used a standard `for` loop for code clarity)

```
void SetCurrentWeaponLayerWeight(int index)
    {
        _animator.SetLayerWeight(index, 1);

        for(int i=0;i< _animator.layerCount;i++)
        {
            if (i != index)
                _animator.SetLayerWeight(i, 0);
        }
    }

```
> 1 votes

---
Tags: unity, animation, mecanim
---


# Question
Title: Drawing a simple triangular prism in opengl in 3D
Is there a simple way to draw a triangular prism in opengl?

I'm using lighting and a non-orthographic camera. I basically need a 3d object, not just vertices.

*edit:* well I've tried searching, and I tried doing it with two cubes. One that is rotated at an angle from the other, but logically that doesn't work. I have to get an object with angles less than 90 degrees.

I basically need something like this:

# Answer
> 2 votes
You can just provide the vertices yourself:

```
// bottom
0, 1, -1/2
√3 / 2, -1/2, -1/2
-√3 / 2, -1/2, -1/2

//Top
0, 1, 1/2
√3 / 2, -1/2, 1/2
-√3 / 2, -1/2, 1/2

```

Then the indices:

```
// Bottom
0, 1, 2,

// Top
3, 4, 5,

// Side1
0, 1, 3,
3, 1, 4,

// Side 2
1, 2, 4,
4, 2, 5,

// Side 3
2, 0, 5,
5, 0, 3,

```

# Answer
> 0 votes
So Bálint's advice works. Here's how to do it in code. You can define a function that draws a triangular prism at the centre using glVertex3f() functions

```
void triangularPrism()
{
    glBegin(GL_QUADS);
        glVertex3f(0.5, 0, 0.5);
        glVertex3f(0.5, 0, -0.5);
        glVertex3f(-0.5, 0, -0.5);
        glVertex3f(-0.5, 0, 0.5);

        glVertex3f(0.5,0,-0.5);
        glVertex3f(0.5,1,-0.5);
        glVertex3f(-0.5,1,-0.5);
        glVertex3f(-0.5,0,-0.5);

        glVertex3f(0.5,1,-0.5);
        glVertex3f(-0.5,1,-0.5);
        glVertex3f(-0.5,0,0.5);
        glVertex3f(0.5,0,0.5);
    glEnd();
    glBegin(GL_TRIANGLES);
        glVertex3f(0.5,0,0.5);
        glVertex3f(0.5,1,-0.5);
        glVertex3f(0.5,0,-0.5);

        glVertex3f(-0.5,0,0.5);
        glVertex3f(-0.5,1,-0.5);
        glVertex3f(-0.5,0,-0.5);
    glEnd();
}

```

Then this function can be used in the glutDisplayFunc() just like the other primitives. You can translate it, scale it, rotate it and so forth. Example:

```
glPushMatrix();
    glTranslated(1.5,1.1,2.75);
    glRotated(180,0,1,0);
    glRotated(flapsDegree, -1,0,0);
    glScaled(0.5,0.8,0.1);
    triangularPrism();
glPopMatrix();

```

---
Tags: opengl, c++, 3d, glut
---


# Question
Title: Unity3d mesh is getting distorted while animation
I attached boxing glove to rig using this method https://stackoverflow.com/questions/34719718/transferring-rig-weights-from-one-mesh-to-another-in-blender-2-76 It works fine in the blender, But while animating in unity mesh is getting distorted. Image{https://i.stack.imgur.com/4vD80.jpg} Anyone knows how to fix this?

# Answer
> 1 votes
Basically what is happening is that you are parenting the boxing glove to the player model(the humanoid). It works fine in blender, but not in unity, probabily due to the weightpaint of the boxing glove in blender. I have in my mind a much easier way of handling this: -import the two models into unity. Drag the player in the scene and look for the hand bone; -create an empty gamobject and attach to this the boxing glove. This way the glove will follow the hand of the player, without actually having to be attached to it in blender.

---
Tags: unity, blender
---


# Question
Title: Unity3D: Problems drawing on duplicated texture
**I'm trying to:**

1. load texture from assets folder
2. create a clone of said texture that will be manipulated during runtime
3. set pixels on cloned texture

---

I have successfully set pixels on the original texture (*ie. discarding the code in the start function*), but **I cannot seem to be able to draw to the duplicated version**.

---

```
void Start () {

    canvas = gameObject.GetComponent(typeof(SpriteRenderer)) as SpriteRenderer;
    Sprite oldSprite = canvas.sprite;
    Texture2D oldTex = oldSprite.texture;
    Rect oldRect = oldSprite.textureRect;

    tex = new Texture2D(oldTex.width, oldTex.height, TextureFormat.RGB24, false);
    tex.SetPixels32(oldTex.GetPixels32());
    tex.Apply();

    Rect r = new Rect(oldRect.x, oldRect.y, oldRect.width, oldRect.height);
    Vector2 pivot = new Vector2(oldSprite.pivot.x, oldSprite.pivot.y);
    float pixelsPerUnit = oldSprite.pixelsPerUnit;
    Sprite sprite = Sprite.Create(tex, r, pivot, pixelsPerUnit, 0, SpriteMeshType.FullRect);

    canvas.sprite = sprite;
}

public void draw(Tool tool, Color32 color, List<Vector2> locations) {
    Color32[] pixels = tex.GetPixels32(0);

    for(int i = 0; i < pixels.Length; ++i) {
        pixels[i] = color;
    }
    tex.SetPixels32(pixels);
    tex.Apply();
}

```

---

Please ignore the unused vars, I'm just trying to set the whole texture's color for now.

Anyways, any help is always appreciated - thanks :)

# Answer
> 0 votes
The problem was this line:

```
Vector2 pivot = new Vector2(oldSprite.pivot.x, oldSprite.pivot.y);

```

**oldSprite.pivot.x returns a pixel coordinate and I was expecting it to be a float between 0.0f and 1.0f.** Once the args were changed, drawing on the texture worked perfectly fine.

revised:

```
Vector2 pivot = new Vector2(0.5f, 0.5f);

```

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


# Question
Title: How to bind more texture array objects into shader?
I can't find information if it is posiible, to bind few texture array objects into shader. Any searches for "array of texture arrays" or "multiple texture arrays" end with how to use texture array object. I'm creating a texture array object in this way:

```
glGenTextures(1, &array_texture_object_A);
glBindTexture(GL_TEXTURE_2D_ARRAY, array_texture_object_A);
...
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);  //unbind

```

Texture array object is distinguishable by texture width, height and bits per pixel. When I want to load texture with different size I create anoter texture array object:

```
glGenTextures(1, &array_texture_object_B);
glBindTexture(GL_TEXTURE_2D_ARRAY, array_texture_object_B);
...
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);  //unbind

```

And my question is how to bind array\_texture\_object\_A and array\_texture\_object\_B into shader. (For example I have diffuse map in array\_texture\_object\_A and specular map in array\_texture\_object\_B).

For binding function (**glBindTexture**) first argument - target, has only **GL\_TEXTURE\_2D\_ARRAY** enum, there is no something like GL\_TEXTURE\_2D\_ARRAY\_0, GL\_TEXTURE\_2D\_ARRAY\_1 etc. End now I'm stuck at this point.

Many thanks for any help.

# Answer
> 3 votes
You can use OpenGL's `glActiveTexture` before binding the texture, which expects one of `GL_TEXTURE0`, `GL_TEXTURE1`, etc. values (these are sequential, `GL_TEXTURE0 + i` is the i-th texture slot)

After you bind a texture, load an integer into the sampler object in the shader. The integer should be equal to the index of the texture slot the textures are in (e.g. with `GL_TEXTURE3` you'll need to load in 3)

---
Tags: opengl, rendering
---


# Question
Title: How to achieve single animation for different charcters?
I've been playing a game called Marvel Contesnt of Champions for android. In that game two opponent fights with each other in most 2D view but the game is developed in 3D. Each character has their own special move which dynamically interacts with opponent. So how does they achieve single animation for different characters?

By single animation I mean, for example, I'm playing with X character and he uses his special move on Y character and in that animation X character grabs character Y's neck and smashes him on the ground. Now, I'm fighting Z character with X character and in the special move he smashes Z character same way he smashed Y character. Is it like a common skeletal movements that are just changing their clothes(textures) ?

I'm pretty sure it's not pre-animated thing cause there are like more than 50 characters. I'm currently working in Blender and getting my character design right but this question was bugging me for a while and I thought there could be no better place other than here to clarify my confusion.

# Answer
When you want a character skeleton to interact with objects in the environment (which might or might not also be a character skeleton), then you usually use a technique called inverse kinematics, often abbreviated as IK (the link leads to the documentation of the Unreal engine, but other 3d engines usually can do this too).

When you play an animation, like for example "grabbing another character's throat", you pass the position of the target object to the animation system. It will then modify the animation of the arm- and shoulder bones so that the hand-bone ends up where you want it to be.

If you have two or more characters which have different body proportions but the same bone hierarchy, then many engines allow you to easily reuse animation sequences between them. That's called animation retargeting.

Having animations where two characters interact with each other is complicated. There are several options:

1. Fuse the two character skeletons into one for this animation. This gives you the most control over the animation, but might lead to problems when the two characters have different proportions. It might look as if individual bodyparts suddenly grow or shrink during the animation.
2. Animate both skeletons separately. So one has a "smash other person into the ground" animation and the other a "get smashed into the ground" animation with the attackers hand as one IK target point and the floor as another.
3. For this specific case of "getting smashed into the ground", you can also just deactivate the animation of the victim's model and use ragdoll physics with the throat-bone being the anchor point of the character model. It will look as if the victim gets thrown to the ground like a wet sack. This might or might not be what you are going for.
> 2 votes

---
Tags: 3d, animation, skeletal-animation, character
---


# Question
Title: Should I worry about Youtube Let's Plays when I'm creating a story-heavy game?
A few years ago, I watched a full playthrough of the first three Phoenix Wright games on Youtube. I enjoyed the story and characters a lot, hence why I pretty much binge-**watched** what is a series of very story-heavy **games**. I know it sounds stupid, but that's what happened.

As a consequence, I had no reason to buy and play any of those games. In hindsight, I realize I pretty much pirated the games without ever even playing them. It's not like I enjoyed the games because of their *epic* gameplay, I enjoyed them because of the story, and since I know what's going to happen, I don't have a reason to play them myself.

I still bought them in the end out of principle (even if it's Capcom...), but how many people are seriously going to do that? I doubt very many.

Now, I'm in the middle of creating my own story-heavy game, and I'm unsure because of how popular gaming channels have become on Youtube. I fear some big youtuber will play my game, a big portion of my potential playerbase will see the story and not be bothered to buy the game themselves. I mean, why should they if they've seen the story? Sure, I get some free publicity/marketing for my game, but what good is that if nobody's going to buy the game?

Is my concern valid? Or am I too pessimistic about people?

# Answer
> 133 votes
Yes, you should care about Let's Players. In fact, you should make your game as appealing to them as possible. Reach out to them and encourage them to play your game.

Let's Players have become one of the most important marketing channels for independent game developers. They are a great way to expose your game to a large and interested audience and most of the time they don't even want any money for it. And exposure is everything in a market as crowded as today's game market. Only those people who know your game exists will consider buying it. I am sure some games like *Surgeon Simulator* or *Octodad* would have never been as successful if they weren't played into the ground on Youtube and Twitch.

Regarding your fear that "a big portion of your potential playerbase will see the story and not be bothered to buy the game": Have you calculated how large your "potential playerbase" actually is? There are hundreds of millions of people in the world who regularly buy and play video games. Your "potential playerbase" is practically endless, even if your game only targets a niche demographic. But just as countless as your customer pool is your competition. That's why exposure is so crucial for games.

However, if you are afraid that watching your game is just as good as playing your game, make sure it is not. Add multiple major branches to your story and lots of minor decisions which affect later events in the game. You want the audience to constantly wonder what would have happened if the player had done something different. And do not neglect your actual gameplay. The unique strength of games as a medium is that they are interactive. If you just want to tell your story and don't want any audience interaction to interfere with it, you can just as well write a novel.

# Answer
> 20 votes
I had a similar experience to the one you describe with some other game I will not mention, and ended up thinking about it in similar terms as you do.

As Bálint says, it is a double edged sword. Yet that does not mean you cannot get ahead.

What happens when they play the game for an online audience, then that audience gets to know the game. If this were people who would not have known about the game otherwise, they are people who would not have bought the game anyway. Thus, you should not think about this as a loss, but as a missed opportunity.

To exploit that opportunity, you need to sell replay value during the gameplay. After all, most "let's players" (for lack of a better name) will rarely replay a game (most of them have to move on to something else to keep their audience interested), thus having multiple endings or stuff locked behind a complete play through will make it harder for them to present the entirety of the game.

Now, replay value is usually achieved with some variation of choice and consequence, yet that could be harder in a story heavy game as those tend to be very linear. In that case, I would suggest catering to theories. How? You avoid heavy exposition in the game. Let the explanations, backstory, setting, lore, mythology and the rest of the world building to those who want to look for it, and make it as deep as it need be.

Do that correctly and “Let's players” will complete the game and only scratch the surface of what the game has to offer. If people watching them find mysteries in the game, if you inspire curiosity, and if people would like to take the control of the game and go explore more by themselves, then most of the work to sell the game has been done.

In abstract, you want to provide joy of discovery, and if you put a lot to discover, “let’s players” will not discover it all.

---

> I fear some big youtuber will play my game, a big portion of my potential playerbase will see the story and not be bothered to buy the game themselves. I mean, why should they if they've seen the story?

Well, it is not that they "should". Yet, they can be interested in playing the game by themselves if:

* They have not seen the whole story because that is not necessary to complete the game. Perhaps you can replay the game with a different character and get a different point of view.
* The story is not the only interesting thing of the game. There is a lot of world building beside the story. Then there are the game mechanics that could (and arguably should) be fun and interesting by themselves.

You might be interested in Shandification. The act of telling a story is also the act of picking what is relevant and what is not... there are multiple way to tell the same story by merely changing the point of view. If you can accommodate that in the game and let the player choose on what to focus on instead of dictating it, then you have the potential to make every play through different.

You may even make that literally. For example, the game "Revolution 1979" lets you take the role of a reporter during the eponymous 1979 Iranian Revolution. Although this means that the player is not the protagonist of the history, it allows the player to explore different parts of the history as it unfolds. This allows circumventing the problem of placing the player in command having player action result in something different that the actual history (by being a glorified spectator, you are not in position to change historical events).

See also How a Japanese Indie Studio Kicks Bethesda's Butt at World-Building

Consider also that the experience of playing the game is not the same as watching it. Of course, this is more relevant for an action games (platforming, first person shooting, etc.) - You need to know what you are making, is it a graphic novel or a video game? Consider games like Chrono Trigger, Fallout or your pick of the Final Fantasy series... they do a great job in storytelling and world building, yet they have game mechanics that are (most of them) fun to play regardless of the story.

On the other hand, if you are making something like a detective game, I suggest to find ways to mix things up, so that it does not play the same every time. Crime mystery really suffer in replay value once you know who the criminal is.

---

> Should I look for other ways to monetize my game, just to be sure?

Yes and no.

Not all games fit all monetization schemes. Some games work best in a pay upfront model. In addition, monetization is better when you considered an integral part of the game design (because it can make or break the game).

On the other hand, thinking of ways to monetize the game (even if you end up not doing it) would be a good exercise to find aspect of the design that you could change. For example, if there is a part of the game that could be different thanks to DLS or micro-transaction, that part of the game that could be different, period. If you can make it so that it plays different every time, you have added replay value to the game.

# Answer
> 5 votes
Youtube let's plays are double edged swords. On one hand there's the probability, that you'll lose potential players, but there's also the probability, that you'll gain new ones, especially if you're an indie dev.

Most popular indie games become popular in the first place because of them. You can probably name a few from the top of your head; Stardew Valley, Shower with your dad, Flappy Bird, etc.

There were cases of video game companies being afraid of let's players spoiling the majority of story based games. The most recent I know of was Atlus not allowing youtubers to upload let's plays of Persona 5 after a certain point in the game.

---
Tags: marketing, monetization
---


title: Unity Loadscene link errors

text:
# Question
Title: Unity Loadscene link errors
I am working on a mobile game, and am experiencing a strange bug/error. When I load into the main scene , all is fine everything works and no errors. However there are two scenario's in which it breaks

* when I open the pause menu and go to the main menu. Then return to the level all is broken.
* coming directly from the main menu into the level

GameObject links in scripts are missing and some other stuff. Here are the errors and corresponding code that is used:

If some screen from the editor are required I will update the question

Code used for the pause menu:

```
 public class Pause : MonoBehaviour {

    [SerializeField]private bool _isPaused;
    [SerializeField] private GameObject _attackButton;
    [SerializeField] private GameObject _moveButton;
    [SerializeField] private GameObject _pauseMenu;
    [SerializeField] private GameObject _pauseButton;

    // Use this for initialization
    void Start () {
        _isPaused = false;
        _pauseMenu.SetActive(false);
    }

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

    }

    public void OnClickPauseButton()
    {
        _isPaused = !_isPaused;
        if(_isPaused)
        {
            Time.timeScale = 0;
            HideButtons();
        }
    }

    public void OnClickResumeButton()
    {
        _isPaused = !_isPaused;
        if (!_isPaused)
        {
            Time.timeScale = 1;
            ShowButtons();
        }
    }

    public void OnClickMenuButton()
    {
        SceneManager.LoadScene("MainMenu");
    }

    private void HideButtons()
    {
        _attackButton.SetActive(false);
        _moveButton.SetActive(false);
        _pauseButton.SetActive(false);
        _pauseMenu.SetActive(true);
    }

    private void ShowButtons()
    {
        _attackButton.SetActive(true);
        _moveButton.SetActive(true);
        _pauseButton.SetActive(true);
        _pauseMenu.SetActive(false);
    }
}

```

The Main menu code, that is used

```
 public void StartGame()
 {
        SceneManager.LoadScene("2DScene");
 }

 public void ClickUnfinishedButton()
 {
        StartCoroutine("FadeInAndOutText");
 }

 IEnumerator FadeInAndOutText()
 {
        toBeAddedText.SetActive(true);
        yield return new WaitForSeconds(2);
        toBeAddedText.SetActive(false);
}

```

EDIT:

Scoremanager code:

```
public class ScoreManager : MonoBehaviour {

[SerializeField] private PlayerController _player;
[SerializeField] private GameObject text;
[SerializeField] private Slider SliderVar;
private int _currentScore, _requiredScore;

// Use this for initialization
void Start()
{
    InitializeVariables();

}

private void InitializeVariables()
{
    _player = _player.GetComponent<PlayerController>();
    _requiredScore = 10;
}

// Update is called once per frame
void Update()
{
    setScoreSlider();
    text.GetComponent<Text>().text = _player._currentScore + "/" + _requiredScore;
}

private void setScoreSlider()
{
    SliderVar.value = _player._currentScore / _requiredScore;
}
}

```

Code from inputscript:

```
 public class InputScript : MonoBehaviour
{
    public FingersJoystickScript joystickScript;
    [SerializeField] private float _minimumDistanceSwipe;
    [SerializeField] private float _minimumSpeedSwipe;
    [SerializeField] private SwipeGestureRecognizerDirection _swipeDirection;
    public GameObject player;
    public bool isAttacking;
    private TapGestureRecognizer _pressGestureRecognizer;
    private Vector2 _smoothDirection;
    private SwipeGestureRecognizer _swipeGestureRecognizer;
    private LongPressGestureRecognizer _longPressGestureRecognizer;
    private bool _facingRight = false;
    private Animator anim;

    private GestureTouch FirstTouch(ICollection<GestureTouch> touches)
    {
        foreach (var t in touches)
        {
            return t;
        }
        return new GestureTouch();
    }

    private void Awake()
    {
        joystickScript.JoystickExecuted = JoystickExecuted;
        joystickScript.MoveJoystickToGestureStartLocation = false;
        isAttacking = false;
    }

    //  public bool MoveJoysticktoGestureStartLocation;

    private void Start()
    {
        anim = player.GetComponent<Animator>();
        CreateSwipeGesture();

        _swipeGestureRecognizer.MinimumDistanceUnits = _minimumDistanceSwipe;
        _swipeGestureRecognizer.MinimumSpeedUnits = _minimumSpeedSwipe;
        _swipeGestureRecognizer.Direction = _swipeDirection;
    }

    private void Update()
    {
        _swipeGestureRecognizer.MinimumDistanceUnits = _minimumDistanceSwipe;
        _swipeGestureRecognizer.MinimumSpeedUnits = _minimumSpeedSwipe;
        _swipeGestureRecognizer.Direction = _swipeDirection;

    }

    private void CreateSwipeGesture()
    {
        _swipeGestureRecognizer = new SwipeGestureRecognizer
        {
            Direction = SwipeGestureRecognizerDirection.Any,
            DirectionThreshold = 1.0f
        };
        _swipeGestureRecognizer.Updated += SwipeGestureCallback;
        FingersScript.Instance.AddGesture(_swipeGestureRecognizer);
    }

    private void SwipeGestureCallback(GestureRecognizer gesture, ICollection<GestureTouch> touches)
    {
        if (gesture.State == GestureRecognizerState.Ended)
        {
            isAttacking = true;
        }

    }

    private void JoystickExecuted(FingersJoystickScript script, Vector2 amount)
    {
        if (amount.x > 0 && !_facingRight)
        {
            FlipXAxis();
        }
        else if (amount.x < 0 && _facingRight)
        {
            FlipXAxis();
        }
        Vector3 pos = player.transform.position;
        pos.x += (amount.x * 8 * Time.deltaTime);
        pos.z += (amount.y * 8 * Time.deltaTime);
        player.transform.position = pos;
        anim.SetBool("isWalking", true);

        if (amount == Vector2.zero)
        {
            anim.SetBool("isWalking", false);
        }
    }

    private void FlipXAxis()
    {
        //oposite direction
        _facingRight = !_facingRight;

        //get local scale
        var theScale = player.transform.localScale;

        //flip on x axis
        theScale.x *= -1;

        //apply that to the local scale
        player.transform.localScale = theScale;
    }

```

}

# Answer
> 1 votes
You are getting Null Pointer Exceptions for all of those errors.

Basically you are trying to use variables that you haven't initialized. For any private variable, you have to get a handle to the object with FindGameObject methods in your Start() before you can use it.

Your first error, for instance is at

```
private void InitializeVariables()
{
    _player = _player.GetComponent<PlayerController>();
    _requiredScore = 10;
}

```

\_player is still null, because you havent initialized it with FindGameObject like so

```
GameObject p=GameObject.FindWithTag("Player");
if(p!=null)
    _player=p.GetComponent<PlayerController>();

```

From that point on, you need to always preface any calls to \_player with

```
if(_player != null)

```

In order to be safe if for some reason no object is tagged as Player

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


title: Flexible Controller Support

text:
# Question
Title: Flexible Controller Support
I am developing a platformer in Pygame with the eventual hope of releasing it on Steam.

I am currently trying to add input support for multiple controllers.

To do this, I am using the Pygame joystick module, which allows a connected controller to send input events to my event queue (the event types are JOYBUTTONDOWN, JOYBUTTONUP, and JOYAXISMOTION).

I want to have input support for at least keyboards, Xbox 360 controllers, Xbox One controllers, and PS4 controllers.

The problem, of course, is that these controllers all use different button IDs.

One way I thought of getting around this was to call a function in my event processing code which could convert input from any of these devices to a more abstract event tag. For example, keyboard presses of "a", Xbox 360 controller presses of left on the D-pad, and negative motion on the seventh axis of a PS4 controller would all set an abstract "mapped\_event" attribute to "left". I could then use this "mapped\_event" attribute in my player sprite's process\_event() method, which moves him based on event input.

Here's a sketch of how that conversion code would look:

```
def map_event(event):

    # KEYBOARD BUTTON PRESSES

    if event.type == pg.KEYDOWN:
        if event.key = K_RIGHT:
            mapped_event = "right"
        elif event.key == K_LEFT:
            mapped_event = "left"

    # CONTROLLER BUTTON PRESSES

    elif event.type == pg.JOYBUTTONDOWN:

        if joystick == "Xbox360 controller":
            if event.button == 3:
                mapped_event = "right"
            elif event.button == 2:
                mapped_event = "left"

    # CONTROLLER AXIS MOTION

    elif event.type == pg.JOYAXISMOTION:

        if joystick == "Xbox360 controller":
            if event.axis == 1:
                if event.value == 1:
                    mapped_event = "left"
                elif event.value == -1:
                    mapped_event = "right"

        elif joystick == "PS4 controller":
            if event.axis == 3:
                if event.value == 1:
                    mapped_event = "left"
                elif event.value == -1:
                    mapped_event = "right"

    return mapped_event

```

From what I can tell, this is the way a lot of people recommend getting around the inconsistent controller issue. For example, I think this is what is meant when people speak about an "intermediate layer" of input processing and "mapping from real buttons to game concepts". Please correct me if I'm interpretting this wrong.

My question is:

**How can I extend this method, (or an alternative), to also support all controllers which use, say, XInput/DirectX** (according to this answer, a lot of aftermarket controllers use these), **while handling multiple OSes?**

I am open to using a different framework for processing joystick events, provided the language is Python.

---

**Related Questions**

How can one impliment multiple control schemes for a single player?

Correct way to abstract an XBox Controller

Unity3D Joystick Buttons Xbox360 & PS3 have Inconsistent Button Inputs?

# Answer
> 0 votes
According to this talk by Lars Doucet and Jeff Bellinghausen, hard-coding input code for specific controllers is a naive approach to input support.

Even if you abstract to an intermediate layer, the approach is problematic for the followImg reasons:

1. It makes key rebindings difficult
2. It results in messy, ad hoc code
3. It's not reliable given that different OSes and drivers may result in different button and axes mappings
4. It's hard to display the correct button glyphs in-game

If you plan on releasing on Steam, a better way to achieve flexible controller support is to use the Steamworks Controller API, which is part of the Steamworks SDK.

From what I can tell, this would involve you purging your code of references to controller-specific input events in favor of more generic (higher-level) input actions (for example, "INTERACT", or "JUMP").

The Steamworks Controller API would take care of mapping specific controller inputs to these actions (you can specify a default mapping).

In addition to supporting many controllers, the Steamworks Controller API also allows users to customize their input schemes, which is always a nice feature.

The specifics of how to incorporate the Steamworks Controller API into your code can be found in the documentation.

If your game is written in Python, you may have to find a Python wrapper for the Steamworks API. There are a few out there, but they haven't integrated Steam's controller stuff yet, as far as I can tell.

The exact details of how to use the Steamworks Controller API in your Python code may deserve its own question.

---
Tags: input, python, pygame, controllers
---


# Question
Title: Realtime inverse kinematics on unity apps for android and iOS
Hello I want to understand how much overheads do implementing inverse kinematics in realtime add.

I am looking at an implementation as such demonstrated in the video. https://www.youtube.com/watch?v=Gyakxv34404&feature=youtu.be

Let me explain the exact requirement now.

Assuming a game of mario, where mario is a 3D Character. And there is a coin placed at a height. So when mario comes into area of effect for the coin, we know the initial position of his arms, and we know the expected final position which is the position of the coin.

So we create a trajectory from initial to final position in realtime and the main character moves accordingly in the trajectory.

Now I can understand this would work fine in editor but if we have exported the game and this computations happen realtime for every object, how much CPU intensive would this be? Do all the existing IK assets provided on store

for example in this video of final IK https://www.youtube.com/watch?v=ZuWvGq3yV44 the characters are following the trajectory in real time I suppose. But what if we were to create the trajectory realtime depending on player positions, would that be a CPU intensive task to NOT work on mobile devices?

# Answer
As you can see in videos you've provided it is possible even for more characters. In the second video you have more than 10 models, each of them is computed in realtime and I suppose they don't share the same IK results (the reason for this demo is to show it can solve foot and hand contacts for different character proportions, so each character is computed separately).

The IK itself doesn't need to be so heavy. There are many levels of IK - you can compute a hand or leg made of just two segments or you can compute entire body at once. The first one is very simple computationally while the second is almost never needed in a game.

Having that said I'm not sure if you approach the problem from the good side or I didn't understand your description. What you wrote seems like you have the current position of hand and the target position, and you want to 'drag' your character by hand from start to end.

This could work but you may end up with other problems like breaking of the rest of the body movement. Instead, I would move the character by his center as always, and IK would just respond to this movement.

**I'll give you another example from Mario game:**

In old Mario game you could jump under the brick to hit it with your fist but because of the character proportions its hand ended at the same level as head so it looked fine. Now let's assume you put a typical human in place of Mario. You hit 'jump' and Mario raises his hand above head and starts moving up. At some point Mario will touch the brick and you need to decide if it keeps moving or stops - either way may look odd.

**So what can we do with IK?** On jump you set simple solver, only for the raised hand. The solver have the task to not to allow the hand to move above brick level. Then when you're movig up and touch the brick then you hand will start to bend, so it never goes above the brick. Given that all the details were done right it should improve the look of you character.

On the end few random thoughts I recall from working on IK in Unity:

* Bio IK is not the fastest one, it's more like an R&D. If it works for you then fine, if it gets too slow - change it to Final IK.
* Don't drag your character by hands/feet and depend on IK where possible. Instead move the character as always and use IK only to modify limbs movement.
* Try to avoid complex IK structures, like multiple chains, full-body IK etc. If possible use few separate limb solvers.
* Final IK has A LOT of nice examples, showing you how to achieve some specific effect using simple solvers. It's worth to look at, just to see how you can solve common problems.
> 1 votes

# Answer
If you only have one IK animation computation happening and it is not happening at every frame, then it should be fine in real-time -- especially if you are using FinalIK or BioIK. However, if you are worried about the performance of your IK solver, you can easily build your own FABRIK IK Solver: Build Your Own IK in Unity3D
> 0 votes

---
Tags: animation, skeletal-animation, realtime, inverse-kinematics
---


# Question
Title: Issues making a gradient square in glsl es 2.0, Gamemaker Studio 2.0
I made a triangle list with 4 triangles, having the middle point a different color. And then aim to combine the triangles to get a nice gradient. But the edges of the triangles create unwanted lines, I don't want these lines I want it to be smooth al the way. How can I get the desired result?

Images:

Shader Code:

```
    // Simple passthrough vertex shader
    //
    attribute vec3 in_Position;                  // (x,y,z)
    attribute vec4 in_Colour;                    // (r,g,b,a)
    attribute vec2 in_TextureCoord;              // (u,v)

    varying vec2 v_texcoord;
    varying vec4 v_colour;

    void main()
    {
        vec4 object_space_pos = vec4( in_Position.x, in_Position.y,         in_Position.z, 1.0);
        gl_Position = gm_Matrices[MATRIX_WORLD_VIEW_PROJECTION] * object_space_pos;

        v_colour = in_Colour;
        v_texcoord = in_TextureCoord;
    }

    //
    // Simple passthrough fragment shader
    //
    varying vec2 v_texcoord;
    varying vec4 v_colour;

    void main()
    {
        gl_FragColor = v_colour;
    }

```

Gamemaker code: Create event:

```
    //Build vertices list

    vertex_format_begin();
    vertex_format_add_position();
    vertex_format_add_colour();
    vertex_format_add_textcoord();
    v_format = vertex_format_end();
    v_buff = vertex_create_buffer();
    vertex_begin(v_buff, v_format);

    //triangle 0
    vertex_position(v_buff, 200, 100);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 0.0, 0.0);

    vertex_position(v_buff, 600, 100);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 1.0, 0.0);

    vertex_position(v_buff,  400, 300);
    vertex_colour(v_buff, c_red, 1);
    vertex_texcoord(v_buff, 0.5, 0.5);

    //triangle 1
    vertex_position(v_buff, 200, 100);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 0.0, 0.0);

    vertex_position(v_buff, 200, 500);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 0.0, 1.0);

    vertex_position(v_buff,  400, 300);
    vertex_colour(v_buff, c_red, 1);
    vertex_texcoord(v_buff, 0.5, 0.5);

    //triangle 2
    vertex_position(v_buff, 600, 100);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 1.0, 0.0);

    vertex_position(v_buff, 600, 500);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 1.0, 1.0);

    vertex_position(v_buff,  400, 300);
    vertex_colour(v_buff, c_red, 1);
    vertex_texcoord(v_buff, 0.5, 0.5);

    //triangle 3
    vertex_position(v_buff, 200, 500);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 0.0, 1.0);

    vertex_position(v_buff, 600, 500);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 1.0, 1.0);

    vertex_position(v_buff,  400, 300);
    vertex_colour(v_buff, c_red, 1);
    vertex_texcoord(v_buff, 0.5, 0.5);

    vertex_end(v_buff);
    tex = sprite_get_texture(sprite_index, 0);

```

Draw event:

```
    shader_set(shd_prim);
    shader_set_uniform_f(uni_radius, var_radius);
    vertex_submit(v_buff, pr_trianglelist, tex);
    shader_reset();

```

# Answer
Here's a WebGL implementation showing the same effect, which means it is the intended behaviour

That's just an optical illusion, the line isn't there. Let me magnify the image:

Your eye perceives lightness relative to the sorroundings. You might've seen one of these images before:

The pixel at A and B have the exact same color, but you perceive them as different ones because of the surroundings (It's also the explanations behind the infamous black-blue and white-gold dress.

The pixels in the corners have a lot of relatively darker pixels around them, this makes them look brighter than the pixels at the edges with fever surrounding darker pixels.

So, if you want quad-like gradient, then you simply can't eliminate this problem. If you however want a spherical one, then you can achieve one very easily.

Instead of using the fragment shader as a simple pass-trough one, use something that creates a circular gradient using the texture coordinates. Texture coordinates range from 0 to 1, 0.5 is the center. This means, that the distance between your current texture coordinate and `(0.5, 0.5)` can be used to create the gradient. The fragment shader is:

```
varying vec2 v_texcoord;
varying vec4 v_colour;

void main()
{
    float dist = distance(vec2(0.5), v_texcoord) * 2.0;
    dist = min(dist, 1.0);
    gl_FragColor = (1.0 - dist) * v_colour;
}

```
> 2 votes

---
Tags: glsl, opengl-es2, game-maker
---