title: Issues accessing arrays in Unity

text:
# Question
Title: Issues accessing arrays in Unity
I'm trying to make a mini quiz game, but I'm stuck. I'm showing questions, randomly, but the first question never comes up. Furthermore, when I set the size of the `questionsNumberChoosen` array to `10` and run the game, it crashes.

```
public struct Question
{
    public string questionText;
    public string[] answers;
    public int correctAnswerIndex;

    // .. we also construct the Question, directly providing all values.
}

public Text questionText;
public Button[] answerButtons;

private Question currentQuestion;
private Question[] questions = new Question[10];
private int[] questionNumbersChoosen = new int[9];
private int questionsFinished;

void Start ()
{
    questions [0] = new Question("1", new string[]{"A", "A", "A", "A", "A" }, 2);
    questions [1] = new Question("2", new string[]{"A", "A", "A", "A", "A" }, 0);
    questions [2] = new Question("3", new string[]{"A", "A", "A", "A", "A" }, 4);
    questions [3] = new Question("4", new string[]{"A", "A", "A", "A", "A" }, 0);
    questions [4] = new Question("5", new string[]{"A", "A", "A", "A", "A" }, 0);
    questions [5] = new Question("6", new string[]{"A", "A", "A", "A", "A" }, 2);
    questions [6] = new Question("7", new string[]{"A", "A", "A", "A", "A" }, 0);
    questions [7] = new Question("8", new string[]{"A", "A", "A", "A", "A" }, 4);
    questions [8] = new Question("9", new string[]{"A", "A", "A", "A", "A" }, 0);
    questions [9] = new Question("10", new string[]{"A", "A", "A", "A", "A" }, 0);

    setQuestionIndex ();
    assignQuestion (questionNumbersChoosen[0]);
}

void assignQuestion(int questionNum)
{
    currentQuestion = questions [questionNum];
    questionText.text = currentQuestion.questionText;
    for (int i=0; i < answerButtons.Length; i++)
        answerButtons[i].GetComponentInChildren<Text>().text
            = currentQuestion.answers [i];
}

public void checkAnswer(int buttonNum)
{
    if (buttonNum == currentQuestion.correctAnswerIndex)
        print ("Correct!");
    else
        print ("Incorrect!");

    if (questionsFinished < (questionNumbersChoosen.Length - 1))
        moveToNextQuestion ();
}

void setQuestionIndex()
{
    for (int i = 0; i < questionNumbersChoosen.Length; i++)
    {
        int questionNum = Random.Range (0, questions.Length);

        if (!isContain (questionNumbersChoosen, questionNum))
            questionNumbersChoosen [i] = questionNum;
        else
            i--;
    }

}

bool isContain (int[] num, int numbers)
{
    for (int i=0; i < num.Length; i++)
    {
        if (numbers == num [i])
            return true;
    }

    return false;
}

public void moveToNextQuestion()
{
    assignQuestion (questionNumbersChoosen
        [questionNumbersChoosen.Length -1 - questionsFinished++]);
}

```

# Answer
> 1 votes
You could potentially be causing problems by editing the iterator in your for loop `setQuestionIndex()`.

Try doing it without, like:

```
void setQuestionIndex()
{
    int questionIterator = 0;
    for (int i = 0; i < questionNumbersChoosen.Length; i++) {
         int questionNum = Random.Range (0, questions.Length);
         if (!isContain (questionNumbersChoosen, questionNum))
         {
              questionNumbersChoosen [questionIterator ] = questionNum;
              questionIterator ++;
         }
     }
}

```

# Answer
> 1 votes
You initialize the size of `questionNumbersChoosen` to length of 9 (or 10), and the values default to 0.

That means that anytime you randomly select `question[0]`, `isContain(questionNumbersChoosen, questionNum)` is `true`, which is considered a failure.

When the length of `questionNumbersChoosen` is 10, and 9 questions have been assigned, the only question left to choose from is `question[0], but`question\[0\]`keeps being rejected since`questionNumbersChoosen\[9\]\` is still the default value of 0.

The quickest fix is to initialize `questionNumbersChoosen[]` to a value outside of the range 0 to 9.

# Answer
> -1 votes
Though I do not see precisely what the specific problem is, I will list the few things that bother me in your code, and how you can easily find the bug yourself :

1. The loop in `setQuestionIndex()` method is error-prone and I suggest you fix it, as changing the iterator inside the loop is a bad practice imho. An option would be to do as Raeles suggests, replacing the for loop by a while (see my comment below his answer). An other option would just be to do some random permutations in your question array, which should prove more efficient.
2. I do not see where you initialize `questionsFinished` to 0. Maybe in Unity it is not mandatory to initialize variables, but still a good practice would be to explicitely write `questionsFinished = 0` in your start method.
3. You do not need to pass `questionNumbersChoosen` in the parameters of isContain as it is a class variable. That just makes the code more confusing.

Now how would I debug it if I were you? In most IDE you can easily debug your code by adding Breakpoints. Just check step by step what is happening, put one in your `setQuestionIndex` loop to see if you have an infinite loop there (as you said Unity is freezing), if not just keep going, see how the questions are ordered in your array, check the state of the variables, and you should understand the problem pretty quickly.

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


title: Modify raycast?

text:
# Question
Title: Modify raycast?
In my script, the raycast starts from a camera, and moves forward. I need to modify it to make it start from a bit far from the camera, without changing the direction.

```
Vector3 fwd = transform.TransformDirection(Vector3.forward);
RaycastHit hit;

if (Physics.Raycast(transform.position, fwd, out hit,100))
{
    print("Ray hit something !");
}
else
{
    print (" Nothing ");
}

```

# Answer
This is really quite simple.

When you cast your ray, you provide `transform.position` as your starting point. Simply change this to your desired position.

A good way to do this would be to simply add the difference to your `transform.position`. As *DCGregory* points out, you should use a multiple of `fwd`, as this already represents the local direction you intend to follow.

---

Note that in your answer, I could not tell what you meant by "a bit far". Do you want the ray to come from *behind* the camera, or start somewhat in front of it? *It does not matter*. The only difference, in the code, is if we are *adding* the offset or *subtracting* it.

**In front of camera:**

```
<summary>Approximately how far should the ray be from the camera, in game units.</summary>
float distanceFromCamera = 1.0f;
<summary>The local forward direction.</summary>
Vector3 fwd = transform.TransformDirection(Vector3.forward);
<summary>Placeholder for ray cast information.</summary>
RaycastHit hit;

if (Physics.Raycast((transform.position + (fwd * distanceFromCamera),
    fwd, out hit,100))
{
    print("Ray hit something !");
}
else
{
    print (" Nothing ");
}

```

**Behind camera:**

```
<summary>Approximately how far should the ray be from the camera, in game units.</summary>
float distanceFromCamera = 1.0f;
<summary>The local forward direction.</summary>
Vector3 fwd = transform.TransformDirection(Vector3.forward);
<summary>Placeholder for ray cast information.</summary>
RaycastHit hit;

if (Physics.Raycast((transform.position - (fwd * distanceFromCamera),
    fwd, out hit,100))
{
    print("Ray hit something !");
}
else
{
    print (" Nothing ");
}

```

---

As a final note, I am *assuming* `print(string)` is a custom method. Typically, I would simply replace these with the in-house `Debug.Log(string)`.
> 1 votes

---
Tags: unity, raycasting
---


# Question
Title: GLSL error on AMD gpu. No error on nVidia
I have an OpenGL program that works fine on nVidia card, but produces Access violation error and GL\_INVALID\_OPERATION at glDrawElements on AMD gpu.

For starters I have this geometry shader which now won't compile.

```
#version 330

// Input is triangles, output is triangle strip.
layout(triangles) in;
layout(triangle_strip, max_vertices = 6) out;

// Data passed from vertex shader.
in VertexData
{
   vec3 normal;
   vec3 view;
}  inData[];

// Data passed to fragment shader.
out FragData
{
   vec3 normal;
   vec3 view;
} frag;

// Uniforms.
uniform mat4 modelview_matrix;
uniform mat4 projection_matrix;

// Array of indexes for triangles to be split.
uniform int index[256];
uniform vec3 points[256];

uniform float split_factor;

uniform int tear;

void create_split ();
void make_face (vec4 a, vec4 b, vec4 c, vec3 normalA, vec3 viewA, vec3 normalB, vec3 viewB, vec3 normalC, vec3 viewC);

void create_split ()
{
   float f = gl_PrimitiveIDIn * split_factor;
   if ( f == 0.0f)
   {
       f = 0.2f;
   } else if ( f > 0.9f )
   {
       f = 0.9f;
   }

   vec4 midPointA = (gl_in[0].gl_Position + gl_in[1].gl_Position) * f ;
   vec4 midPointD = (gl_in[3].gl_Position + gl_in[4].gl_Position) * f;

   vec3 normalA = inData[0].normal;
   vec3 viewA = -midPointA.xyz;

   vec3 normalB = inData[1].normal;
   vec3 viewB = -midPointB.xyz;

   vec3 normalC = inData[2].normal;
   vec3 viewC = -midPointC.xyz;

   make_face (gl_in[0].gl_Position, midPointA, midPointD, inData[0].normal, inData[0].view, normalA, viewA, normalC, viewC);
   make_face (gl_in[0].gl_Position, midPointD, gl_in[4].gl_Position, inData[0].normal, inData[0].view, normalA, viewA, normalC, viewC);
}

void make_face (vec4 a, vec4 b, vec4 c, vec3 normalA, vec3 viewA, vec3 normalB, vec3 viewB, vec3 normalC, vec3 viewC)
{
   gl_Position = a;
   frag.normal = normalA;
   frag.view = viewA;
   EmitVertex();

   gl_Position = b;
   frag.normal = normalB;
   frag.view = viewB;
   EmitVertex();

   gl_Position = c;
   frag.normal = normalC;
   frag.view = viewC;
   EmitVertex();

   EndPrimitive();
}

void main()
{
    int i = 0;
    bool flag = false;

   if ( tear == 1 )
   {
      while(i < MAX && !flag)
      {
          if (gl_PrimitiveIDIn == index[i])
          {
              if (i > 0 && i < 256)
              {
                  if (index[i+1] - index[i] < 100)
                  {
                      create_split();
                      flag = true;
                  }
               }else if (i == 0 || i == 256)
               {
                  create_split();
                  flag = true;
               }

           }
           i++;
       }
   }

   i = 0;
   if (!flag)
   {
       for (i = 0; i < gl_in.length(); i++)
       {
           gl_Position = gl_in[i].gl_Position;
           frag.normal = inData[i].normal;
           frag.view = inData[i].view;
           EmitVertex();
           if ( i == 2)
           {
               EndPrimitive();
           }
       }
       EndPrimitive();
   }
}

```

Which produces those errors:

```
Compiling the geometry shader : _shaders/gs_smooth.glsl ...
Error: The shader _shaders/gs_smooth.glsl failed to compile.
Shader info log for GL index 4
Geometry shader failed to compile with the following errors:
ERROR: 0:55: error(#147) "[" array index out of range: '3'
ERROR: 0:55: error(#147) "[" array index out of range: '4'
ERROR: 0:82: error(#147) "[" array index out of range: '4'
ERROR: error(#273) 3 compilation errors.  No code generated

```

I've tried googling but nothing interesting showed up. This error is not happening on the nVidia card.

Also AMD card is R9 270 while nVidia is GTX970.

Thanks.

# Answer
> 4 votes
https://www.khronos.org/opengl/wiki/Geometry\_Shader

With input of triangles, gl\_in has a vertex count of 3. This is also covered in section 4.3.8.1 of the version 330 GLSL specification (I'm specifically citing this version because of your `#version 330`):

> All geometry shader input unsized array declarations will be sized by an earlier input layout qualifier, when present, as per the following table.
>
> Layout: triangles, Size of Input Arrays: 3
>
> The intrinsically declared input array `gl_in[]` will also be sized by any input layout declaration. Hence, the expression `gl_in.length()` will return the value from the table above.

Since you're using an unsized input layout declaration:

```
layout(triangles) in;

```

But attempting to access elements 3 and 4:

```
vec4 midPointD = (gl_in[3].gl_Position + gl_in[4].gl_Position) * f;

```

And:

```
make_face (gl_in[0].gl_Position, midPointD, gl_in[4].gl_Position, ...

```

So you're overflowing your GS input, and the AMD behaviour is actually more correct. NVIDIA is being excessively permissive and is accepting code that goes against the specification; you should correct your code.

---
Tags: glsl
---


# Question
Title: How to prevent sending semantically wrong messages in event based architecture?
I have created the following architecture in C++:

`ReceiveMessage` has two important parameters:

1. `Scope`, which defines the scope, like game object, scene or core. This determines how far the message will be forwarded. For example, core messages will be processed by `Core`, and game object messages will processed by `GameObject`.
2. `Event`, which defnes the name of the event, as an enum. This might include `FIND_GAMEOBJECT_IN_RANGE`, `PLAY_SOUND`, etc.

---

If I accidentally send an event that can only be handled by `Core` with the game object scope, instead of core, it is only checked at runtime. Currently, it is possible to send a message like `ReceiveMessage(GAMEOBJECTS, PLAY_SOUND, ...);`. This would be forwarded to every game object, and won't be handled, because the `PLAY_SOUND` event is only properly handled by `Core`.

How do I redesign my messaging system so that the compiler will give an error or warning when I try to send a message with an invalid scope-event pair?

# Answer
You didn't specify language, but there's some options that should work regardless. The first question to ask yourself is if this is a problem that actually needs solving, though; is this a hypothetical problem you have with your code or are you wasting considerable time/money by frequently sending events to the wrong places?

**Signals and Slots**

One is to move away from a generic event broadcaster and to use direct message types and registrations. Think Qt's signals and slots. In order to send an event you must call an explicit `handleEventType(EventType event)` method; if it doesn't exist, you can't call it.

This tends not to scale well for things like game objects because a system emitting an event doesn't know which objects care about. However, it works very well for systems receiving events, since there tends to be a small number of those.

*Signals Variant*

A variation of that would be to invert your event flow. Instead of sending messages *to* receivers, send messages *from* emitters, and anyone interested in the event finds the appropriate event emitter and registers.

This works very well for any kind of event, so long as the event's emitter is well-known; e.g., it doesn't work well for events emitted by game objects. For example, it works well for events emitter by systems that an object or another system is interested in.

The combination of these two approaches can potentially solve both the sending of events to systems from systems/objects and the sending of events from systems to systems/objects, but neither approach handles well the case of sending events from objects to object. You can keep your existing approach for that case though and solve your original question by only allowing the generic message system to be valid for objects and never your core systems.

**Event Queues**

You could move away from immediate-mode events and instead to generate event lists during system updates, and the lists persist until next frame. Subsequent systems can then iterate over all the event lists they may care about. This is the approach that many data-oriented enthusiasts prefer.

This scales fairly well and is easy to extend. It will work very poorly if your game objects or components have their own `update` methods and you're not keeping the meat of your game logic in systems that operate on collections of components/objects. Given your use of UML diagrams (hello 1990's, welcome back!) I'd bet strongly that this approach isn't going to work well with your architecture. :)

**Separate enums**

You mention enums for types. You could use different enums for each context and make the handler only accept appropriate enums. If a message is valid in multiple context, just add its key to both enums; if you make them use the same value, you can even forward messages dynamically. You can use explicit ranges of message identifier values to denote which range is shared so you can quickly check that any dynamic message is multi-context.

Basically, `Core::HandleMessage(ECoreMessage type, ...)` vs `GameObject::HandleMessage(EObjectMessage type, ...)`.

**Tag Types**

This is a more advanced version of the `enum` approach that relies on there being specific types for each message, e.g. a `struct` or something that contains event payload.

You can use inheritance or C++ type traits to augment any message with one or more context tags that denote which context(s) it is compatible with. This can be enforced via the type system to make it a compile-time error to send the wrong kind of message to the wrong context.

This can be tricky to implement and embeds a lot of data into the type system in very awkward ways. If you're looking for a compile-time fix to an object-based dynamic message system, this might be your best bet, but I'd consider it a last resort.

**Revisit the Necessity**

I want to stress again that you should really be sure you need any of this. The problem you're describing has come up *so rarely* in years of working on an engine that allows it, in my experience. Some of your examples also, to me, seem like they're better uses for *functions* and not events. If the only possible receiver of a `PlaySound` event is the audio system, why are you sending an event instead of just `audio->playSound(...)` ?

If the argument is decoupling object relationships (I see this one a lot), just keep in mind that converting functions into messages and tossing them through a generic message router doesn't decouple anything; your whole question is basically about how you can statically check the relationship between a message and its receiver.
> 1 votes

# Answer
In a comment you said that every message is only valid for one scope. When that's the case, you actually have three separate message systems here and should have separated infrastructures for them.

Create separate `enum`'s for GameObjectMessageId, SceneMessageId and CoreMessageId. Also create three separate methods `ReceiveGameObjectMessage(GameObjectMessageId, ...)`, `ReceiveSceneMessage(SceneMessageId, ...)` and `ReceiveCoreMessage(CoreMessageId, ...)` (If your programming language supports method overloading, you can call them all just `ReceiveMessage` and have them differ by their parameter). Have each class of event receiver only implement those methods which are relevant for it.

When you are using a programming language which has type safety for enumerations at compile-time, you will be prevented from passing an event to an object which is not supposed to handle it.
> 2 votes

# Answer
I got some ideas, might be in random order:

1. I personally do not prefer too much use of `enum`, especially when it's tied to classes, i.e. `GAMEOBJECTS` if designed for `class GameObject`. The tying makes it harder to expand/modify the code base, So my first move would be remove the enum and do not rely on it.
2. It looks like `ReceiveMessage(Scope scope, EventName name, ...)` would do some `if (name == xx)` or `switch(name)` work inside, which I personally feel tedious. Also you are concerning not to receive irrelevant messages. So the second move would be find a way to let event dispatcher directly fire the event to exactly who wants to receive it.

So, anyway, I suggest to implement the event system like the signal & slot system mentioned by Sean Middleditch. And I suggest to check the Unreal Engine 4's event system -LINK HERE-, which is also written in C++, so it might help you a lot. Note that UE4 uses the term "delegate" for the event dispatcher. For the event receiver to receive the message, they bind their listener function to the delegate, and it's done. By the way you can also check C#'s delegate architecture, they are very alike.

The advantage of such system is that:

1. The event dispatcher would be a member variable, so it looses inheritance tree. You don't have to let every class who wants the ability to fire/receive event to inherit anything, just declare a member and it's done.
2. Since it's a member, you can have multiple members, each of them represent different messages.
3. Since each of them represent different messages, you can have different parameters and types and whatever for them.
4. The dispatchers just fire, don't care about the receivers, which is very easy task for the dispatchers.
5. The receivers "bind" themselves to the dispatcher, and can "unbind" anytime they want, so you can control when/how to react to the messages.
6. Since the receivers have to bind to each dispatcher, the listener function can be separated, and they can have different parameters (basically the same as the delegate's parameters).
7. In this design, the event scope and name won't be needed, since the dispatcher's variable name, variable type, and parameters fired directly represent the scope and name, and in a better way.

I'll give some conceptual example codes of the suggested solution:

```
class MyObject1
{
public:
    // this is UE4's syntax, which creates a new type of dispatcher
    // this line creates a dispatcher of type `MyMessageType1`, and 1 parameter of string
    DECLARE_DELEGATE(MyMessageType1, string);
    MyMessageType1 message;

    void DoSomething()
    {
        string result = "";

        // ... do many things
        // things are done and good, send a message

        result = "good!".
        message.Broadcast(result);

        // note here, the listener can be anyone,
        // and the dispatcher doesnt care, just fire.
    }
}

class MyObject2
{
public:
    void Initialize()
    {
        MyObject1* obj1 = SomehowYouHaveThePointerOfSomeObj1();

        // bind this object and its function to the dispatcher,
        // and the message would be received when dispatcher do the `Broadcast()`.
        obj1.message.Bind(this, &MyObject2::OnReceiveObj1);
    }

    void OnReceiveObj1(string result)
    {
        if (result == "good!")
        {
            // whatever
        }
    }
}

```
> 0 votes

---
Tags: c++, architecture, events, messaging
---


title: How to change FoV in vertex shader?

text:
# Question
Title: How to change FoV in vertex shader?
Is it possible to change the Field of View vertex shader? I zoom my camera by changing the FoV value. However this will cause the skybox also be zoomed and this is not what I wanted. Is it possible to change the FoV value of the projection matrix in vertex shader?

Specifically, I pass the projection matrix by uniform to a glsl shader. I want to change the FoV value of the projection matrix (to make a new projection matrix) in the vertex shader of the skybox.

# Answer
**Yes, it's possible**

If we look at a typical vertex shader transform (source) we might see something like this:

```
vTrans = projection * modelview * incomingVertex;

```

So if we have access to our projection and our modelview matrices from the vertex shader, we can just use a different projection matrix to achieve the desired effect.

As we know, one way of constructing a projection matrix involves feeding it FOV, together with a few other params, for example, this from GLM (source):

```
// Generates a really hard-to-read matrix, but a normal, standard 4x4 matrix nonetheless
glm::mat4 projectionMatrix = glm::perspective(
    FoV,         // The horizontal Field of View, in degrees : the amount of "zoom". Think "camera lens". Usually between 90° (extra wide) and 30° (quite zoomed in)
    4.0f / 3.0f, // Aspect Ratio. Depends on the size of your window. Notice that 4/3 == 800/600 == 1280/960, sounds familiar ?
    0.1f,        // Near clipping plane. Keep as big as possible, or you'll get precision issues.
    100.0f       // Far clipping plane. Keep as little as possible.
);

```

You can see the matrix this generates in the GLM source code here: https://github.com/g-truc/glm/blob/0.9.5/glm/gtc/matrix\_transform.inl#L208

```
T const rad = fovy;
T const tanHalfFovy = tan(rad / static_cast<T>(2));

detail::tmat4x4<T, defaultp> Result(static_cast<T>(0));
Result[0][0] = static_cast<T>(1) / (aspect * tanHalfFovy);
Result[1][1] = static_cast<T>(1) / (tanHalfFovy);
Result[2][2] = - (zFar + zNear) / (zFar - zNear);
Result[2][3] = - static_cast<T>(1);
Result[3][2] = - (static_cast<T>(2) * zFar * zNear) / (zFar - zNear);

```

So if you just rewrite this code in GLSL, plugging in a different FOV value, you can construct your new projection matrix on-the-fly in your vertex shader.

It's actually even easier, because since all you're changing is elements `[0][0]` and `[1][1]` you can copy off the existing projection matrix and just change those elements.

**But you probably don't want to do it**

The first thing you should notice is that this will involve some extra calculations in your vertex shader, including some trigonometry. It's lightweight enough but it will impact performance.

If you're doing CPU-side frustum culling (and you really should be) then your newly constructed projection matrix will not be valid for your frustum, so you'll either end up drawing too much (more performance impact) or not enough (resulting in cleared or hall-of-mirrors regions at the sides of the window), depending on how you adjust FOV.

You will need to send the new FOV as a uniform to your shader.

That last one is crucial: **since doing it requires sending a new uniform to your shader, you may as well just send a different projection matrix instead and avoid all of the other issues**.
> 1 votes

---
Tags: shaders
---


# Question
Title: Where to find an example of the Actions?
I do not work Actions.moveTo.

```
actor.addAction(Actions.moveTo(500, 500, 1));

```

Please show me a working example.

Thank you.

`ADD CODE`:

```
stage.addActor(actor);
actor.addAction(Actions.moveTo(500, 500, 1));

```

...

```
@Override
public void render () {
    Gdx.gl.glClearColor(1, 1, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
}

```

# Answer
As long as you call `act` with the `delta time` on your `Stage` then any `Action`s that you have on the `Actor`s in that `Stage` will be affected.

Looking at your `render` method this looks correct, so I can only assume the problem is when you set up the `Actor` and its corresponding `Action`.

A working example could look something like this:

```
package com.bornander.lpcsandbox;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Image;

public class LpcGdxGame extends ApplicationAdapter  {
    SpriteBatch batch;
    Texture img;
    Stage stage;

    @Override
    public void create () {
        batch = new SpriteBatch();
        img = new Texture("badlogic.jpg");
        stage = new Stage();
        Image image = new Image(img);
        image.addAction(Actions.moveTo(100,100, 5));
        stage.addActor(image);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }
}

```
> 1 votes

---
Tags: libgdx
---


title: Is MSAA broken in Unreal 4.14?

text:
# Question
Title: Is MSAA broken in Unreal 4.14?
I'm trying to use the new forward rendering with MSAA in GearVR, on a Galaxy S6. But there's definitely no antialiasing going on. At all.

After a lot of time searching online and in the editor I found the following variables which potentially could be related to turning MSAA on:

1. *Window \> Developer Tools \> Device Profiles \> Android:*

* r.MSAACount
* r.MSAACompositingSampleCount
* r.DefaultFeature.Antialiasing
* r.MobileOnChipMSAA
* r.MobileMSAA
* r.MobileContentScaleFactor

None of the above seem to make a difference if I change them from within the Device Profiles editor within UEd.

2. *Edit \> Project Settings \> Engine \> Rendering \> Default Settings \> Anti-Aliasing Method:*. Setting it to MSAA does nothing.

3. I also tried setting all of the previous variables from within DefaultEngine.ini and nothing.

There's got to be something I am overlooking. If anyone has any thoughts I'd really appreciate it.

# Answer
> 0 votes
Turns out that:

1. MSAA is enabled by default for mobile.
2. The Forward renderer in 4.14 has nothing to do with mobile. It's new only for desktop (i.e. HTC Vive and Rift).

As to how to check that MSAA is indeed enabled:

You can check when running on the device in the logcat by searching for: `LogHMD: Enabling r.MobileOnChipMSAA, previous value 0`

You can also add a log (and recompile the engine) at *OpenGLRenderTarget.cpp: line 201*. You want to make sure you are hitting: `glFramebufferTexture2DMultisampleEXT`

Since the else branch in this codepath would otherwise create a non multisampled FBO.

The MSAA sample count however, appears to be hardcoded to 2 somewhere else in the engine source. After a long discussion in the Oculus forums I was told I could change the sample count (to have MSAA x4 for instance) at line 152:

```
`// TODO: Mali supports 4x with similar hit as 2x, should we do something smarter here? Hard coded to 2 everywhere else
            const uint32 SampleCount = 2;

```

But this codepath is not being executed when running on the device. So not sure where else the 2 might be hardcoded.

---
Tags: android, unreal, antialiasing, gearvr
---


# Question
Title: How can I convert screen space to GUI Space/View Space?
Is there any way available to convert screen space into view space as like in the following figure:

# Answer
Assuming that you know the values of `Camera.pixelWidth` and `Camera.pixelHeight`, you can get from the last picture to the middle one by simply dividing your ScreenSpace coordinates respectively by `Camera.pixelWidth` and `Camera.pixelHeight`.

```
Vector2 screenSpacePosition = new Vector2(100, 100);
Vector2 viewportSpacePosition = new Vector2(screenSpacePosition.X / Camera.pixelWidth, screenSpacePosition.Y / Camera.pixelHeight)

```
> 1 votes

# Answer
Can't you just use `Camera.ScreenToWorldPoint` or `Camera.WorldToScreenPoint`? As you can guess from methods names, they are transforming screen position to world position, and vise versa.

The only thing you need to take into account is Z axis, which will be same to Z value of camera position.
> 0 votes

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


# Question
Title: How can I make my Color Mixing game more difficult?
I am making my first game and it is coming out too simple. Are there standard "techniques" to making it more difficult?

The game is pretty simple. Picture the game 2048. When you slide in a direction the blocks all slide that direction and collide or merge. But instead of merging *numbers* (like 2+2=4 in 2048) it merges *colors*, so a yellow block hitting a blue block makes a green (and red + yellow = orange, etc.) Then if you merge a primary color (blue) and a newly created secondary color (green) it makes a tertiary color (in this case "blue-green").

At that point you can tap on the tertiary color (what I have deemed a "tertiary-bomb") and it will destroy all of it's primary colors, so "blue-green" will destroy all "blue" blocks. You lose if you can no longer move, same as 2048, but it seems to be far too easy not to get stuck, by creating bombs.

How would an experienced game designer make this game less trivial?

# Answer
> 10 votes
Consider the player's options / resources & look for ways to limit them. Here's a technique taken from Jesse Schell's Art of Game Design (which he in turn credits to game designer Rob Daviau):

List out all of the assumptions you're making & consider ways to invalidate them. Here are some examples based on what you've described (or left out) about the game so far. Your description leads me to assume:

* Turn based game play - what happens if you add a time limit?
* Fair random number distribution - what if you periodically skewed things favor certain colors based on pieces in play?
* Equal value in clearing any color - what if clearing certain colors was worth more (either in terms of points, more time on the clock or free bombs)?
* Any tertiary piece can become a bomb - what if:
    + they were a limited number per minute?
    + only certain colors could bomb others (i.e. can only clear red with \[red red blue\] combo)?

Some of these will undoubtedly be complete nonsense. That's okay. If nothing else, the bad ideas will reassure you that the base assumptions they failed to invalidate were good decisions. And some of the time you'll encounter a really interesting twist that you wouldn't have considered.

Note: it can be difficult to realize your own assumptions about your own work. If you have a prototype, consider letting person A watch person B play the prototype & then ask A what they perceive to be the ground rules of the game.

# Answer
> 7 votes
Trainyard had a mechanic where if you allowed all three primary colours to mix (eg. a secondary plus the other primary, or two dissimilar secondaries), you'd get a murky brown colour which was effectively dead weight. You couldn't get rid of it once you'd made one, so you had to plan your moves carefully to ensure the wrong colours never came in contact.

A mechanic like that might be a way to add escalating pressure, creating blocks you can't eliminate (or maybe only a tertiary bomb can eliminate them?) and restricting your moves.

---

Another angle you may want to investigate is nerfing the tertiary bomb, as the current version sounds quite powerful considering it can be made in just two steps. Some possibilities:

* Tertiary bombs can only destroy (chains of) adjacent blocks, so there's some strategy to arranging them before detonation.

Or they can only destroy a muddy brown block, as a way of recovering from a previous mistake.
* Tertiary colours aren't bombs, they just turn back to their dominant primary if mixed with that primary one more time (diluting the other primary out).

Combined with the above rule about muddy browns, primaries are your safest colours because they blend with most things, and compound colours are liabilities. Tertiaries become a way to remediate a secondary back into safe primaries again - so the strategy becomes about managing how many compound colours you have in play at once.

---

A third angle is to restrict the moves the player has available. For example, if two colours share a primary, but aren't similar enough to mix into a single block, they "stick" together when they touch, until one of them changes colour or is eliminated.

This bars one of the avenues for merging the block with another, since now it has this other colour in the way. And it can stick out like a shelf, interfering with the transport of blocks in the adjacent row/column.

If the player isn't careful, they could turn their playfield into a big tarball of almost-but-not-quite matching colours, limiting their flexibility to respond to new situations.

---
Tags: game-design, balance, difficulty
---


# Question
Title: pyOpenGL draw loop - slow with just 1500 items to draw
I've been trying to build myself a simple little game API using pyOpenGL (previously I tried using just Tkinter, but I keep hitting the same wall whatever I do!)

I rewrote everything using my very limited knowledge of OpenGL and came up with the following for my draw loop:

```
def _draw(self):
    vertex_count = 0
    items = 0
    coords = numpy.array([], numpy.float32)

    for item in self.graph:
        z = item.z - 1
        if z < 0:
            z = 0

        x1 = item.x * 2.0 / self.width - 1
        y1 = (item.y+z*item.height) * 2.0 / self.height - 1

        x2 = (item.x+item.width) * 2.0 / self.width - 1
        y2 = ((item.y+z*item.height)+item.height) * 2.0 / self.height - 1

        coords = numpy.hstack((coords, numpy.array([
        # X,    Y,      Z     U,                                V
        x1,     y2,     0.0,  self.sprite_sheet[item.frame][0], self.sprite_sheet[item.frame][1],
        x2,     y2,     0.0,  self.sprite_sheet[item.frame][2], self.sprite_sheet[item.frame][3],
        x1,     y1,     0.0,  self.sprite_sheet[item.frame][4], self.sprite_sheet[item.frame][5],
        x1,     y1,     0.0,  self.sprite_sheet[item.frame][6], self.sprite_sheet[item.frame][7],
        x2,     y2,     0.0,  self.sprite_sheet[item.frame][8], self.sprite_sheet[item.frame][9],
        x2,     y1,     0.0,  self.sprite_sheet[item.frame][10], self.sprite_sheet[item.frame][11],
        ], numpy.float32)) )

        vertex_count += 6

    glBufferData(GL_ARRAY_BUFFER, coords.nbytes, coords, GL_STATIC_DRAW)
    vertices = glGetAttribLocation(self.shader_program, 'a_position')
    tex_coords = glGetAttribLocation(self.shader_program, 'a_texCoords')

    glEnableVertexAttribArray(vertices)
    glEnableVertexAttribArray(tex_coords)
    glVertexAttribPointer(vertices, 3, GL_FLOAT, GL_FALSE, 20, None)
    glVertexAttribPointer(tex_coords, 2, GL_FLOAT, GL_TRUE, 20, ctypes.c_void_p(12))

    return vertex_count

```

... in calling func ...

```
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Clear all pixels.

count = self.scene._draw()

glDrawArrays(GL_TRIANGLES, 0, count)

glutSwapBuffers()
glutPostRedisplay()

glFlush()

```

I'm testing it with a window 720 x 512, drawing a simple set of 2d tiles 32x32 each, so ~1500 items in total, but it is sooo slow, each frame is taking about 0.1 seconds. I thought I'd be safe with OpenGL until I was trying to draw \>10,000 things!

I have tried a few permutations of building 1 big array and writing it all in one chunk (as above), or creating a big empty buffer then using `glBufferSubData()` to write in each item as needed (still creating a `numpy.array()` for each item then writing it to the buffer).

I have a very simple vertex and fragment shader which really just pass everything through:

```
attribute vec3 a_position;
attribute vec2 a_texCoords;

uniform mat3 u_matrix;

varying vec2 v_texCoords;

void main()
{
    gl_Position = vec4(a_position, 1);

    v_texCoords = a_texCoords;
}

```

and

```
uniform sampler2D u_image;

varying vec2 v_texCoords;

void main()
{
    gl_FragColor = texture2D(u_image, v_texCoords);
}

```

Sorry for the giant walls of code, trying to be thorough.

Have I done something terribly stupid?

# Answer
From the code you presented to us, it appears as though your issue is with how you're creating an array every frame in your render loop. In my experience, you should minimize the logic within a render loop to close to nothing. A rendering loop should be a read-only pipeline, in which you're reading and drawing from arrays and assets that have already been previously created. All your assets should be initialized before the rendering loop starts, this naturally includes any arrays, etc.

If performance is a primary concern for you, you should be doing *nothing* during your rendering cycle—*absolutely nothing*; even if statements hinder performance in a small way. Not that this should dissuade you, it's just a truth that comes with game development. It should also be noted that most games(depending on complexity involved) don't even need to go all out with Vertex Buffer Objects, and all the new candy that's available. In fact, one game, Minecraft, still uses Display Lists and Immediate mode for most of their rendering. Essentially, the voxels of any given chunk are compiled into a single display list after being heavily optimized by a face-combining algorithm. Each chunk can then be rendered with a single draw call, leaving only Frustum Occlusion testing to be done within the rendering frame. It's super fast, and serves as proof that you don't need to use VBOs to achieve optimal performance.

Just remember, when writing a rendering loop you need to obey the KISS principle. Do as little as you can, and aim for zero array creations/string allocations(which are internally arrays)/Object Creations. It should all be done before hand.
> 1 votes

---
Tags: opengl, python
---


# Question
Title: How i can do colisions with irregular hitboxes?
I'm developing my new platform engine and i don't know how to program collisions with slopes - I'm using hitboxes. For the collisions of rectangles i use this:

```
if (player.rec(Position, level.scale).Intersects(t.rec(level.scale)))

```

but this doesn't work for sloped collisions or triangular hitboxes. How can I do this?

# Answer
You want to read up on PIP algorithms. You'll be also able to find many implementations, even in C#. Here is my suggestion:

```
public static List<Vector3> intersectShape
    (Geometry polygon_to_cross_0, Geometry polygon_to_cross_1)
{
    List<Vector3> list_vertices = new List<Vector3>();

    for (int i = 0; i <= polygon_to_cross_1.Points_.Count - 1; i++)
    {
        if (Geometry.isInsideOf(polygon_to_cross_1.Points_[i], polygon_to_cross_0))
            list_vertices.Add(polygon_to_cross_1.Points_[i]);

        if (i < polygon_to_cross_1.Points_.Count - 1)
        {
            foreach (Vector3 p in Geometry.getIntersectionVertexGeometry(
                new Vector3[]{ polygon_to_cross_1.Points_[i],
                polygon_to_cross_1.Points_[i + 1] }, polygon_to_cross_0))
            {
                list_vertices.Add(p);
            }
        }
    }

    for (int i = 0; i <= polygon_to_cross_0.Points_.Count - 1; i++)
    {
        if (Geometry.isInsideOf(polygon_to_cross_0.Points_[i], polygon_to_cross_1))
                list_vertices.Add(polygon_to_cross_0.Points_[i]);

        if (i < polygon_to_cross_0.Points_.Count - 1)
        {
            foreach (Vector3 p in Geometry.getIntersectionVertexGeometry(
                new Vector3[] { polygon_to_cross_0.Points_[i],
                polygon_to_cross_0.Points_[i + 1] }, polygon_to_cross_1))
                {
                    list_vertices.Add(p);
                }
            }
        }

        return sortPolygonClockWise_XZ((list_vertices));
    }

```

`Count(intersectShape(Geom1, Geom2)) > 0 == true` stands for collision.
> 1 votes

# Answer
It is not just a rectangle/rectangle test. It is also a dot product test to determine which side of the slope line the other object is on. For this you will need to initialize the 2 end points of your slope. This becomes a line segment and the corners of your slope's collision rect. So your slope and rect both share point A & B.

The algorithm gos like this:

If other object is in the rect, check which side of the line it is on,

If above,

```
 No collision,

```

else

```
 Collision

```

In XNA, that would go something like this,

```
if(objectRect.Intersects(slopeRect)
{
  Vector2 objectRelativePosition = objectPosition - PointA;
  Vector2 slopeRelativePosition = PointB - PointA;
  Vector3 slopeNormal3 = Vector3.Cross(Vector3.UnitZ, Vector3(slopeRelativePosition,0));
  Vector2 slopeNormal = Vector2(slopeNormal3.X, slopeNormal3.Y);

  if(Vector2.Dot(slopeNormal, objectRelativePosition) > 0)
    {
      //object is above slope, no collision
    }
    else
    {
      // object is below slope, collision
    }
}

```

The slopeRelativePosition, slopeNormal3, & slopeNormal can all be done only once in the initialization of your map, not each frame. but `objectRelativePosition` must be recalculated each time you want to run a collision check with the slope.

You can also run this check against each point that makes up the object (say, each corner of a rectangle) if there is no single "position" for the object.
> -1 votes

# Answer
I'm think it can be done like this:

```
class Tile
{
    public virtual float GetTileY(float pX)
    {
        return 1; // Mean tile size is 1x1 units; I'm using 1 unit = 8 pixels, for example.
    }
}

class SlopeTile : Tile
{
    public bool IsFlipped; // If true look like |\, if false - like /|.
    public override GetTileY(float pX)
    {
        return this.IsFlipped ? 1 - pX : pX;
    }
}

```

You send to GetTileY() value from 0 to 1 that mean how far on this tile player standing and get height, also as value from 0 to 1.

```
Vector2 position = ...;
Vector2 offset = ...;
Tile tile = ...;
float new_x = position.X + offset_x;
float new_y = position.Y + tile.GetTileY(new_x % 1);

```

Note, I'm not a professional but I'm also trying to make platformer and this is way I'm want to make slopes.
> -2 votes

---
Tags: xna, c#
---


title: Line vs Triangle wrong computation

text:
# Question
Title: Line vs Triangle wrong computation
I used the Möller-Trumbore algorithm. That seemed to work for a while but I found a bug:

```
const glm::vec3 avert0 = glm::vec3(-0.13f, 0.01f, 0.0f);
const glm::vec3 avert1 = glm::vec3(-0.01f, 0.01f, 0.0f);
const glm::vec3 avert2 = glm::vec3(-0.13f, 0.1f, 0.0f);

const glm::vec3 start = glm::vec3(-0.1f, 0.05f, -1.0f);
const glm::vec3 end = glm::vec3(-0.1f, 0.05f,    1.0f);

rayIntersectTriangle(start, end, avert0, avert1, avert2, position);

```

The above code does *not* collide ( u is \< 0 ). However, if I change the Z value of the end vector from 1 to 30, it works:

```
 const glm::vec3 end = glm::vec3(-0.1f, 0.05f,    30.0f);

```

---

Here is my implementation:

```
bool Node::rayIntersectTriangle(glm::vec3 orig, glm::vec3 dest
              , glm::vec3 vert0, glm::vec3 vert1, glm::vec3 vert2
              , glm::vec3 &result)
{
const glm::vec3 edge1 = vert1 - vert0;
const glm::vec3 edge2 = vert2 - vert0;
const glm::vec3 pvec = glm::cross(dest, edge2);
const float det = glm::dot(edge1, pvec);

static const float Epsilon = std::numeric_limits<float>::epsilon();

/*
   If det is below zero, we are back facing the triangle.
   If det is close to zero we are missing the triangle.
*/
if (det > -Epsilon && det < Epsilon)
  return false;

const float invDet = 1.0f / det;

const glm::vec3 tvec = orig - vert0;

result.x = glm::dot(tvec, pvec) * invDet;
if (result.x < 0.0f || result.x > 1.0f)
  return false;

const glm::vec3 qvec = glm::cross(tvec, edge1);

result.y = glm::dot(dest, qvec) * invDet;
if (result.y < 0.0f || result.x + result.y > 1.0f)
  return false;

result.z = glm::dot(edge2, qvec) * invDet;

return true;
}

```

# Answer
> 0 votes
I think the code only works for single sided tests. I have used a similar function before (adapted from the book: Real-Time Collision Detection by Christer Ericson) that does a double sided check:

```
template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

bool same_sign(const float a, const float b) {
    return sgn(a) == sgn(b);
}

float scalar_product(const glm::vec3& a, const glm::vec3& b, const glm::vec3& c) {
    return glm::dot(glm::cross(a, b), c);
}

bool IntersectLineTriangle(glm::vec3 p, glm::vec3 q, glm::vec3 a, glm::vec3 b, glm::vec3 c,
float &u, float &v, float &w)
{
    const glm::vec3 pq = q - p;
    const glm::vec3 pa = a - p;
    const glm::vec3 pb = b - p;
    const glm::vec3 pc = c - p;

    glm::vec3 m = glm::cross(pq, pc);
    u = glm::dot(pb, m);
    v = -glm::dot(pa, m);
    if (!same_sign(u, v)) return 0;
    w = scalar_product(pq, pb, pa);
    if (!same_sign(u, w)) return 0;

    const float denom = 1.0f / (u + v + w);
    u *= denom;
    v *= denom;
    w *= denom; // w = 1.0f - u - v;
    return true;
}

```

That returns a positive result for the inputs you give, although it may not be what you after.

**EDIT1: possible explanation**

I think the original function is giving a incorrect answer because the test works on the assumption that start-\>end passes through a triangle where the verts are defined counterclockwise. But the points above have the line segment going through the triangle from the other direction:

which effectively reverses the winding of the verts, from the point of view of the line segment. The double sided test takes this possibility into account and returns the proper result.

**EDIT2: Original function should take direction, not end vector**

After looking at the article I think I've found the error, I believe your original function should be taking the direction vector, rather than the end vector. It should look something like this:

```
bool rayIntersectTriangle(
    const glm::vec3& orig, const glm::vec3& dir,
    const glm::vec3& vert0, const glm::vec3& vert1, const glm::vec3& vert2,
    glm::vec3 &result, float& t)
{
    const glm::vec3 edge1 = vert1 - vert0;
    const glm::vec3 edge2 = vert2 - vert0;
    const glm::vec3 pvec = glm::cross(dir, edge2);
    const float det = glm::dot(edge1, pvec);

    static const float Epsilon = std::numeric_limits<float>::epsilon();

    /*
       If det is below zero, we are back facing the triangle.
       If det is close to zero we are missing the triangle.
    */
    if (det > -Epsilon && det < Epsilon)
      return false;

    const float invDet = 1.0f / det;

    const glm::vec3 tvec = orig - vert0;

    result.x = glm::dot(tvec, pvec) * invDet;
    if (result.x < 0.0f || result.x > 1.0f)
      return false;

    const glm::vec3 qvec = glm::cross(tvec, edge1);

    result.y = glm::dot(dir, qvec) * invDet;
    if (result.y < 0.0f || (result.x + result.y) > 1.0f)
      return false;

    result.z = 1.0f - result.x - result.y; // barycentric w = 1 - u - v
    t = glm::dot(edge2, qvec) * invDet; // ray intersection

    return true;
}

```

then call it like so:

```
rayIntersectTriangle(start, glm::normalize(end-start), avert0, avert1, avert2, position, t);

```

---
Tags: raycasting
---


title: How do I make perfect sprite sheets?

text:
# Question
Title: How do I make perfect sprite sheets?
I made a .GIF using sprite sheet animation, but I do not think it is working properly, because it shivers at the base. I made it in Photoshop Max Power.

How do I easily make perfect sprite sheets with images? I want to be able to add my images, resize them for my game and create a sprite sheet. Alternate software recommendation might be considered.

# Answer
> 1 votes
Seems like you cropped the images to the characters bounds for each frame. The images are being drawn from a fixed point in space and thus will appear to shift. An easy fix would be to have a fixed size for your image. This size should be big enough to fit the largest frame.

If this easy fix simply takes up too many texture space then you should manually fix each frame. Often you end up with some kind of atlas to lookup the frames within the sheet. Here you can make changes depending on the atlas format.

---
Tags: animation, spritesheet
---


# Question
Title: creating a simple cartoon like light effect
I could like to create a really simple light engine that does not eat to much CPU and will produce this effect:

I am using libgdx for my game with box 2D light (which is too heavy for my needs). I have no idea of what is the best solution to create this effect (shapeRenderer? pure shader?). For the moment I don't need any shadow casting, but I would like to be able to maintain multiple light sources and to add color to the light.

# Answer
I have finally opted for the following solution:

1 - creating a frame buffer and drawing some full opacity circle on top of it

2 - rendering this frame buffer using this opengl blend function on the scene

```
GL20.GL_SRC_COLOR, GL20.GL_ZERO

```

this function will substract occlusion mask opacity from the destination opacity

I know it is not a cartoon render here, but the exact same technique can be applied without the gradient to achieve a more cartoonish look
> 0 votes

---
Tags: libgdx, shaders, lighting
---


# Question
Title: GameObject with Audio File called with FindGameObjectWithTag returns "Object reference not set to an instance of an object"
I'm puzzled with this error because in a different file (see below), I'm doing exact same process to an object to enable/disable and works fine. But this new object throws the error, the object has a Script calling an audio file.
Enabling manually the Object, and playing the game the audio is fine. I hit the check box to disable it and I get the error "Object reference ..." This audio object is attached to another GameObject which is the character of the game.

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

    [RequireComponent(typeof(BoxCollider2D))]
    public class carController : MonoBehaviour {

        public float carSpeed;
        public float maxPos = 4.17f;

        Vector3 position;

        public ParticleHit pr;
        public AudioManager cr;
        public Blast cb;

                audioObj = GameObject.FindGameObjectWithTag("policeAuTag");
                audioObj.SetActive (true);
                cr.carSound.Play ();

```

What am I doing wrong.? I have closed and reopened unity but nothing. I have changed the tag name but same error.

I have tried also "FindWithTag" and doesn't work.

What is causing the code to throw errors?

# Answer
> 8 votes
**What is going on?**

It is not `FindGameObjectWithTag` that's returning that error. I guess what you are actually seeing is something like this:

> NullReferenceException: Object reference not set to an instance of an object carController.Start () (at Assets/carController.cs:*line-number*)

Where *line-number* is the line number for `audioObj.SetActive (true);` and this is the actual source of the error.

This kind of error (a `NullReferenceException`) for that specific line can only mean that `audioObj == null`.

**How to fix it?**

So why is `audioObj` assigned `null` by `FindGameObjectWithTag`? There is no documentation entry for that function but `FindGameObjectsWithTag` is close enough:

> Returns a list of **active** GameObjects tagged `tag`.

Emphasis mine; so `FindGameObjectWithTag` returns `null` when no active game object with the specified tag can be found.

So don't deactivate this game object from the editor. Do one of these instead:

* Store a reference to the game object in `carController.Start` or `carController.Awake` and deactivate it immediately. Then use that reference to activate it.
* Deactivate the relevant specific component or components on the game object and activate those.

# Answer
> 2 votes
I recently had this problem where I would start a scene with disabled objects and be unable to access them or enable them later on. Start the scene with your object enabled but add `gameObject.SetActive(false);` to the end of your `Start()` method in the last script on your `gameObject`. Link.

In your case, adding `gameObject.SetActive(false);` to `AudioManager` script should do it, but if you have that on other objects and you want them to be active, you should make a new script.

I'm not sure why this happens but I think Unity just doesn't bother loading inactive items at scene start (at least in the Editor).

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


# Question
Title: What format is this 3D model in or how can I change my rendering code to accept obj files?
I have a file in my project that defines 2 numbers and 4 arrays:

```
#define NUM_TEAPOT_OBJECT_VERTEX 824
#define NUM_TEAPOT_OBJECT_INDEX 1024 * 3

static const float teapotVertices[NUM_TEAPOT_OBJECT_VERTEX * 3] =
{
    // ...
};

static const float teapotTexCoords[NUM_TEAPOT_OBJECT_VERTEX * 2] =
{
    // ...
};

static const float teapotNormals[NUM_TEAPOT_OBJECT_VERTEX * 3] =
{
    // ...
};

static const unsigned short teapotIndices[NUM_TEAPOT_OBJECT_INDEX] =
{
    // ...
};

```

These, together with a texture as jpeg, define a teapot 3D model.

How can I generate these arrays from a 3D model? Our 3D models are in `.obj` (and a `.jpeg` for texture).

I use these arrays in the following code:

```
Vuforia::Matrix44F modelViewMatrix = Vuforia::Tool::convertPose2GLMatrix(result->getPose());
// OpenGL 2
Vuforia::Matrix44F modelViewProjection;

VuforiaApplicationUtils::translatePoseMatrix(0.0f, 0.0f, kObjectScale, &modelViewMatrix.data[0]);
VuforiaApplicationUtils::scalePoseMatrix(kObjectScale, kObjectScale, kObjectScale, &modelViewMatrix.data[0]);
VuforiaApplicationUtils::multiplyMatrix(&projectionMatrix.data[0], &modelViewMatrix.data[0], &modelViewProjection.data[0]);

glUseProgram(shaderProgramID);

glVertexAttribPointer(vertexHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)teapotVertices);
glVertexAttribPointer(normalHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)teapotNormals);
glVertexAttribPointer(textureCoordHandle, 2, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)teapotTexCoords);

glEnableVertexAttribArray(vertexHandle);
glEnableVertexAttribArray(normalHandle);
glEnableVertexAttribArray(textureCoordHandle);

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, augmentationTexture[0].textureID);
glUniformMatrix4fv(mvpMatrixHandle, 1, GL_FALSE, (const GLfloat*)&modelViewProjection.data[0]);
glUniform1i(texSampler2DHandle, 0 /*GL_TEXTURE0*/);
glDrawElements(GL_TRIANGLES, NUM_TEAPOT_OBJECT_INDEX, GL_UNSIGNED_SHORT, (const GLvoid*)teapotIndices);

glDisableVertexAttribArray(vertexHandle);
glDisableVertexAttribArray(normalHandle);
glDisableVertexAttribArray(textureCoordHandle);

```

If you know how I can adapt this code to load standard 3D models, such as `.obj` files, please help.

# Answer
Your code seems like it works in a reasonable way to display a 3D model. What you're missing is actually reading in a .obj file. The .obj file format is a fairly well documented format. You need to read the vertex, texture coordinate, vertex normal, and index data from the file and construct your arrays to match how you've told OpenGL you've laid them out. The `l`, `p`, and `f` commands in the file tell you the index order for each of the other 3 types of data (vertex coordinates, texture coordinates, and normals). (And note that they don't have to match - you can have vertex index 1 with texture coordinate index 53 and vertex normal index 312.)

One strategy would be to do 2 passes. One that reads all the data in from the files, and another that then copies them into new arrays with the appropriate order so the indices match.

There probably already exist libraries to do this, though I've never personally used any. An internet search will surely turn up some.
> 1 votes

# Answer
http://www.assimp.org/ Open Asset Import Library (short name: Assimp) is a portable Open Source library to import various well-known 3D model formats in a uniform manner. The most recent version also knows how to export 3d files and is therefore suitable as a general-purpose 3D model converter. See the feature list.
> 1 votes

# Answer
I would support @bobenko suggestion to use assimp. Also, there is a lot of code to be write, even if you have a scene graph as returned by assimp. Instead it is better if you can using an existing library to do the rendering for you at a higher level.

I would suggest using `open frameworks`, which also has an Assimp Model Loader.

You can find an example to load a model here. The two most important steps here in are to load the model and then draw it, the code for which really is:

```
ofxAssimpModelLoader model;
model.loadModel("file_name.3DS");

void ofApp::draw(){
   ofBackground(50, 50, 50, 0);
   ofSetColor(255, 255, 255, 255);

   model.setPosition(ofGetWidth()/2, (float)ofGetHeight() * 0.75 , 0);
   model.drawFaces();
}

```

You should be able to easily adapt the above linked example to load your `.obj` files.
> 1 votes

---
Tags: c++, 3d, opengl-es, models
---


# Question
Title: How can I randomly generate objects inside of a Complex Area?
In my game, I want to generate randomize enemies inside of this green area that I made with a custom editor tool.

# Answer
1. Triangulate the area.
2. Pick a random triangle.
3. Generate a random point inside that triangle (link).
> 6 votes

# Answer
This might not be the most elegant solution, but it might work for you:

Drawback: Should the polygon for some reason have an area of zero, you will run into an infinite loop. It can even become a performance bottleneck when the area is just very small compared to the area of the bounding box. You can mitigate that problem by limiting the maximum number of tries, but then you no longer have a guarantee that every spawn will be successful.
> 4 votes

---
Tags: unity, c#, mathematics, coordinates
---


# Question
Title: How could an offline app store images so that they aren't trivially discoverable?
There is an app I play which has lots of images. I have reverse engineered the app but couldn't find the images in the APK. The app is an offline app so it doesnt retrieve images from a server.

My question is, then, where did this app store its images? I'd like to achieve the same level of protection (to deter casual observation of the images).

# Answer
You could download the images once, at first launch, as theorized in the comments. Or encrypt them locally with a key that is sent over the internet. Both of these options would require an internet connection at least *once* though. If you want to store your image data in a fashion that isn't trivially discoverable, but also does not require an internet connection *ever*, you have a few possibilities:

* Store the images in code. This means either write code to generate the image (as @Water suggested in the comments), or store the actual byte buffer of the image file in a global or static variable some place in your game's executable. Images that are completely procedurally generated (the first variant) won't really be discoverable at all. Images that are stored as buffers in code probably won't be found by programs that just unpack all the bundled files in the APK, but they may be found by programs that scan the entire application archive for patterns that look like potential known image file formats.
* "Encrypt" (or more reasonably "obfuscate") the files so that they can't be trivially read. You could simply flip every other byte of the image, which would likely make it look like garbage when opened. This technique was employed by a game of my childhood, TaskMaker; they compressed the picture resources that stored all the game graphics with a custom algorithm that was sufficient to render them unreadable by most basic resource-editing tools of the era. This technique will hide the contents of the image but may not hide the fact that the images exist.

You can of course combine these techniques for maximum impact. Because the data is still there, and the method to correctly access the data is still there, neither of these techniques can make it *impossible* to find the image data, but they can make it so most people who are just casually poking around won't find anything you don't want them to see, probably.
> 0 votes

---
Tags: android
---


# Question
Title: How to use 3D models in video games? (Copyright related)
There are many gray areas in using 3D models online that may be free, creative commons with specific terms, or public domain. I notice many 3D models being sold by artists that are exact replicas of known vehicles (eg. BMW,Honda,etc.(with emblem)). I would think in this situation there will be some sort of infringement especially if someone bought that model and used it in their video game, no matter if it was marked as royalty free. I would appreciate if someone with experience could assist in clarifying some of the following areas. Please note, this is the information I have inferred based of personal research, may not be factual, please correct me if I am wrong.

Commercial Use: Of course never sell someone's 3D model, but what part of that is considered theirs; if they made a model of an RC car, are the wheels legal to use, the chassis, engine especially if the creative textures(or meshes) are removed and all that is the mere form of the object. (Eg. if I 3D model a nail/screw; that is not considered copyright protected because it is a 'common'/'useful' object)

Free Usage: If your product is free, my assumption is that game devs could use a 3D model as long as they change textures, colors, etc. But form of the object is all for grabs.

Commercial Use & Free Use: If the product/game you are using is free, but you have advertisements bringing you revenue that may be on the side of a website or phone app and pop up every now and again; does this make it acceptable?

Thank you ahead of time!

# Answer
> 1 votes
You'd generally want a lawyer to advise you on any specific situation that seems convoluted to you. That said, in general:

When you purchase or otherwise acquire a piece of art (e.g., you download it from a "free art" website), that transaction will come with a license agreement. Many of those sorts of websites put the agreement up *once*, somewhere on their website, so you might need to dig to find it.

The license agreement will say what your rights are with respect to the piece of art. Do not do anything that you are not licensed to do with it. If you have any doubts, such as for example if the license grants you use of the art, but the art contains trademarked designs or logos et cetera that the license does not explicitly provide usage rights to you for, you will probably want to stay away from the art. You can contact the author and request clarification, or engage the services of a lawyer who could help you unravel the complexity of the appropriate IP law, but generally you are better off staying away from anything that could be somebody else's intellectual property that you are not explicitly granted permission for in the license agreement.

---
Tags: 3d, models, art, copyright
---


# Question
Title: How to make a death screen without making it a new state?
You must be confused by the question, let me explain. In some games, when you die, it shows a death screen but the background is sometimes transparent and shows the game play. how to do that. here are a few pictures to help out: And sorry for advertising

# Answer
Just keep the game playing behind UI overlay. If you have some AI, which is dependent on player's presence, then do something like this:

```
private void Update() {
  if (player.isAlive) {
    UpdateAI();
  }
}

```

If your enemies are based on FSM, make a new "Wonder" state, in which they act as if there was nobody to attack. Things not dependent on player, should work correctly after player's death.
> 1 votes

---
Tags: screen
---


title: How do I get the object color?

text:
# Question
Title: How do I get the object color?
I want to get the object color, when I start the game. How do I do this?

```
public Renderer cube;
public float r,b,g,a;

void Start() {
            r = cube.GetComponent<Renderer>().material.color =
            b = cube.GetComponent<Renderer>().material.color =
            g = cube.GetComponent<Renderer>().material.color =
            a = cube.GetComponent<Renderer>().material.color =

}

```

# Answer
> 6 votes
Its actually simple. Just use Color32 class to get the r, b, g, a of your desired gameobject. Here is an Example Code. Here I used a cube gameobject and got the color of its material.

```
public class FirstScript : MonoBehaviour
{
// Use this for initialization
  void Start ()
  {
    Color32 objColor;
    objColor = gameObject.GetComponent<MeshRenderer>().material.color;

    print(objColor.r + " "+ objColor.g + " "+ objColor.b+ " "+ objColor.a + " ");
  }
}

```

---
Tags: unity, color
---


title: PlaySound() Lags opengl c++

text:
# Question
Title: PlaySound() Lags opengl c++
I am new to OpenGL. I am making a game similar to this, shown in image below. The problem is when I detect collision, i.e cannon ball and ship collide, I play a sound using

```
PlaySound(TEXT("explode.wav"), NULL, SND_FILENAME);

```

After the sound is played, my background animation and the whole scene is stuck for a second and then it resumes. Any fix? Please help. It is my project.

# Answer
> 6 votes
Looking at the documentation of PlaySound() on MSDN it states:

> The **SND\_ASYNC** flag causes **PlaySound** to return immediately without waiting for the sound to finish playing.

The conclusion from this information, although not explicitly stated there, is that PlaySound() waits for the sound to finish playing, if the **SND\_ASYNC** flag is *not* specified. Therefore the lag you experience when playing a sound has not to do with OpenGL but with the fact that PlaySound() just waits for the sound to finish before it returns, thus blocking the calling thread.

So the proper code for non-blocking (i.e. asynchronous) sound should be:

```
PlaySound(TEXT("explode.wav"), NULL, SND_FILENAME | SND_ASYNC);

```

If you want to stop an asynchronous sound before it is finished, use

```
PlaySound(NULL, 0, 0);

```

---
Tags: c++, sound, winapi
---


# Question
Title: How do I convert positions between local coordinate systems?
Say I have *worlds* and *levels*. Each world contains multiple levels. Levels have their own coordinate system, centered around their pivot point (assume its centre, for example). These level coordinates are expressed in floats.

Each level have has int64 coordinate.

Now I have game objects which should seamlessly travel between levels in the world. How can I transition between coordinates inside these levels?

# Answer
What you have is the basics of 3D math, without any rotation. In 3D, we generally refer to an object's position as its translation, and set of things that describe its position (its translation, and its rotation) in space as the transform. In this case, since we are not talking about rotated objects, then we can assume that an object's transform is the same as its translation.

Just to illustrate, let's say we have 2 levels, one called Level A, and one called Level B. Each of those Levels has a position in the world, that is the level's *world transform*. You have a bullet, we'll call it Bullet 1, and that Bullet resides in Level A at some position. Bullet 1's position relative to level A is called the *local transform*.

The neat thing about transforms is that you can apply a transform to another transform, and you will get a new transform out that is a combination of the two. Let's make a simple example, let's say Level A's *world transform* is (10, 10). This means it is 10 units away from the world on the X axis, and 10 units away on the Y axis. Level B will have a *world transform* of (5, 1). Now let's say that Bullet 1 is inside Level A, and inside Level A, Bullet 1's position is (2, 3). We can now say that Bullet 1's *local transform* is (2, 3). What do we do if we want to find Bullet 1's position in the world? This is known as finding Bullet 1's *world transform*. Well, Bullet 1 is in Level A, and the center of Level A is at (10, 10) in the world, and Bullet 1's position relative to the center of Level A is (2, 3), so we can just add them together. In math terms, this is "Applying the world transform of Level A to the local transform of Bullet 1", and what you get out of this operation is "The world transform of Bullet 1", or in English, the position of Bullet 1 in the world.

Phew, ok, so one more concept before we go on. When we apply the world transform of Level A to the local transform of Bullet 1, we add them together. What if we had the world transform of Bullet 1 and we want to find the local transform of Bullet 1 relative to Level A (the position we started with!)? Why, it should be obvious, we subtract the numbers we just added, in other words, we subtract the world transform of Level A from the world transform of Bullet 1. But we only know how to apply transforms, and that is adding! Well, we can fix that, instead of subtracting a number, we can just add the negative number, and this does the same thing. The negative version of the world transform of Level A is (-10, -10), in math terms, this is called the *inverse transform*.

So now we have all the tools we need to solve this problem. I've explained them in a way that may seem complicated, but it's actually some very simple math, but these concepts are important in 3D and game development, and will help things you read make more sense, so please bear with me. Let's go through all the things we have first. World Transform of Level A: (10, 10) World Transform of Level B: (5, 1) Local Transform of Bullet 1 relative to Level A: (2, 3)

What we want to find is Local Transform of Bullet 1 relative to Level B.

First, we need to get the *world transform* of Bullet 1, or, where the bullet is in the world. To get that, we will apply the world transform of Level A to Bullet 1: (10, 10) + (2, 3) = (12, 13). So now we have World Transform of Bullet 1: (12, 13)

To find where it is relative to Level B, we need to find the *inverse world transform* of Level B, also known as its negative, (-5, -1). If we have the World Transform of Bullet 1, and the Inverse World Transform of Level B, then adding those together will give us the Local Transform of Bullet 1 relative to Level B. Now we have: Local Transform of Bullet 1 relative to Level B: (12, 13) + (-5, -1) = (8, 12)

Ok, we finally have what we started out to get. We take the position of Bullet 1 relative to Level A, and we add in Level A's position relative to the world. This gives us where Bullet 1 is in the world. Then we want to find where it is relative to Level B, so we subtract the world position of Level B from the world position of Bullet 1 and we're left with the position of Bullet 1 relative to Level B.

Hopefully this helps!
> 3 votes

---
Tags: transformation, coordinates, open-world
---


# Question
Title: MPL 2.0 in perspective of game development and selling
I am planning to use a math library named Eigen3 which is under MPL 2.0.
However, I am not sure what MPL 2.0 means.

As a game developer, who want to sell `game.exe` (probably by Steam or GoG) who does not wish to distribute source `.h`/`.cpp`, here is what I understand MPL 2.0 :-

1. I have to tell the buyers of my game that I use **Eigen3**, and provide a reasonable-and-almost-free way (how? Is attaching a description `.txt` enough?) to download code of **Eigen3**.
2. If I just call some functions of **Eigen3** and I don't modify any part of the library, I don't have to distribute any of modification of anything.
3. There are no other obligation.

## **Question**

1. How should I provide them source code of **Eigen3** *in practice*?
2. Is there any wrong about my understanding?

# Answer
> 5 votes
This is not the best site to get legal advice (not sure if the SE legal site is good for game licenses either).

I used TLDRlicense for MPL 2.0. Based on what it says, the answers to your questions are:

1. You should provide them a link. Something like "You can download the source code for Eigen3 at http://eigen.tuxfamily.org" (or whatever the right URL is)
2. No, your understanding is correct.

The "usual" way to do this is provide a `license.txt` or `credits` file/screen (or something similar) which lists all copyright-related things. Here's where you can provide the link and notice about Eigen3.

---
Tags: licensing
---


# Question
Title: Creating a player that can hold different items
I am making a game using Java, LibGDX and Box2D. What would be the best way to create a player that can hold:

* no item
* one item from group A
* one item from group B
* one item from both groups

Items from group A can only be used to attack, and are held in the right hand.
Items from group B can only be used to defend, and are held in the left hand.

Should I add the item to the player class and render/update the item in the player class? Or is there any best way to this that I am not aware?

This is the best way I know how to do it:

I would also be interested in any design pattern that could be applied to this situation.

# Answer
> 3 votes
I'd say, don't sweat it. Your character's two hands are independent of one another, the two items groups have distinct interfaces and are meant to be used in different ways. Just use a properly-typed reference for each hand, there's no need for type erasure or fancy design patterns.

```
public class Player {

    private DefenceItem leftHandItem;
    private AttackItem  rightHandItem;

    // ...

    public void update() {
        // Update yourself

        if(leftHandItem != null)
            leftHandItem.update();

        if(rightHandItem!= null)
            rightHandItem.update();
    }

    public void draw() {
        // Draw yourself

        if(leftHandItem != null)
            leftHandItem.draw();

        if(rightHandItem!= null)
            rightHandItem.draw();
    }

    public void attack() {
        if(rightHandItem!= null)
            rightHandItem.attack();
    }

    public void defend() {
        if(leftHandItem != null)
            leftHandItem.defend();
    }
}

```

I've kept these simple `void()` methods for the example, but passing the required information around won't be problematic since all type information is preserved.

---
Tags: java, libgdx, box2d, design-patterns
---


# Question
Title: Can someone explain me how rayCast works?
Im learning libgdx and one of the things that really confuses me its raycasting. I read a tutorial of how to use it and I understand it but I really want to know what's in the back. I searched for the source code of this method.

```
public void rayCast (final RayCastCallback callback, float point1X, float point1Y, float point2X, float point2Y) {   // FIXME pool RayCastCallback?
    world.raycast(new org.jbox2d.callbacks.RayCastCallback() {
    @Override
    public float reportFixture (org.jbox2d.dynamics.Fixture f, Vec2 p, Vec2 n, float fraction) {
        return callback.reportRayFixture(fixtures.get(f), point.set(p.x, p.y), normal.set(n.x, n.y), fraction);
    }
}, this.point1.set(point1X, point1Y), this.point2.set(point2X, point2Y));

```

} How we can see this method calls itself recursively and returns a call to reportRayFixture of the callback variable. The thing that really confused me it's from where the code select the Fixture, and how its checks every fixture. Can someone explain me really how its works.

This its the source code page https://github.com/libgdx/libgdx/blob/master/extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/com/badlogic/gdx/physics/box2d/World.java

I will appreciate it!

# Answer
> 1 votes
Raycasting is when we draw an invisible line through space and see what it intersects with. A common use for this is to figure out what a player is clicking on- we draw a line from the camera in the direction that the player is clicking, and the first object our line touches is the line the player clicked on.

In Box2D, the RayCastCallback interface is used to allow you to write code that gets executed when your ray hits a Fixture (for example, you may want to ignore certain fixtures). I haven't used this personally, but I imagine you could use something like this in a shooter game to see if a wall-penetrating weapon could hit an object behind a wall (or something like that).

At a high level, what this *lovely* piece of code is doing is a little slight of hand- if you look at it really closely, what it's doing is taking in the **libGDX** RayCastCallback and wrapping it in a **JBox2D** RayCastCallback which has a slightly different API. It's more like it's overloading the method than calling it recursively.

What I *don't* know is why the author chose to create the Point1 and Point2 instance variables. I would think if you had multiple fixtures they would get overridden, so perhaps they are supposed to contain the last fixture hit by the ray? Even so, it looks like multiple raycasts would overwrite them.

---
Tags: java, libgdx, physics
---


# Question
Title: How do I get Input Positive Button value in Runtime?
In *Unity* in InputManager I assigned `R` Button to "Restart" name.

Now that property (Restart) has another property with a key "Positive Button" and string value "R".

In the game I can show notice to user: "click `R` for Restart!"

But what if user will change that key in the start config window? For example from `R` to `T` button.

Now the game should display notice: "click `T` for Restart!"

**Question:** How do I get changed Positive Button value by name "Restart" via script in Runtime? Is it possible?

---

p.s. in Editor I can do this:

```
SerializedObject inputManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/InputManager.asset")[0]);
SerializedProperty axisArray = inputManager.FindProperty("m_Axes");

for (int i = 0; i < axisArray.arraySize; ++i) {
    var axis = axisArray.GetArrayElementAtIndex(i);
    var axisName = axis.FindPropertyRelative("m_Name").stringValue;
    if (axisName == "Restart") {
        restartButtonValue = axis.FindPropertyRelative("positiveButton").stringValue;
        break;
    }
}

```

But it allows to use it only in the Editor. Because it uses `UnityEditor.dll`

# Answer
Unfortunatly, **this isn't possible right now**.
Like you said, it uses the Editor library.
The only option left is to use an entierely different system to manage all inputs. Take a look on the asset store for system like this.
> 1 votes

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


# Question
Title: A class for all levels or for each level an own class?
My Game become more complex with each new Level or Map that I design. The game is an basic rpg game like Pokemon.

For now I have one class that organize all Maps but different maps have special features and different Monsters.

Better use for each Map an own Class and have duplicated code or is there a specific pattern for this?

Edit: My Problem: I can load the new map and play but all maps have different monsters and different events. I can't put all of them in the Game class and check all the time everything.

my class diagram in simple:

# Answer
> 1 votes
The problem you have can be solved by Inheritence. Make a base Map class with overridable functions. If you need to, you can extend the Map class for specific behaviors. You don't need to "duplicate code" this way, since you can call a function called `Foo()` from a child class which will ALSO call `Foo()` from the parent class.

## Should I use a specific class for each map behavior?

In my opinion, yes. If your maps have mostly similar behaviors except for a few things, you can and should use inheritance to your benefit. It's also great for organizing map behaviors and keeping you sane, and your code will look cleaner.

As DMGregory has noted, maps are usually JUST data, so creating a new class for a specific ordering of tiles and objects is not necessary. An array or an XML file can do that for you. Your Map class should ONLY be in charge of doing things with the data, not holding onto the data in the editor. You should have a separate class or file with your map data in it and hand it to your Map class, which will render it and control the update loop. Try not to let you map do too many things at once, though. Because of this, it may be pertinent to rename your `Map` class to `MapController` or something similar, so that it's clear what exactly it does. Then you can extend for specific behaviors beyond that like `SwampController` or `DesertController`

---
Tags: design-patterns
---


# Question
Title: How to remove Sharp Edges on Texture in Libgdx Game
I am making the above Libgdx game but I have come across the problem of really sharp images for my background if I zoom out of the world.

As you can see on the screenshot there are really sharp edges that appear surrounding the texture of the purple background.

How can I make the Texture blend well with the surrounding?

# Answer
After talking with Rowland Mtetezi(the post creator), we found a way to solve his problem. The sharp edges were caused because he was using different objects with the same texture for the background, instead of using a wrap texture repeat and use just one object. Then, the solution was to use:

```
texture.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);

```

To repeat the texture through the entire background, instead of placing different consecutive objects with the same texture.
> 1 votes

---
Tags: libgdx, textures
---


# Question
Title: Libgdx: api fadein() and fadeout() methods are switched?
I've been trying to create a white-screen fade effect for my libgdx game.

When I run the following code with `fadeOut = false`, nothing happens (white-screen does not appear because alpha is 0). When `fadeOut = true`, it works (fades out) until the actors alpha is down to `0.5f`, then it rebounds and starts fading in. No clue why.

```
    if(fadeOut){
        map.setColor(new Color(1, 1, 1, 1));
        addAction(Actions.fadeOut(duration));
    }else{
        map.setColor(new Color(1, 1, 1, 0));
        addAction(Actions.fadeIn(duration));
    }

```

When I run the exact same code but switch the starting alpha's like this:

```
if(fadeOut){
        map.setColor(new Color(1, 1, 1, 0)); //notice this is 0 now
        addAction(Actions.fadeOut(duration));
    }else{
        map.setColor(new Color(1, 1, 1, 1)); // notice this is 1 now
        addAction(Actions.fadeIn(duration));
    }

```

When I run this code with `fadeOut = false`, nothing happens (screen is all white though, because starting alpha is 1). When `fadeOut = true`, it actually fades in. sigh...

---

Here's the draw method i'm running, but I doubt there's an issue there.

```
@Override
public void draw(Batch batch, float parentAlpha){
    batch.draw(texture, 0, 0);

    //Get the current color of the actor
    batch.setColor(getColor());

    act(Gdx.graphics.getDeltaTime());

}

```

I really don't know why this is happening, any insight would be valuable.

Thanks!

---

Edit: Here's the full code I'm using to call the fades:

I have a "StartScreen" object that gets initialized (and contains the stage), and this piece of code is in it's constructor:

```
fade = new Fade((int)GdxGame.getWidth(), (int)GdxGame.getWidth(), Color.WHITE, fadeOut, duration);
stage.addActor(fade);

```

In the same StartScreen class, I have the following code to draw the stage:

```
@Override
public void render() {
    super.render();
    stage.draw();
}//end render

```

The following code then calls the "Fade" objects constructor which has the code mentioned above:

```
public Fade(int width, int height, Color color, boolean fadeOut, float duration){

    this.fadeIn = fadeOut;
    this.duration = duration;

    Pixmap map = new Pixmap(width, height, Pixmap.Format.RGBA8888);

    if(fadeOut){
        map.setColor(new Color(1, 1, 1, 1));
        addAction(Actions.fadeOut(duration));
    }else{
        map.setColor(new Color(1, 1, 1, 0));
        addAction(Actions.fadeIn(duration));
    }

    map.fillRectangle(0, 0, width, height);

    texture = new Texture(map);

    map.dispose();
}

```

---

Update: Changing the alpha with this line:

`map.setColor(new Color(1, 1, 1, alpha));` to `0.2f` or `0.7f` works fine. Though that's because it's changing the alpha of the pixmap (and later becomes the texture)- which leads me into investigation of whether `fadeOut or fadeIn` change the texture's alpha or something else...

# Answer
> 0 votes
**Big Edit:** The reason the above didn't work was because I was changing the Alpha of the pixmap, and not the texture. Huge mistake, should work after creating a texture with the pixmap.

---

After a while of playing around, I arrived at a conclusion that `fadeIn` and `fadeOut` are defective. I was able to solve this issue (more below), but without using Actions. This solution below creates a new thread and starts a fade animation over time.

```
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.Actor;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class Fade extends Actor {

public enum FadeType{
    FADE_IN,
    FADE_OUT
}

private Texture texture;

private Color color;
private AtomicFloat alpha = new AtomicFloat(); //I actually use a custom made AtomicFloat class
private final AtomicInteger duration;

private FadeType fade;

private AtomicBoolean isFading = new AtomicBoolean(false);

public Fade(int width, int height, Color color, FadeType fade, int duration){

    this.color = color;
    this.fade = fade;
    this.duration = new AtomicInteger(duration);

    Pixmap map = new Pixmap(width, height, Pixmap.Format.RGBA8888);
    map.setColor(new Color(color.r, color.g, color.b, alpha.get()));
    map.fillRectangle(0, 0, width, height);

    texture = new Texture(map);

    map.dispose();
}

public void startFade(){
    isFading.set(true);

    new Thread(new Runnable() {
        @Override
        public void run() {

            final int start = (int)System.currentTimeMillis();

            int current;
            float delta;

            do{
                current = (int)System.currentTimeMillis();

                delta = current - start;

                alpha.set( (fade == FadeType.FADE_OUT) ? delta/duration.get() : 1 - delta/duration.get() );

            }while (delta < duration.get());

            isFading.set(false);
        }
    }).start();

}//startFade

@Override
public void draw(Batch batch, float parentAlpha){

    if (isFading.get())
        batch.setColor(new Color(color.r, color.g, color.b, alpha.get()));

    batch.draw(texture, 0, 0);
}

}//Fade

```

You would use this code like so:

```
//create a new face object
Fade fade = new Fade(screenWidth, screenHeight, Color.WHITE, Fade.FadeType.FADE_IN, 3000);

//add the fade object to the stage (fade extends actor)
stage.addActor(fade);

//then call this method where ever needed
fade.startFade();

```

After battling this issue for a while, I hope this helps someone out.

---
Tags: java, libgdx, scene2d, alpha
---


# Question
Title: Character implementation and architecture
Me and a friend are trying to make an RPG in Java, while we are learning the language, and we have been discussing the character implementation. We would like to know which is the best solution in computational and expanding criteria s.

The game will be something like Final Fantasy 6. We would have a lot of different characters, each having their own stats and 3 different abilities. The stats would change frequently, and be saved for future reference. It's not supposed to have two identical characters.

---

**Option 1:** My idea defends that there would be a class "Hero", and a class to every character that would extend Hero. For example, if I have 10 characters, there would be 10 classes that extend "Hero". This character class would contain all variables concerning stats and a method for each ability. We would implement a singleton pattern, to assure there is only ever one instance.

---

**Option 2:** For my friends idea, the object "Hero" would have several attributes, the more important ones being for name, stats and character class. While name and stats can be summarized as simple variables, a character class is manifested as an object of its own tied to a specific hero. In short, an instance of a character class is bound only to one "Hero", but many heroes can have a common character class. For example, Josh and John can both be "Fighters", but they don't share the same instance of the character class object; they're just similar in functionality.

A "Hero" **must** have a character class in order to work properly, therefore his creaion would demand his own name and the name of a character class.

This method guarantees much higher flexibility when it comes to creating heroes, since the use of generic character classes (having many "Fighters" in a party, for example) becomes possible; in fact, this idea of character classes can be expanded for use with enemy units. However, it will require a bit more processing power.

# Answer
> We would like to know which is the best solution in computational \[...\]
>
> \[...\] it'll require a bit more processing power.

Stop right there. This is a non issue. The scope of these character classes is so small in comparison to what you'll have to compute when managing physics and graphics that it's really not worth to take that into consideration now.

You should still *profile* your game once in a while and make sure the processing power goes to the right place.

> Option 1

It's ok to have specialized classes that inherits a base class. You could even make your base class an interface and have all the Heroes specialized.

But *please*, **don't use singletons**. Find another way to enforce that, i.e. make the rest of your design aware of it, or make it enforce it.

> Option 2

It seems to be the same design as what's in option 1, but you use composition over inheritance.

> this idea of character classes can be expanded to be used on enemy units

You said it :) Go with that, and don't bother with 'processing power' now, it's quite trivial.
> 6 votes

---
Tags: java, architecture, character
---


# Question
Title: How should I implement a dialogue box in Pygame?
I'm working on a small RPG with Pygame, using Python 3.5.1. I've spent a week trying to find a decent tutorial or example for a dialogue box implementation that would pull dialogue from a source file (eg. an XML file) and support choices, with little success. Of course, getting the data is a trivial task. However, I can't think of a good way to implement the presentation side.

Here's my question: **What would be the best way to implement a dialogue system that supports choices, while keeping the code relatively easy to understand?**

In case you want to take a peek at the project, the source code can be found here.

# Answer
> -1 votes
Well after you draw out the area for all the options and stuff, in python using pygame, you can make an if statement for every choice that there may be and in response pull out a specific (if there is a specific dialogue) piece of the dialogue. Another thing you could do is create a dictionary which would save you time, and run the if statements.

---
Tags: python, rpg, pygame
---


title: Disable a Prefab when Clicked

text:
# Question
Title: Disable a Prefab when Clicked
I want to disable the Question Prefab so that when it is clicked the Prefab behind it will be shown:

I am using Unity 5.3.5 and C#.

# Answer
> I created a new gameObject and added this script:

Why did you created a new gameObject when you wanted to disable the prefab clones?.

There's nothing wrong with the *given* code. You should put the script on your **Prefab**.

If it still doesn't work. You can use EventSystems to get the Game Object that is currently selected and deactivate it.

Check this link for how to use Event Systems.
> 0 votes

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


# Question
Title: How to make even animations with sprite sheets in Unity 5?
When importing a sprite sheet into Unity and dividing it up, what is the best way to do so to ensure that your animation works smoothly? Is there a mathematical formula for dividing the spritesheet evenly, and should you use Grid By Cell Size or Grid By Cell Count?

Also, can the free version of TexturePacker help with organizing sprites for Unity? Or are there other alternatives to the software?

# Answer
No maths formula is needed, as long as you decompress the sprite sheet you can use automatic splicing, or experiment with different x and y numbers on the grid by cell size and grid by cell count until you're happy.

As for animation there is a very good animation and animator within Unity, I suggest you look at the Unity Documentation to get to grips with it(it is a bit big to put in a post).

Useful links:

Animator Controller

Animation

Hopes this helps.
> 1 votes

---
Tags: unity, 2d, spritesheet
---


# Question
Title: LibGDX - Image width is not set to resetting to zero when full width
I am making a progress bar for showing the players current experience. However I have come around to a bug, which appears when the player is maxing out his experience and then is getting a new level. In the ideal world my code should reset the progress bar image width (which is a Scene2D image btw), but for some reason it is not setting the image width to zero, but is setting it to its full width instead, which I can't seem to understand why. I hope anyone can help me.

I have provided my code below, and also uploaded a video on youtube with my bug - Video of the bug

The method below is the one I use to change the experience progress bar width as well as the experience.

```
public void changeLevelExperience(int gainedExperience) {
    float maxExpDividedInPixels = 131f / this.GAME.gameScreen.getGameManager().maxExperience;

    this.GAME.gameScreen.getGameManager().currentExperience += gainedExperience;

    if (this.GAME.gameScreen.getGameManager().currentExperience >= this.GAME.gameScreen.getGameManager().maxExperience) {
        this.GAME.gameScreen.getGameManager().currentLevel++;
        this.currentLevelLabel.setText(this.GAME.gameScreen.getGameManager().currentLevel + "");
        //TODO: Another arrangement for the experience needs to be made.
        this.GAME.gameScreen.getGameManager().maxExperience += 35;
        this.GAME.gameScreen.getGameManager().currentExperience = 0;
        Gdx.app.debug(TAG, this.GAME.gameScreen.getGameManager().currentExperience + "");
    }

    this.levelProgressBar.setWidth((int) (maxExpDividedInPixels * this.GAME.gameScreen.getGameManager().currentExperience * this.scaleFactor));
}

```

# Answer
> 0 votes
I found the bug. It was with some help from people at a facebook group. :)

The bug occours, because my Scene2D Image (the level progress bar) was a child of a scene2D Table. And the Table was initially set to have a column width to the width of the image, when it was at its largest size. This width was now set to zero, as I have done in the code below.

```
table.add(this.levelProgressBar).width(0 * this.scaleFactor).height(10 * this.scaleFactor);

```

Apparently the Image width is reset to the tables column width,when it is set to the width of zero. Thank you all which tried to help me. It was really appreciated :)

# Answer
> 3 votes
I haven't personally used `ProgressBar` yet, but it looks like the right way to set the current percentage is using `setValue(float)`, not `setWidth(float)`. I'd start with that.

---

Also, saving your `GameManager` object in a local variable instead of writing `this.GAME.gameScreen.getGameManager()` 10 times will make the code a lot more legible ;)

---
Tags: java, libgdx, software-engineering
---