title: LibGdx Table not firing touch events

text:
# Question
Title: LibGdx Table not firing touch events
I can easily add listeners to the actors within a table, and they will fire events, but if I want an entire to table to have 1 listener and do not care to have differentiated effects depending on where it is touched, I want to be able to add the listener directly to the table. However, it is not firing, at all. I have turned on debug and tried pressing within the labels in the table or outside of them (still in the table, like on padding), but to no avail.

This is how I add the create the table:

```
il = new InfoListener();// extends ClickListener
info = new Table(skin);
info.setBackground("default-rect");
info.setVisible(false);
info.addListener(il);
info.setDebug(true);

// later on I have a method that adds things to the table
info.clear();
info.add(item.getDescription()).padRight(5);

info.setVisible(true);
info.setSize(info.getPrefWidth(), info.getPrefHeight());

```

It is a dynamic table (i.e. I change it's children when necessary), but that shouldn't make a difference. How do I have the table fire touch events?

# Answer
> 1 votes
Wow wow wow. So `clear()` removes all children, actions, **and listeners**...

All I needed to change was `clear()` to `clearChildren()`...

---
Tags: java, libgdx
---


# Question
Title: How can I add an animation curve to an object with no animations?
I want to scale text in different ways over time. I figured the best way to do this would be an animation curve. It turns out I need an actual animation clip just to create this curve.

My question is, is there a way to create and use an animation curve, or something like it, without making a redundant animation for this object? If not, is there anyway to create empty animation clips from the Unity editor?

Importing empty animations from third party applications into Unity just to use the animation curves seems ridiculous.

# Answer
> 2 votes
You can simply create an AnimationCurve, sample it overtime and use the value to modify an object parameter, such as scale:

```
public AnimationCurve myCurve; //let's say you edit from inspector, but you can built at runtime if you prefer

float t;
void Update()
{
  t+= Time.deltaTime;
  float val = myCurve.Evaluate(t);
  transform.localScale = Vector.one * val; //or do whatever you want with the curve value
}

```

---
Tags: unity, animation
---


title: 3d compute shaders in order access

text:
# Question
Title: 3d compute shaders in order access
I'm working on a compute shader for a 3d texture where I want to evaluate pixels in a specific order, is there any way to do this? let's say that I have made a texture using the following code;

```
tex = new RenderTexture(64, 64, 0);
tex.volumeDepth = 6;
tex.isVolume = true;
tex.enableRandomWrite = true;
tex.Create();

```

Now let's say that for example I want to make the following computation on the gpu rather then cpu:

```
tex[0]=basetex //all values where z =0 are some basic 2d texture
for(int z=1;z<6;z++){ //loop over every z level
 for(int x=1;x<64;x++){ //loop over every x level
        for(int y=1;y<64;y++){ //loop over every y value
         tex[x][y][z-1]=tex[x-1][y][z-1]+tex[x-1][y][z-1]+tex[x][y-1][z-1]+tex[x][y+1][z-1] //add all values next to this pixel on the z value bellow
      }
  }
}

```

# Answer
> The individual invocations within a work group will be executed "in parallel". The main purpose of the distinction between work group count and local size is that the different compute shader invocations within a work group can communicate through a set of shared variables and special functions. Invocations in different work groups (within the same compute shader dispatch) cannot effectively communicate. Not without potentially deadlocking the system.

You can assign work groups for your compute shader for some limited communication, but in general the compute shader runs in parallel without a defined order, trying to force it to run sequentially would slow down the GPU to a crawl since it's power comes from running all operations in parallel.

In this case the solution is to write to a separate texture from the one your reading from, if you don't the operation will be undefined and could cause all sorts of problems because of said multitasking.

If your input is a 1024x1024x30 3d texture for instance, and you wish to process it in sequence along the w coordinate then you create a 1024x1024x30 output image, then use glDispatchCompute to define as many workgroups as you need, or define layout(local\_size\_x = X, local\_size\_y = Y, local\_size\_z = Z) in; in your compute shader

```
#version 430
#define width 1024
#define height 1024

layout(local_size_x=width, local_size_y=height) in;
uniform layer;
writeonly uniform image3D output;
uniform sampler3D input;

// gl_GlobalInvocationID is a uvec3 variable giving the global ID of the thread,
// gl_LocalInvocationID is the local index within the work group, and
// gl_WorkGroupID is the work group's index
void main() {
  ivec2 pos = ivec3(gl_GlobalInvocationID.xy, layer);
  imageStore(output, pos, texture3D(input, pos));
}

```

Code is untested but should hopefully be enough to get you started. If you create more than one workgroup you have to multiply that with the layout used in the shader to get the total size of the work space.

```
for (int layer = 0; layer < 30; layer++) {
  glUniform1i(layerPosition, layer);
  glDispatchCompute(1,1,1); // X: 1*1024  Y: 1*1024  Z: 1*1
}

```

Remember to not write to the same texture your reading from, so if you want to use the previous computations result you will need to swap textures around between executions as well.
> 1 votes

---
Tags: unity, shaders
---


# Question
Title: Why does my simple OpenGL shadow map fail?
I want to render a simple shadow map for grass, where closer looks brighter and further looks darker, from the view of the light point. I can't get it to work.

Here is the relevant code:

```
//setting up buffers
gl.glGenFramebuffers(1, framebuff);
gl.glBindFramebuffer(GL4.GL_FRAMEBUFFER, framebuff.get(0));

gl.glGenTextures(2, textureBuff);
gl.glBindTexture(GL4.GL_TEXTURE_2D, textureBuff.get(0));
gl.glTexStorage2D(GL4.GL_TEXTURE_2D, 1, GL4.GL_R32F, displayWidth, displayHeight);
gl.glTexParameteri(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_MAG_FILTER, GL4.GL_LINEAR);
gl.glTexParameteri(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_MIN_FILTER, GL4.GL_LINEAR_MIPMAP_LINEAR);
gl.glFramebufferTexture(GL4.GL_FRAMEBUFFER, GL4.GL_COLOR_ATTACHMENT0, textureBuff.get(0), 0);

gl.glBindTexture(GL4.GL_TEXTURE_2D, textureBuff.get(1));
gl.glTexStorage2D(GL4.GL_TEXTURE_2D, 1, GL4.GL_DEPTH_COMPONENT32F, displayWidth, displayHeight);
gl.glTexParameteri(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_MAG_FILTER, GL4.GL_LINEAR);
gl.glTexParameteri(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_MIN_FILTER, GL4.GL_LINEAR_MIPMAP_LINEAR);
gl.glTexParameteri(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_COMPARE_MODE, GL4.GL_COMPARE_REF_TO_TEXTURE);
gl.glTexParameteri(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_COMPARE_FUNC, GL4.GL_LEQUAL);
gl.glFramebufferTexture(GL4.GL_FRAMEBUFFER, GL4.GL_DEPTH_ATTACHMENT, textureBuff.get(1), 0);
gl.glDrawBuffer(GL4.GL_NONE);

if(gl.glCheckFramebufferStatus(GL4.GL_FRAMEBUFFER) != GL4.GL_FRAMEBUFFER_COMPLETE)
         System.out.println(gl.glCheckFramebufferStatus(GL4.GL_FRAMEBUFFER));

```

Drawing command (unsure if it's correct):

```
//gl.glBindFramebuffer(GL4.GL_FRAMEBUFFER, framebuff.get(0));
gl.glViewport(0, 0, displayWidth, displayWidth);
gl.glEnable(GL4.GL_POLYGON_OFFSET_FILL);
gl.glPolygonOffset(2.0f, 4.0f);

/*
gl.glClearBufferfv(GL4.GL_COLOR, 0, new float[] {0, 0, 0}, 0);
gl.glClearDepth(1.0f);
gl.glClear(GL4.GL_DEPTH_BUFFER_BIT);*/

setupMVPMatrix();
gl.glBindVertexArray(vaoBuff.get(0));

gl.glUseProgram(shaderProgram);
gl.glDrawArraysInstanced(GL4.GL_TRIANGLE_STRIP, 0, 5, 512 * 512);

gl.glDisable(GL4.GL_POLYGON_OFFSET_FILL);
//gl.glBindFramebuffer(GL4.GL_FRAMEBUFFER, 0);

```

When I comment the `glBindFramebuffer()`, the grass appears correctly with the white color (from the light point of view, which shows the matrix should be correct):

But if I call `glBindFramebuffer()` with the depth test enabled, everything just disappears. I have also checked the framebuffer status, yet it seems there is no error.

What might cause this?

# Answer
> 1 votes
Fixed, I didn't understand the meaning of off-screen rendering at the beginning. Just render the depth value stored in the texture into the default framebuffer for display, and everything work just fine. I can't believe I spent 5 days on this.

```
gl.glBindFramebuffer(GL4.GL_FRAMEBUFFER, framebuff.get(0));
draw scene...(storing the depth value into the depth texture)

gl.glBindFramebuffer(GL4.GL_FRAMEBUFFER, 0);
draw scene...(comparing with the depth texture stored)

```

---
Tags: opengl, shadow-mapping, jogl
---


title: How to stop rotation every 90 degrees?

text:
# Question
Title: How to stop rotation every 90 degrees?
I was facing another rotation problem yesterday, that i managed to solve by rotating the object like this :

```
transform.Rotate (speed * Time.deltaTime, 0, 0, Space.World);

```

I tried almost every other way but nothing seems to work, usually i only use Euler angles to rotate my objects but in this case i couldn't.

So what am trying to accomplish here is to rotate the cube 90 degree around the X or Z axe everytime the player press the arrow key (doesn't have to stay pressing), and theoretically i thought this would work :

```
if (Input.GetKeyDown (KeyCode.LeftArrow)) {
            targetEul = transform.eulerAngles;
            targetEul.x += 90;
            timer = 90;
     //also tried this alone:
    targetQuat = Quaternion.Euler (transform.rotation.eulerAngles.x + 90, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);
   }

if (timer>0){
     timer -= speed * Time.deltaTime;
     transform.Rotate (0, 0, speed *  Time.deltaTime, Space.World);
  }else{
    transform.rotation = Quaternion.Euler (targetEul);
 }

```

This is to avoid the risk of getting the object rotation out of sync which will eventually happens if i don't use that line inside the else statement : **GIF PREVIEW**

Now if i use that to adjust the rotation, this happens : **GIF PREVIEW**

in the rotation number: 4 the object start to flip itself strangely, which i have no idea why.

So what i exactly need is this, say am working with just a float that i want to increase in time to reach 10.00, if i do this :

```
if  (x<10){
    x+=Time.deltaTime;
}

```

Then the final result of x won't be exactly 10.00, it would be something a little bit more. and so i need to make it like this :

```
if(x<10){
   x+=Time.deltaTime;
} else{
   x=10;
}

```

That is exactly what i am trying to make but instead of X i want the object rotation, and instead of 10 i want the previous object rotation+90 on X or Z

Is it really "impossible" to do in that simple way?

Thank you very much

**EDIT** here is the entire Class am using in this example :

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

public class RotateCube : MonoBehaviour
{
    public Text txt;
    public  float speed;
    public Vector3  targetEul, myEul;
    public bool canRotate, doLeft, doRight;
    int i ;

    void Update ()
    {
        //check input when possible
        if (canRotate)
            checkInput ();
        if (doLeft)
            checkLeft ();
        if (doRight)
            checkRight ();
    }

    //rottate left
    float chrono;
    void checkLeft ()
    {
        if (chrono > 0) {
            chrono -= speed * Time.deltaTime;
            transform.Rotate (speed * Time.deltaTime, 0, 0, Space.World);
            myEul.x += speed * Time.deltaTime;
        } else {
            transform.rotation = Quaternion.Euler (targetEul);
            //transform.rotation = Quaternion.Slerp(transform.rotation,targetQuat,100);
            canRotate = true;
            doLeft = false;
        }
    }

    //rotate right
    float chronoR;

    void checkRight ()
    {
        if (chronoR > 0) {
            chronoR -= speed * Time.deltaTime;
            transform.Rotate (0, 0, -speed * Time.deltaTime, Space.World);
            myEul.z += speed * Time.deltaTime;
        } else {
            transform.rotation = Quaternion.Euler (targetEul);
            //transform.rotation = Quaternion.Slerp (transform.rotation, targetQuat, 100);
            canRotate = true;
            doRight = false;
        }
    }

    //check input
    Quaternion targetQuat;

    void checkInput ()
    {
        if (Input.GetKeyDown (KeyCode.LeftArrow)) {
            //targetQuat = transform.rotation * (Quaternion.AngleAxis (90,Vector3.left));Quaternion.Euler (transform.rotation.eulerAngles.x + 90, 0, 0);
            targetQuat = Quaternion.Euler (transform.rotation.eulerAngles.x + 90, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);//Quaternion.AngleAxis(90,Vector3.right);
            targetEul = transform.eulerAngles;
            targetEul.x += 90;
            chrono = 90;
            canRotate = false;
            doLeft = true;
            i++;
        }

        if (Input.GetKeyDown (KeyCode.RightArrow)) {
            targetQuat = Quaternion.Euler (transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z + 90);
            targetEul = transform.eulerAngles;
            targetEul.z += 90;
            chronoR = 90;
            canRotate = false;
            doRight = true;
            i++;
        }
        txt.text = "" + i;
    }
}

```

# Answer
> 1 votes
This sounds like a perfect candidate to use coroutines. By using a coroutine, you can keep the amount of (class) state variables to a minimum and you end up with really clean code.

Here's an example how this could look like:

```
// duration of the rotation in seconds, can be set via Inspector
public float RotationDuration = 0.5f;
private bool _isRotating = false;

void Update () {
    if (Input.GetKeyDown(KeyCode.LeftArrow) && !_isRotating) {
        StartCoroutine(RotateObject(
            transform.rotation,
            transform.rotation * Quaternion.Euler(90, 0, 0),
            RotationDuration
        ));
    }
    if (Input.GetKeyDown(KeyCode.RightArrow) && !_isRotating) {
        StartCoroutine(RotateObject(
            transform.rotation,
            transform.rotation * Quaternion.Euler(0, 0, 90),
            RotationDuration
        ));
    }
}

IEnumerator RotateObject(Quaternion start, Quaternion end, float duration)
{
    float endTime = Time.time + duration;
    _isRotating = true;
    while (Time.time <= endTime) {
        // normalized progress from 0 - 1
        float t = 1f - (endTime - Time.time) / duration;
        transform.rotation = Quaternion.Lerp(start, end, t);
        yield return 0;
    }
    transform.rotation = end;
    _isRotating = false;
}

```

If you're new to using coroutines, or if you need a refresher, check out this excellent introduction to coroutines.

# Answer
> 0 votes
**Special thanks mintman from Reddit/r/Unity3D who fixed this issue** here

## **(The following is just copied from his original answer)**

---

After doing the interpolation, you set your result to a different quaternion:

```
float chronoP;
void checkQuatParent ()
{
    if (chronoP > 0) {
        chronoP -= speed * Time.deltaTime;
        myTrans.parent.rotation *= Quaternion.Euler (Vector3.forward * speed * Time.deltaTime);
    } else {
        // ---------- this line -------
        myTrans.parent.rotation = Quaternion.Euler (parentTargetEul);
        canRotate = true;
        doRight = false;
    }
}

```

Figure out your final final final target quaternion, and then just interpolate to it. I finally just opened Unity to make this. Apply it to just a vanilla cube - no parenting magic or anything. It actually did have more of a trick to it than I thought:

```
using UnityEngine;
// Attach to just a cube.
public class RotatingCube : MonoBehaviour {

        public float TotalSecondsInRotation = 0.7f;
        float t;
        Quaternion initial;
        Quaternion target;
        bool isRotating;

        void Update ()
        {
                if (!isRotating) {
                        if (Input.GetKeyDown (KeyCode.LeftArrow)) {
                                t = 0;

                                var unrotatedLeft = Quaternion.Inverse(transform.rotation) * Vector3.left;
                                var worldRotateLeft = Quaternion.AngleAxis(90, unrotatedLeft);

                                initial = transform.rotation;
                                target = initial * (worldRotateLeft);

                                isRotating = true;
                        }
                        if (Input.GetKeyDown (KeyCode.RightArrow)) {
                                t = 0;

                                var unrotatedForward = Quaternion.Inverse(transform.rotation) * Vector3.forward;
                                var worldRotateForward = Quaternion.AngleAxis(90, unrotatedForward);

                                initial = transform.rotation;
                                target = initial * (worldRotateForward);

                                isRotating = true;
                        }
                }

                if (isRotating) {
                        InterpRotation();
                        if (t >= 1)
                        {
                                isRotating = false;
                        }
                }
        }

        void InterpRotation ()
        {
                t += Time.deltaTime / TotalSecondsInRotation;
                transform.localRotation = Quaternion.Slerp(initial, target, t);
        }

}

```

The big trick was finding how to actually rotate around the correct axis:

```
var unrotatedLeft = Quaternion.Inverse(transform.rotation) * Vector3.left;
var worldRotateLeft = Quaternion.AngleAxis(90, unrotatedLeft);

initial = transform.rotation;
target = initial * (worldRotateLeft);

```

Multiplying Vector3.left by the inverse of the current rotation gives us the correct world axis to rotate around. We're effectively "undoing" the current rotation of the object to make sure the axis we're rotating around is correct.

Good luck!

---
Tags: c#, unity, rotation, quaternion
---


# Question
Title: How are win conditions handled in a turn based game?
Turn based games sometimes have different win conditions for different maps and mission.

For example, control some structure for X turns, last X turns without losing a single soldier.

They usually also have standard win conditions across all maps like eliminate all enemy units and structures, etc.

How would I implement map/mission specific win condition checks?

My current implementation utilizes a finite state machine that loads the play state. The play state has objects and logic for gameplay. I could write custom play states for each mission, but I feel like that is not the best way to go as I would have large portions of duplicate logic and code.

Ideally I would like to tie in win conditions into my map/mission file data. When I load a map, the win conditions are loaded also, but am not sure how I would achieve that.

Any suggestions?

# Answer
This is very similar to how one might handle Achievements, or Challenges, or any other situation needing you to keep track of a series of events and counters.

Simply coding the rules into a scripting language does work. You would need to be sure that all events related to conditions you care about are exposed to the language. You might also need to allow scripts to register conditions and current values with an external UI system, of course.

A more structured version of this would be to just keep a list of conditions, current state, and so on. In many ways, you'd just be building a limited and very domain-specific scripting system; the advantages of this approach are that any other interested system (the UI, your map editor, debug console, etc.) can trivially integrate with this system as there is a well-defined structure to how it works.

If you're trying to throw something together that works with the minimal pain and effort, I'd probably go with the first approach (scripting). If you plan to put in the time to make a high-quality map editor for user-created content or want to develop very high-quality debugging tools (which map designers love, even if they're your in-house designers), I would go with the second option.

The second option can be coded up using either C-like arrays of structs/unions with enumerations that define requirements for conditions, e.g.:

```
enum condition_t { controlled_houses, killed_enemies };
struct condition_defition_t {
  condition_t type;
  int data; // number of houses required, or number of killed enemies required, etc.
};

condition_definition_t* conditions; // per-map; load this data from your map file

int evaluate_for_player(condition_definition_t* condition, size_t num_conditions, player_t* player) {
  for (size_t i = 0; i != num_conditions; ++condition) {
    switch (condition->type) {
    case controlled_houses:
      if (player->houses < condition->data)
        return 0; // does not have enough houses to win
      break;
    case killed_enemies:
      if (player->kills < condition->data)
        return 0; // did not kill enough enemies
      break;
   }
   return 1; // all conditions have passed
}

```

With a little extra work, you can also support `OR` and `AND` conditions, ranges, or whatever other complexity you need for your game design. It's often better to avoid state in the condition itself; e.g., if the condition is "controlled castle for 5 turns" then just keep track of how long a player has controlled the castle in the player, and the condition simply checks that value. As your conditions grow in complexity, you may need to add some kind of per-player `condition_state_t`, though.

A polymorphic approach to the above would just replace the enum and the big switch statement with an abstract base class and derived classes that implement specific rules, e.g.

```
struct ICondition {
  virtual bool IsSatisfied(Player const& player) = 0;
};

class KilledEnemiesCondition : public ICondition {
  int _requiredKills;

public;
  KilledEnemiesCondition(int num_required) : _requiredKills(num_required) {}

  bool IsSatisfied(Player const& player) override {
    return player.GetNumKilledEnemies() >= _requiredKills;
  }
};

class OrCondition : public ICondition {
  std::vector<std::unique_ptr<ICondition>> _conditions;

public:
  bool IsSatisfied(Player const& player) override {
    return std::find_if(_conditions.begin(), _conditions.end(), std::mem_fun(&ICondition::IsSatisfied)) != _conditions.end();
  }
};

```

And the loop would use that interface. As shown, this approach does make it a bit easier to add more complex conditions like an `OR` condition. Loading the conditions from file would likely need extra work to deserialize the definitions into the proper classes with the proper data, of course, and you'll probably find the polymorphic version to just be bigger and more complex; that complexity may or may not be worth it to you, depending on various factors (e.g., required complexity of conditions, the API you want for exposing these to other systems, whether you already have a good serialization system in place, and your comfort level with that programming paradigm).
> 1 votes

# Answer
We used **hardcoded conditions** with some variables in early days. That was working good enough, but quite cumbersome. There were standard objects (houses, army, citizens, time) and deeds (kill, preserve) connected with win/defeat goals. So for example we could have:

* kill houses of player 5 to win
* kill army of player 5 to win
* preserve citizens of player 4 to win
* preserve own houses to win
* reach time 6000 to loose

As you can see thats somewhat flexible and easy to rig in code.

Later on we decided to support modding and for that we have incorporated **scripting language** support (Pascal Script in our case, but you can use Lua or something else just as well). Scripting language has handlers for game events (OnTick, OnHousePlaced, OnUnitKilled, etc. ~60 of them) and game state queries (IsHouseAtXY, IsUnitWounded, IsAlliance, ~50) and game handlers (GiveHouse, UnitKill, ResourceGive, etc ~60). That all combines into very rich scrpted maps with complex scripts, some even making an RPG from our RTS game :)
> 1 votes

# Answer
i'll be a bit abstract. Why don't you use a Observer pattern

After each turn you call NotifyObservers that invoke the Notify method inside each observer. Every observer is a win/defeat condition.

At the start of a stage, you "register" one or more observers.
> -1 votes

---
Tags: game-design, turn-based-strategy
---


title: LibGDX font issues

text:
# Question
Title: LibGDX font issues
I've started creating a small project for the store with LibGDX. So far I only tested on PC, and everything went well. I'm using the `gdx-smart-font` library for font rendering. The fonts are looking good on a clean start:

But if I exit from the app (ex.: via the back button, or the home button), and it still remains in the memory, then if I launch the app again, the whole font set is messed up:

Currently I have a `Settings` class, which loads the fonts, and creating a skin for the `TextButtonStyle`s and `LabelStyle`s, and I only have code in the `Screen`s `show`, `resize` and `render` function.

# Answer
This is due to either a context loss or simply you disposing your textures, without recreating them at the proper time (as you pointed out).
> 2 votes

---
Tags: android, libgdx
---


# Question
Title: onCollisionEnter2D not behaving as expected
I have two game objects. They both have a Rigid Body 2D and a Box Collider 2D components.

One of them also has script component. Below is the full script

```
using UnityEngine;
using System.Collections;
public class Col : MonoBehaviour
{
void Start ()
{
}
void Update ()
{
}
void onCollisionEnter2D(Collision2D col)
{
Debug.Log("collision detected");
}
}

```

When I start the project, go to the Scene view and drag one GameObject over another i don't get the Log message i am expecting to see.

What am i doing wrong here? Seems so simple.

Last pic is the size of the box colliders so you can see that they are correct size.

I've seem other very similar question and they are all in regards to unity5.0 (i am using 5.0 as well)

# Answer
Feel weird answering my own question but the problem is the

```
void onCollisionEnter2D(Collision2D col)

```

It needs to be

```
void OnCollisionEnter2D(Collision2D col)

```

(With the capital 'O').

Hope this help someone over there as it is rather easy to overlook for beginners
> 0 votes

# Answer
Collisions in the physics space (stuff using `onCollision`, not `onTrigger`) need to have a `Rigidbody2D` attached to the objects. This `Rigidbody2D` component is what places the objects into the physics simulation and allows for the objects to collide with each other.

If you only want to know when the objects touch each other, and not simulate physics or collision responses, use `onTriggerEnter2D` (Making sure to set your colliders to triggers).

Also, you'll need to ensure your method signatures are correct:

```
void onCollisionEnter2D(Collision col)

```

is wrong. You want

```
void OnCollisionEnter2D(Collision2D coll)

```

Notice the `2D` type of collision is the correct way to implement this method, in addition to the capital `O` at the beginning.

I started a new scene. Added two 2D sprites. I added colliders to both. I then added a rigid body to one and attached a new script to the other. The script contained your code above for `OnCollisionEnter2D`. When I moved the rigidbody object over the other object, the debug text was printed.

You either need to start over because you've done something wrong or you need to reexamine your assumptions.
> 0 votes

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


# Question
Title: What direction is forward when the rotation is (0, 0, 0)?
I'm representing the rotations of my actors (or gameobjects) with euler angles (one float for each axis). And I've always considered the vector (1,0,0) (x,y,z) to be the actor's direction if all angles are 0. So if an actor don't have any rotation, and walks forward, he will be walking down the positive x axis.

However, I was implementing a camera today that's supposed to display the view from the actors perspective. If I use the actor's rotation, that is (0, 0, 0), the camera will be looking down the -z direction (straight into the monitor), but the actor is actually looking to the right.

If, instead, -z would be considered the direction when the rotation is (0, 0, 0), then the camera would be facing the correct direction. Is that how this is normally handled? Or am I thinking of this the wrong way?

To clear things up, I'm using a right handed coordinate system with y as the up axis.

# Answer
> 5 votes
This is *entirely* a matter of convention. (Since you didn't mention any particular tools.)

But! If you are modeling in the same default orientation as your screen, which you say is right-handed, X-right, Y-up, and therefore Z-towards-you, then it would be natural to model your characters facing you, where forward is Z-positive.

Which also implies your default camera looking, as you mention, towards Z-negative into the screen. So your character with an identity matrix will appear centered, looking at you the viewer.

(Which is the convention I use, by the way.)

---
Tags: 3d, camera, rotation
---


# Question
Title: How to make a textured tree model outside of unity that can be used in unity
So I am trying to make a 3d model of a tree that is textured that can be used in unity. So far I have tried two separate ways to do this and they both didn't work. The first time I used blender's tree creator add on to make a great looking tree but the textures for the tree needed to be applied in nodes and that doesn't transfer over to unity. The second time I used unity's own tree creator, but it's incredible hard to make a good tree with it and the textures I apply always get stretched and distorted to fit the tree making them blurry. So I really would appreciate if someone could tell me a good way to make trees that can be used in unity.

Thanks, nova

# Answer
You can always try tree\[d\]. It is an old program from frecle that allows you to create various trees. I believe the devs have stopped updating it and the download link is down. You can find it via the webarchive site here
> 1 votes

---
Tags: unity, 3d, blender, 3d-meshes
---


# Question
Title: OpenGL ES 1.0 to OpenGL ES 2.0, I cant draw a square
I am learning open GL ES 2.0 and I just made 1 easy game for 1.0

I am following tutorials but I cant understand this thing

In OpenGL ES 1.0 if I define a square that way:

```
private float[] vertices = { // Vertices for a face
0.0f, 0.0f, 0.2f, // 0. left-bottom-front
1.0f, 0.0f, 0.2f, // 1. right-bottom-front
0.0f, 1.0f, 0.2f, // 2. left-top-front
1.0f, 1.0f, 0.2f // 3. right-top-front
};

```

and draw it that way it Works

```
public void draw(GL10 gl)
{

    gl.glFrontFace(GL10.GL_CCW); // Front face in counter-clockwise
                                    // orientation
    gl.glEnable(GL10.GL_CULL_FACE); // Enable cull face
    gl.glCullFace(GL10.GL_BACK); // Cull the back face (don't display)

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Enable
                                                            // texture-coords-array
                                                            // (NEW)
    gl.glTexCoordPointer(3, GL10.GL_FLOAT, 0, texBuffer); // Define
                                                            // texture-coords
                                                            // buffer (NEW)

    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

    // front
    gl.glBindTexture(GL10.GL_TEXTURE_2D,TextureLoader.TeclaBlancatextureIDs[0]);

    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Disable
                                                            // texture-coords-array
                                                            // (NEW)
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisable(GL10.GL_CULL_FACE);
    gl.glDisable(GL10.GL_BLEND);
}

```

but in OpenGL ES 2.0 if I do this that way( with the same vertex) it only write a triangle:

```
private void drawSuelo(Suelo suelo)
{
    // Pass in the position information
    suelo.mPositions.position(0);
    GLES20.glVertexAttribPointer(mPositionHandle, mPositionDataSize, GLES20.GL_FLOAT, false,
            0, suelo.mPositions);

    GLES20.glEnableVertexAttribArray(mPositionHandle);

    // Pass in the color information
    suelo.mColors.position(0);
    GLES20.glVertexAttribPointer(mColorHandle, mColorDataSize, GLES20.GL_FLOAT, false,
            0, suelo.mColors);

    GLES20.glEnableVertexAttribArray(mColorHandle);

    // Pass in the normal information
    cubo.mCubeNormals.position(0);
    GLES20.glVertexAttribPointer(mNormalHandle, mNormalDataSize, GLES20.GL_FLOAT, false,
            0, cubo.mCubeNormals);

    GLES20.glEnableVertexAttribArray(mNormalHandle);

    // This multiplies the view matrix by the model matrix, and stores the result in the MVP matrix
    // (which currently contains model * view).
    Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);

    // Pass in the modelview matrix.
    GLES20.glUniformMatrix4fv(mMVMatrixHandle, 1, false, mMVPMatrix, 0);

    // This multiplies the modelview matrix by the projection matrix, and stores the result in the MVP matrix
    // (which now contains model * view * projection).
    Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);

    // Pass in the combined matrix.
    GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);

    // Pass in the light position in eye space.
    GLES20.glUniform3f(mLightPosHandle, mLightPosInEyeSpace[0], mLightPosInEyeSpace[1], mLightPosInEyeSpace[2]);

    // Draw the cube.
    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 6);
}

```

It seems to need all of this vertex in order to draw a square

```
final float[] PositionData = {

// Top face
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f };

```

Why is happening this? Why I am missing? Is there any way in Open GL ES 2.0 to write a square with 4 vertex?

# Answer
> 0 votes
The correct answer was answered by Reto Koradi

You're using different primitive types. In the working ES 1.0 code, you have this:

`gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);` and in the ES 2.0 code that renders only a triangle when you give it 4 vertices:

`GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 6);` So in the ES 1.0 code, you're specifying that you want to draw a triangle strip (primitive type GL\_TRIANGLE\_STRIP) with 4 vertices. This corresponds to 2 triangles. While in the ES 2.0 code, you specify that you want to draw 2 separate triangles (primitive type GL\_TRIANGLES), which indeed needs 6 vertices.

If you want to use the original 4 vertices for the ES 2.0 code, you simply have to use the equivalent draw call with the same primitive type you used in the ES 1.0 version:

`GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);`

---
Tags: opengl-es, opengl-es2, vertex
---


# Question
Title: After collision of two objects change the sprite and move in its direction
I've searched a lot for this question but there was no answer that could solve the problem I'm having. I'm new to unity and a very naive developer.
I'm making a game in unity using c# and it's like a bird that throws eggs in down projectile and when the egg hit the container it should destroy egg and the container sprite should change to a sprite which shows that the egg is inside the container.
It would be really helpful if someone could answer with a example code and I can implement this. Rest of the game is working fine projectile and hit. There are check points on `egg.cs` in `OnTriggerEnter2D` that `if` `target.gameObject.tag == "Container"` now here I need to change the container to another sprite I've and this should move in the direction of container.
**UPDATE:**
Here is the code which changes the sprite, but it changes the egg sprite not the container sprite.
First the declaration:

```
public Sprite changedContainer; //here I've set the sprite of Changed Container
private SpriteRenderer spriteRend;

```

Then in the start method:

```
spriteRend = GetComponent<SpriteRenderer>();

```

and finally my onCollision Trigger method: (Read the comment in my code)

```
void OnTriggerEnter2D(Collider2D target)
    {
        if (target.gameObject.tag == "Container") //if the egg collide with container
        {
            transform.GetComponent<SpriteRenderer> ().sprite = changedContainer; <br //which it did successfully
            Instantiate(changedContainer, target.gameObject.transform.position, Quaternion.identity); //as it is mentioned that target.gameobject.transform.position but it still takes the egg projectile
        }
}

```

So how to change the spite of container? I think I'm in the wrong class I should be doing this in the container class. But it is the projectile of egg that collides not the container that collides with egg.

# Answer
if egg.cs is attached to the egg, then writing:

```
transform.GetComponent<SpriteRenderer> ().sprite = changedContainer;

```

will change the egg component, so maybe use

```
target.gameObject.transform.GetComponent<SpriteRenderer> ().sprite = changedContainer;

```
> 0 votes

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


# Question
Title: Why doesn't this 2d physics calculation yield the desired jump height?
I found a formula for gravity and jumping in this article: http://error454.com/2013/10/23/platformer-physics-101-and-the-3-fundamental-equations-of-platformers/

I implemented this formula and proceeded to do some test calculations, but they yield incorrect results. I expected the outcome to be `4`, but the test resulted in `3.8`. What am I doing wrong? How do I get the number `4`?

```
float deltaTime = 1f / 50f;

float maxJumpHeight = 4;
float timeToApex = 0.44f;
float gravity = (2 * maxJumpHeight) / (timeToApex * timeToApex);

float jumpHeight = 4;
float jumpVelocity = (float)Math.Sqrt(2 * gravity * jumpHeight);

float velocity = -jumpVelocity;
float position = 0;

while (velocity < 0)
{
    velocity += gravity * deltaTime;
    position += velocity * deltaTime;
    Console.WriteLine("Position = {0}", position);
}

```

# Answer
> 3 votes
It's because of the discreet time and the way you integrate. Because you step time forward at 1/50 of a second you're not guaranteed to hit the actual apex of 4.0, the delta is just not granular enough. (Try setting the delta time to 1/5000 and you'll see that it gets closer to 4, obviously that won't work for your game but it will show you the effect).

Depending on the integration method you use you will get varying degrees of correctness, with Euler integration being quite bad when it comes to accuracy.

This article has a nice explanation on why integration might lose precision; http://www.marekfiser.com/Projects/Real-time-visualization-of-3D-vector-field-with-CUDA/4-Vector-field-integrators-for-stream-line-visualization

# Answer
> 0 votes
I was able to achieve a precise gravity simulation by applying the 'correction' said in this article: http://www.niksula.hut.fi/~hkankaan/Homepages/gravity.html

Basicaly it consists in dividing the gravity by 2 in the very first frame/iteration when adding it to velocity.

---
Tags: physics, platformer, jumping
---


# Question
Title: Am I allowed to release a fan-made version of a Trading Card Game on a fansite?
Consider a Trading Card Game that is currently available for play in digital format only, the game in question would be HEX: Shards of Fate, but this question is intended as a general question about all Trading Card Games.

Now my idea is to create an AI player for that game and see how good it performs. For this I'll need to build a client that is capable of playing the game and initially I want to test it myself and distribute it to a few friends so they can play around with it.

I am myself unsure of whether the EULA specific to this game are of any importance, as I believe all games will try to protect their games to the fullest extent as possible. However we also know that there are fansites out there which are allowed (**are** they legally allowed?) to display the cards of the game (including artwork) as long as they have a clear reference to the game which it is about and they do not attempt to make any money out of the cards themselves. I do believe that premium services on a fansite itself are legal.

Ultimately I want to create a fansite where:

* There is an obvious reference that the cards, etc. belong to the company that created the game.
* You can as player play versus an AI, using a game interface that is similar to the one that is in the actual digital version. It most likely won't be an exact 1:1 copy and some substitute interface will be used that doesn't look as nice.
* Playing versus the AI is not promoted as an actual game, it is just a site where you can test your skill as player, and as creator I can test the effectiveness of the AI.
* All cards are freely available to any player, I most surely do not intend to monetize that part.
* There is possibly a premium service that offers benefits, possibly more detailed statistics or more AI matches, more options, etc.

So I've got the following questions about this:

* Is the limited distribution amongst myself and friends legal?
* Is this fansite legal without the premium service?
* Is the premium service legal?
* Would selling booster packs (where you can obtain the cards) and having the player start with a minimal collection actually be **illegal**?

# Answer
I am not a lawyer, but as a software developer and occasional artist, I've investigated this a bit so I know what I can do to protect my work and also so I don't accidentally screw myself over. While it would help to know what country you're in, because different countries have different laws that may also affect you, I'll make an attempt at answering your question.

You'll likely run afoul of Copyright. The owner of Copyright over a certain work (and Copyright in most countries is implicit, and does not require it saying something is copyrighted explicitly) has full control over how and whether at all something may be distributed. This applies to any graphics in the game, any sounds. While it's OK in most countries to make a photocopy of something for personal use, and sometimes even pass it on to a friend, most courts will consider posting something on the internet (where it's publicly accessible) as redistribution. So unless all of this is in a closed, password-protected area, you shouldn't be doing this. It would be treated about the same as pirating software or movies.

Also, keep in mind that many countries have higher fines for commercial infractions. And in many countries (e.g. where I live in Germany) just having ads on your page or having a link to your company's (unrelated) store in the navigation will make it considered commercial (as you could be using it to draw customers there).

Names are usually covered under trademark law. So if anyone already uses that name, and it's not a generic term, you can not use that name. If they've registered the name as a trademark, they can cause even more damage more easily (but a trade mark doesn't have to be registered to let them sue you). So you can't use the others' name either. At most, you might get away with saying that your game is "in the style of" another game, but that's a risky proposition.

So in short: Don't do it. Just make placeholder graphics (or hire someone to do them), make up your own names. The rules are not protected, but even though you can draw your own graphics for a deck of regular French playing cards, the graphics of commercial decks being sold out there are copyrighted, unless they explicitly say otherwise or you can prove that the artist has been dead the requisite 70 years (or more if you're unfortunate enough to live in the US with its endless copyright term extensions).

**Note:** There are fan productions out there that don't adhere to these rules and get by fine. That usually is totally due to benevolence on the part of the Copyright owners, you can't expect this in every case. E.g. Anne Rice was known for a long time to go after fan fiction web sites asking them to take down stories.

**Update:** Here's another example of a takedown done by Nintendo: http://www.eurogamer.net/articles/2015-03-31-nintendo-issues-takedown-notice-for-super-mario-64-hd-project though this involves actual copying of a few sound files and graphics from an original game.
> 2 votes

---
Tags: legal
---


# Question
Title: C# Unity3D FPS apply damage to an enemy (Weapon bullet)
I am kindly new to Unity3d and c# and I don't understand how I could let a bullet deal damage to an other object. I've seen a lot of JS tutorials but no for C#. I've tried to use them, but it wont work. My code I've tried: For the Bullet (Prefab)

```
   using UnityEngine;
using System.Collections;

public class MoveBullet : MonoBehaviour {

    public float speed = 10.0F;
    public float damage = 10.0f;

    // Use this for initialization
    void Start () {

    }

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

        transform.Translate (0, 0, speed);

    }

    void OnCollisionEnter(Collision col){

        col.gameObject.BroadcastMessage("ApplyDamage", damage);

    }
}

```

And the one for the Enemy:

```
public class enemyhealth : MonoBehaviour {

  public int health = 100;

  // Use this for initialization
  void Start () {
  }
  // Update is called once per frame
  void Update () {
  }

  void OnDamage(){
    health--;
    if (health <= 0) {
      Destroy(gameObject);
    }
  }
}

```

What's not clear to me as well is, what type of Collider I should use (Box Collider, CapsuleCollider...) Or doesn't it makes a difference?

As I understood, Rigidbody is used for an other "technique" to make damage, am I right?

# Answer
> 0 votes
some reference : https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html

Check Both objects (bullet and enemy) have a collider with 'Is Trigger' enabled plus the bullet has a rigidbody.

You can use the collider you prefer.

I rewarote youre code this way:

```
    // Update is called once per frame
    void Update () {
    transform.Translate (0, 0, speed);
    }
    void OnTriggerEnter(Collider Enemy){
    if(Enemy.gameObject.CompareTag("enemy"))
    {
        Enemy.gameObject.SendMessage("OnDamage", damage);
    }

```

# Answer
> 0 votes
My understanding from reading your code is that you send a message passing a param (the damage amount) ...

```
gameObject.SendMessage("OnDamage", damage);

```

You then declare a method that takes no params to handle it ...

```
void OnDamage(){

```

My guess is that the unity compilation process is not creating a correlation between these 2 because of that mismatch.

---
Tags: c#, unity, first-person-shooter
---


# Question
Title: Script to change size of a cube when pressing a button
I am very new to coding and very bad at it.

In my environnement there is a table, and i would like, after pressing a keyboard button, to make a cube appear. Then, by pressing another button, i would like to change its size everytime i press the second button.

I have no clue where to begin with.

Thanks in advance,

Kel

# Answer
If you're creating a new gameObject using something along the lines of CreatePrimitive then you could following that with some logic to change it's scale programatically {Warning: untested code} :

```
public class SceneController : MonoBehaviour {

private GameObject cube;
private float cubeScale = 1.0f;

    void Awake() {

    }

    void Start() {

    }

    void Update() {
        // create cube
        if(Input.GetKeyDown (KeyCode.Space) {
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            // reposition cube randomly/rotate it etc
        }
        // size cube up
        var s = cube.transform.localScale;
        if(Input.GetKeyDown (KeyCode.Up) {
            cubeScale *= 1.1f;
            cube.transform.localScale += new Vector3(s.x * cubeScale, s.y * cubeScale, s.z * cubeScale);
        // size cube down
        } else if(Input.GetKeyDown (KeyCode.Down) {
            cubeScale *= 0.9f;
            cube.transform.localScale += new Vector3(s.x * cubeScale, s.y * cubeScale, s.z * cubeScale);
        }
    }
}

```
> 1 votes

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


# Question
Title: Extra sprite spawning when the enemies are redrawn SFML
I am making a game in sfml and at the moment when all of the enemies die. They are set to respawn however when this is happening they are respawning with one extra sprite than before.

The code for loading in the sprites is

```
unsigned int orcNumber = 5;
for (int i = 0; i < orcNumber; i++)
{
    SpriteVector.push_back(ogreSprite);
    SpriteVector[i].setPosition(spawnPointX[i], spawnPointY[i]);
}

```

The code for removing the enemies if they are offscreen or shot is similar to below using erase.

```
for (unsigned j = 0; j < SpriteVector.size(); j++)
{
    if (this->SpriteVector[j].getPosition().x < 0 - 80 )
    {
        //this succesfully removes the object from the vector
        SpriteVector.erase(SpriteVector.begin() + j);
        std::cout << "Container size..." << SpriteVector.size() << "\n";
    }
}

```

The statement for redrawing them is:

```
unsigned int orcNumberRespawn = 5;
if (SpriteVector.size() <= 1)
{
    for (int i = 0; i < orcNumberRespawn; i++)
    {
        SpriteVector.push_back(ogreSprite);
        SpriteVector[i].setPosition(spawnPointX[i], spawnPointY[i]);
    }
}

window.draw(SpriteVector[i]);

```

Can anyone identify why when the sprites need to be redrawn it draws with + 1 sprite everytime?

# Answer
> 1 votes
You are changing the size of the array inside the loop, but not updating the loop index to match.. Thus you skip one item in the list every time you delete one.

```
for (unsigned j = 0; j < SpriteVector.size(); j++)
{
    if (this->SpriteVector[j].getPosition().x < 0 - 80 )
    {
        //this succesfully removes the object from the vector
        SpriteVector.erase(SpriteVector.begin() + j);
        std::cout << "Container size..." << SpriteVector.size() << "\n";

        // Since we removed j, the j'th item gets skipped when you loop (j++)

    }
}

```

A very simple solution could be to move through the list backwards:

```
for (size_t j = SpriteVector.size(); j--;)
{
    if (this->SpriteVector[j].getPosition().x < 0 - 80 )
    {
        //this succesfully removes the object from the vector
        SpriteVector.erase(SpriteVector.begin() + j);
        std::cout << "Container size..." << SpriteVector.size() << "\n";
    }
}

```

This way, when you change the order of all the items after J, it doesn't matter. A more flexible solution could be to make a 2nd list, a list of items to remove.

---
Tags: c++, sfml, spawning
---


title: How does a loop work in game engines?

text:
# Question
Title: How does a loop work in game engines?
Recently I started working on a game with the spritekit engine. My question is not about spritekit in specific though, but generally about game engines.

When I write a loop and run it (eg `while i < 100000`) my cpu usage goes to 100% normally, but when I run the test game there is no changes especially on cpu usage, why? (I know game engines run in a loop that includes logic and graphic commands.)

# Answer
Typically most of the more feature complete game engines actually have 2 game loops. The first is a fixed step loop aimed at iteration around every 16ms for that ideal 60fps zone.

The second is the "as fast as possible" loop.

The idea is that some actions like physics processing need to have some idea of process in order to be calculated correctly and other actions like drawing things on the screen are best served up at the highest possible rate (unless vertical sync is enabled forcing a limit).

Essentially the fixed step is handled by a timer that simply calls a function every x amount of time and the fast as possible loop is just an endless "while(true)" type loop.

For the most part you want to aim to keep your main thread in your game / engine as clean and empty as possible.

With multicore cpu's being the common situation these days even if you maxxed out that thread you should only see around 10% to 30% cpu load so my guess is you are doing a lot of multithreaded cpu intensive work in order to maxx out your cpu.
> 2 votes

# Answer
The game loop is normally called update() that would update everything that happens since the last frame, then draw() that draws the changes, your game loop will work to ensure both update and draw run frequently so that if a large calculation is being run, the game screen doesn't freeze. So your update method will be given a max time if competition, if it doesn't run in that time then update is paused, the draw method is called and so on.

Additionally if the update finished before its max time your method normally would sleep until it is needed next so updates dont run too frequently.
> 1 votes

---
Tags: performance, spritekit
---


title: Creating a 3D mushroom cloud

text:
# Question
Title: Creating a 3D mushroom cloud
Hi I am trying to create a mushroom cloud animation for my strategy game. Something like this. I have been looking at info for creating explosions in general, and the way to go seems to be using 2D sprites and billboarding. However, I don't think this will work in my case as mushroom clouds have a specific orientation, and I am using an arcball camera as my game takes place on a globe.

I've thought about using some kind of particle system, but it seems pretty complicated to make as opposed to using a sprite sheet.

What would be the best way to create a nice looking mushroom cloud?

# Answer
If you have to model that kind of effect in a 3d space such as on a planetoid you are going to need the system to respond to different camera angles and a sprite sheet just isn't going to work unless you pin two of the axis's which your description indicates isn't feasible.

Depending on the game engine you are using, a particle system is going to be the easiest method. You might break it down into three parts: 1) The blast radius along the explosion plane 2) The vertical tower of smoke connecting the hat to the explosion origin 3) The cap billowing and drifting up into the vertical axis

If you are using a tool like Unity3d you can play with each independent piece until it looks right. Then put them under one game object. Here is a quick search in the asset store you find similar effects free and already completed like at http://tinyurl.com/pgwsofa which could at least give you more ideas.
> 0 votes

---
Tags: 3d, particles, graphic-effects
---


# Question
Title: Stretch the game to fit the game window, in Unity 5
* (Desktop) I want to make it so that when the user re-sizes the **game window**, the game is stretched to fill the window.
* (Similarly, for Android) I want it to be stretched to fit the **screen** as well.

The game's real resolution is supposed to be 720x1280 (16:9 equivalent). In the image on the left you can see the actual resolution.

I can see that unity automatically re-scales it everytime the game window is re-sized, but it kind of keeps the same aspect ratio. This results in either **black bars** or part of the game being **off-screen**. How can I scale my game based on the current window aspect ratio ? **I know the graphics will get distorted.**

Isn't there a way to stretch the game without keeping the same aspect ratio, within the unity interface ? If not, how could I do that within a script ?

In xna or libgdx, I would simply add a `scale matrix` on every `spriteBatch.Begin()` method call. That scale would be based on the (current window width, current window height) and the ("real" game width, "real" game height).

For example, since my game is 720x1280, if you had your window re-sized at 500x500, I would **scale the graphics** by 500/720 on X axis and 500/1280 on Y axis. And then I would have to scale the inputs by `1/scale matrix`. I need to know how this works on unity. Perhaps, setting `Camera.main.aspect` to the current aspect ratio of the current window (I could calculate that everytime the window is resized), would solve the problem (?), but is there another option ?

I assumed that `supported aspect ratios` would do just what I needed. But when I re-size my game window to 720x1080 (4:3 equivalent) down from 720x1280 (16:9 equivalent) it just adds black bars. When I want the game to **stretch**, in all cases.

# Answer
> 2 votes
The camera will normally render with an aspect ratio equal to `Screen.width / Screen.height` but this can be overruled.

This script will have an effect similar to taking 16:9 image from the camera then stretching it to fill the screen. This will of course cause some distortion.

```
using UnityEngine;

public class CameraAspect : MonoBehaviour
{
    public float width = 16f;
    public float height = 9f;

    void Awake ()
    {
        Camera.main.aspect = width / height;
    }
}

```

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


# Question
Title: How do I save and restore an int value with PlayerPrefs?
I am stuck on how to save the player's amount of money. When I build the game in the exe as soon as I shutdown the game my money value gets lost. I want this money to be saved. I am using the following code in UnityEngine:

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

namespace CompleteProject
{
    public class MoneyManager : MonoBehaviour {
        public static int money; // The player's money.
        Text moneytext;          // Reference to the Text component.

        void Awake ()
        {
            // Set up the reference.
            moneytext = GetComponent <Text> ();
            money=print(PlayerPrefs.GetInt("Money"));
        }

        void Update ()
        {
            moneytext.text = "" + money;
            PlayerPrefs.SetInt ("Money", money);
        }
    }
}

```

# Answer
You're assigning the value of `money` to the `print` return value, not the actual int value being returned.

```
money=print(PlayerPrefs.GetInt("Money"));

```

Should be

```
money=PlayerPrefs.GetInt("Money");

```
> 8 votes

# Answer
It may be elseswhere but as far as we can see from the code you've provided there doesn't seem to be a call to `PlayerPrefs.Save();` and without it the value won't be persisted.

EDIT: Per comment from @Lohoris this isn't the case as it saves automatically on `Application.Quit`. As @Byte56 points out the issue may still be related if the application is being terminated via the Task Manager.
> 0 votes

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


# Question
Title: Editing a new list of vector3's without changing the original list? (Unity)
I just got Vectrosity for Unity and need to make a line of all the destinations for an object. Issue is that I need to use a single list of vector3's to create the line (as far as I'm aware).

I have a list of vector3's that is the objects queued destinations. I then need to insert the objects current location at index \[0\] in the list so that the first line point is at the objects location. Issue is that no matter how I try and accomplish this I'm still referencing the original destinations list, and inserting something at \[0\] on the list for the lines changes the original destinations list as well.

How do I go about creating a single List from a list of vector3's and an extra point without changing the original list that is being referenced? Do I need to clone it?

# Answer
> 1 votes
```
List<Vector3> newList = new List<Vector3>(originalList);
newList.Insert(0, currentLocation);

```

`originalList` in this example hasn't been modified and should have 1 less element than `newList`.

Another way:

```
List<Vector3> newList = new List<Vector3>();
newList.Add(currentLocation);
newList.AddRange(originalList);

```

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


title: 2d libgdx: runtime level generation

text:
# Question
Title: 2d libgdx: runtime level generation
I have encountered a problem during my first game development: I thought of a `Array<Ground> groundArray` that does `groundArray.add` when a new ground will appear on the screen, and removes oldest ground when it will no longer be seen, if player only moves to the right, like in flappy bird.

The perfect structure would be a queue for such a mechanic, but libgdx doesnt have one. Using libgdx's Array is not intuitive too - i have to reverse the order of elements. It has a method `pop()` that removes the last element, but no such method to use on the first element.

What are my options here?

* extend Array class and add something?
* writing my own queue-like class?

**UPDATE 18/8/2014**

i actually found a way to do it with the default Array:

```
private void checkGround() {
    for (Ground ground : groundArray){
        if (ground.x  + 500 < camera.position.x){
            groundArray.removeValue(ground, true);
        }
    }

    if (groundArray.peek().x < camera.position.x + 500){
        groundArray.add(new Ground(groundX, -150));
        groundX +=50; //my ground texture is 50 pixels wide
    }
}

```

Only question left now - **will it affect performance** when there will be 10000 empty elements before the 10 actual ground elements? In my render method i use:

```
for (Ground ground : groundArray){
        batch.draw(ground.getTextureRegion(), ground.x, ground.y);
    }

```

If yes - i will have to make a re-sort method that shifts all the grounds to the beginning of the array.

Will doing so improve this?:

```
for (Ground ground : groundArray){
        if (ground != null) {
            batch.draw(ground.getTextureRegion(), ground.x, ground.y);
        }
    }

```

After checking apparently the array size doesnt boost , it size is always equals the number of actual ground objects in it, but i thought that it will count also the null values that were ground objects before. But then surely there would be nullpointers when i tried to draw those null's, so the problem looks fully **resolved**.

# Answer
Use Array (or regular java \[\] array!) (`Ground[] grounds = initialize all;`) with index that points to the first visible Ground in that array (`int first = 0;`). Keep some counter (`float x = 0;`) which will hold progress to the next index.

```
void update(float delta) {
  x += delta * speed;
  if(x > groundWidth){
    x -= groundWidth;
    grounds[first].generateNew();
    first = (first + 1) % grounds.length;
  }
}

void render(){
  float renderX = -x;
  int tile = first;
  for(int i = 0; i < grounds.length; i++){ //Code in this loop just needs to be called grounds.length times
    grounds[tile].renderAtX(renderX);
    tile = (tile + 1) % grounds.length;
    renderX += groundWidth;
  }
}

```

Something like that.
> 1 votes

---
Tags: libgdx
---


# Question
Title: Should I worry about variable time step for simple mobile 2d game
After going through some articles on framerate independent game design, i found that its not an easy task to implement in variable time steps(it is difficult compared to fixed frame rate, and considering my lack of understanding of variable time steps), I came across this answer.

According to this answer "option 1" \[ *its this if you dont want to open the link* \- Do nothing. Attempt to update and render at a certain interval, e.g. 60 times per second. If it falls behind, let it and don't worry. The games will slow down into jerky slow motion if the CPU can't keep up with your game. This option won't work at all for real-time multi-user games, but is fine for single player games and has been used successfully in many games.\]

encourages me to not go for framerate independent design.

# Answer
> 1 votes
I have an old phone, maybe 5-6 years old. It's not quite as powerful as it needs to be to run the OS I have running on it so everything just lags... it's pretty bad. I honestly don't think my phone could run a game with a fixed time-step particularly well. But I'm on an old android so you might be completely fine if you're targeting newer iPhones (much more homogeneous than androids). If you're thinking cross-platform I honestly wouldn't trust a fixed time-step, but I'm a very distrustful person.

The bulk of the differences between the two are thinking about everything in unknown quantities vs rigid 1/60th of a second kind of thinking. But there's no reason you can't build everything fixed and switch over later if issues arise (and of course variable can become fixed at the drop of a hat). Just be careful how you code so if you need to make changes you know where they should go.

---
Tags: performance, frame-rate
---


# Question
Title: How to use atan2 to get the correct angle? (inside or outside angle)
I would like to rotate an object (white rectangle) towards another object (black rectangle). EDIT: the white rectangle (at the top) has a camera. I finally rotated the camera by 180 around the "y" axis, because it was looking to the right of the image. Now, the goal is to rotate the camera around the "x" axis, by the green angle.

I found some images that explains atan2 :

What I try to do is :

Edit : the green angle seems wrong, here is a new one :

If I refer to the trigonometry circle, I should have a value around -120 :

Would someone know what is happening? Here is the code I am using :

```
    //boxNode is the black rectangle, boxYellow is the white rectangle at the top
    //163 degrees
    let opposite = boxNode.position.z - boxYellow.position.z
    let adjacent = boxNode.position.y - boxYellow.position.y

    //-73 degrees
    //let opposite = boxNode.position.y - boxYellow.position.y
    //let adjacent = boxNode.position.z - boxYellow.position.z

    camRadians = atan2(opposite, adjacent)
    println("deg: \(convertRad2Deg(camRadians))")

```

Thanks

# Answer
Your drawings seem inconclusive with respect to axis names and signs.

Just going by the first illustration, you could say approximately:

```
_playerSpeedY = 2
_playerSpeedX = -1   // going to the left, negative!
radians = atan2(_playerSpeedY, _playerSpeedX)
degrees = radians * 57.29577951

```

I get radians = 2.0344439357957027 and degrees = 116.56505117080718

(I used python and just typed:

```
bash: py
>>> import math
>>> math.atan2(2,-1)
2.0344439357957027
>>> math.atan2(2,-1) * 57.29577951
116.56505117080718
>>>

```

)

So... do it like that! :-)
> 1 votes

---
Tags: mathematics, ios, angles, trigonometry
---


# Question
Title: Optimizing file-size of a sprite-sheet for a 2D game
I have a question regarding the method of creating a sprite-sheet so that it will not consume to much disk space and still preserve graphics quality.

I was researching about this topic and found that my sprite-sheets should have sizes that are a power of two. So valid sizes would be 512x512, 1024x1024, 2048x2048 etc.

Then I created two sprite sheets (one is 1024x1024 and the other is 2048x2048), they are exported as 16bit but they still use too much disk-space. How can I optimize my sprite-sheet to use the least amount of disk-space possible?

This is one of my sprites:

# Answer
> 2 votes
I believe that in a lot of cases it's not worth investing huge amounts of time into optimizing assets to shave off a few MB of your final game. Sure, if you need to stay below a certain size limit (eg. 100MB for Apples policy for apps to transfer over cellular-networks), then it's reasonable.

A general optimization you can do is making use of some PNG optimizers (here's a tool that combines several of them). This can reduce the file size of a PNG considerably.

In your case, you could save even more space, by removing all redundant assets. You could remove all smaller variants of the circles. Simply scaling the sprite in unity is going to be enough to create the smaller circles (downscaling of sprites is usually fine and pretty much the same as pre-creating the smaller assets).

I'd probably even go further and just put one single circle into the sprite-sheet. Something like this:

Then create the different color-variants by setting the `Color` property in Unity (which will tint the sprite).

# Answer
> 0 votes
I think you could save a lot of space if you drew those circles either as vectors (if Unity doesn't have vector graphics you can probably find libraries you can use with Unity that do) or if you had one circle and made coloured and resized versions in memory when your application runs.

If you pack your colourful food together on one 512x512 sheet and then those icons on another you'll find that you can save the icons at 8bit without losing quality (never save as jpg, the quality will be poor). You might still need to save colourful stuff at 16 or 32 bit, but you won't have as large a sheet to save them on.

Give saving your stuff as a png or gif a go. If it's still a little bloated you can shave off the metadata photoshop injects into its files with something like what this adobe forum post suggests.

---
Tags: unity, sprites, spritesheet
---


# Question
Title: My .FBX model is not picking the .TGA texture file
I'm at a complete loss.

An artist has sent me a 3D model so I can test it in Unity. This is exactly what I got:

```
 - Guy.fbx
 - Guy_DIF_512.tga

```

Alright. So I move the folder into the Unity inspector. Suddenly, a `Materials` folder is created within such folder. The `Materials` folder has one material.

Anyway, now I put the `Guy` prefab into the scene. It doesn't have textures applied.

No problem. A simple Google search yields this response:

> The textures for your model have to be in your Unity project for Unity to apply them automatically when you import.
>
> There are 3 different ways to make sure this happens
>
> 1 Use Textures for your 3D model from a \textures directory already in your Unity project
>
> 2 Embed them in the FBX
>
> 3 Copy the textures into your project before you import your model

I will avoid the second option for now to avoid troubling the artist. Let's see the third option...

> 3 If you are using 3D software packages that might not have newer FBX plugins or are importing native files you generally do not have the option to embed media, so you will need to copy the textures into a directory inside your project called textures - nested next to the model before you import it e.g.
>
> \Projectx\Assets\Models\Textures\ModelTexture.tga
>
> \Projectx\Assets\Models\Model.fbx

Ok, so I created `Assets/Models/Textures` and imported the `Guy_DIF_512.tga` file into it. Then in `Assets/Models` folder I import the `Guy.fbx` file.

Doesn't work. The model still doesn't have textures applied.

Alright, so let's look at the first option then.

... Let's look at the first option...

> 1 If you create your textures in your Unity project to start with and source them from a \textures directory nested under Models for example, Unity should always create materials and pick up the textures correctly at import
>
> \**\Assets\Models\Textures\**
>
> \**\Assets\Models\**

Uh, isn't this the same as the third option?

**How do I import my 3D model?**

I am using Unity 5.

# Answer
> 2 votes
I don't know about Unity 5, but in 4, you can click on your model in the Scene window. On the Mesh Renderer properties, there should be at least one material.

To start, set the shader to "Diffuse", and click on "select" to select the texture. The character should appear textured.

If you want to save these settings for future use, drag the object from the Hierarchy panel to some folder in your Project panel to create a prefab for that precise model with that precise texture.

---
Tags: unity, 3d, fbx
---


# Question
Title: Three.js: Lighting not calculating correctly on THREE.Geometry objects
I have a three.js (REVISION: '68') issue with the lighting of THREE.Geometry objects:

I'm using the THREE.Geometry class to build up objects using vertices and faces, then I computeFaceNormals() and computeVertexNormals() before adding it to the scene.

The lighting is obviously not calculating correctly, and it looks like the light calculates before the object is moved into position (or some other issue causing all objects to have identical lighting regardless of position).

My light code is:

```
hemiLight = new THREE.HemisphereLight( 0xffffff, 0xffffff, 0.6 );
hemiLight.color.setHSL( 0.6, 1, 0.6 );
hemiLight.groundColor.setHSL( 0.095, 1, 0.75 );
hemiLight.position.set( 0, 50, 0 );
app.scene.add( hemiLight );

dirLight = new THREE.DirectionalLight( 0xffffff, 1 );
dirLight.color.setHSL( 0.1, 1, 0.95 );
dirLight.position.set( -1, 1.75, 1 );
dirLight.position.multiplyScalar( 50 );
app.scene.add( dirLight );

```

Note I also tried the documentation's sample-code for the Spotlight the issue persisted.

I am using a comparison of THREE.Geometry objects: the first with a single material for the at mesh creation, and the second with faces individually assigned a material, and passed to the mesh with THREE.MeshFaceMaterial(..) Note that I tried both single material Geometries and multi-material Geometries side-by-side and there is no difference.

Note I changed the color of one of my test cubes from blue to green compared to the header image.

The issue does not appear to be related to the multi-material code.

I understand that the Three.Geometry class behaves differently compared to BoxGeometry, etc. (For example, computeFaceNormals() and computeVertexNormals() needs to be explicitly called for Three.Geometry, but not for BoxGeometry). I think I may be missing some other difference around flagging the material/lighting/geometry for update.

My code to create my two plain test cubes is:

```
var testGeo = new THREE.Geometry();

testGeo.vertices.push(new THREE.Vector3(0,0,0));
testGeo.vertices.push(new THREE.Vector3(0,20,0));
testGeo.vertices.push(new THREE.Vector3(20,20,0));
testGeo.vertices.push(new THREE.Vector3(20,0,0));
testGeo.vertices.push(new THREE.Vector3(0,0,20));
testGeo.vertices.push(new THREE.Vector3(0,20,20));
testGeo.vertices.push(new THREE.Vector3(20,20,20));
testGeo.vertices.push(new THREE.Vector3(20,0,20));

testGeo.faces.push(new THREE.Face3(0,1,2));
testGeo.faces.push(new THREE.Face3(2,3,0));

testGeo.faces.push(new THREE.Face3(2,3,7));
testGeo.faces.push(new THREE.Face3(7,6,2));

testGeo.faces.push(new THREE.Face3(0,1,5));
testGeo.faces.push(new THREE.Face3(5,4,0));

testGeo.faces.push(new THREE.Face3(0,3,4));
testGeo.faces.push(new THREE.Face3(4,7,3));

testGeo.faces.push(new THREE.Face3(1,2,6));
testGeo.faces.push(new THREE.Face3(6,5,1));

testGeo.faces.push(new THREE.Face3(4,5,6));
testGeo.faces.push(new THREE.Face3(6,7,4));

testGeo.computeFaceNormals();
testGeo.computeVertexNormals();

var solidMatA = new THREE.MeshLambertMaterial({
    color: 'blue'
})
solidMatA.side = THREE.DoubleSide;
var cubeA = new THREE.Mesh( testGeo,  solidMatA );

cubeA.position.x = -40;
cubeA.position.y = -30;
cubeA.position.z = -30;
app.scene.add(cubeA);

var testMaterialsListB = [];
var testGeo2 = new THREE.Geometry();

testGeo2.vertices.push(new THREE.Vector3(0,0,0));
testGeo2.vertices.push(new THREE.Vector3(0,20,0));
testGeo2.vertices.push(new THREE.Vector3(20,20,0));
testGeo2.vertices.push(new THREE.Vector3(20,0,0));
testGeo2.vertices.push(new THREE.Vector3(0,0,20));
testGeo2.vertices.push(new THREE.Vector3(0,20,20));
testGeo2.vertices.push(new THREE.Vector3(20,20,20));
testGeo2.vertices.push(new THREE.Vector3(20,0,20));

testGeo2.faces.push(new THREE.Face3(0,1,2));
testGeo2.faces.push(new THREE.Face3(2,3,0));

testGeo2.faces.push(new THREE.Face3(2,3,7));
testGeo2.faces.push(new THREE.Face3(7,6,2));

testGeo2.faces.push(new THREE.Face3(0,1,5));
testGeo2.faces.push(new THREE.Face3(5,4,0));

testGeo2.faces.push(new THREE.Face3(0,3,4));
testGeo2.faces.push(new THREE.Face3(4,7,3));

testGeo2.faces.push(new THREE.Face3(1,2,6));
testGeo2.faces.push(new THREE.Face3(6,5,1));

testGeo2.faces.push(new THREE.Face3(4,5,6));
testGeo2.faces.push(new THREE.Face3(6,7,4));

for (var i = 0; i < testGeo2.faces.length; i++)
{

        var matB = new THREE.MeshLambertMaterial( {color: 'green'} );
        matB.side = THREE.DoubleSide;
        testMaterialsListB.push(matB);

}

testGeo2.computeFaceNormals();
testGeo2.computeVertexNormals();

var cubeB = new THREE.Mesh( testGeo2,  new THREE.MeshFaceMaterial( testMaterialsListB) );

cubeB.position.x = -60;
cubeB.position.y = -30;
cubeB.position.z = -30;

app.scene.add(cubeB);

```

Thanks!

# Answer
> 1 votes
Just to follow up in case others stumble across this:

While I did re-arrange the vertex order to ensure 90 degree perpendicular normals, I found that didn't make a material difference to adjacent object lighting.

The answer is that three.js doesn't intrinsically calculate lighting across adjacent objects in the scene graph, and while the shadowmap feature attempts to solve this, my investigations showed that a shadowmap solution didn't really work for my use case.

Instead, I applied only 1 of the two geometry calculations to get a simulated light effect

What I had:

```
geo.computeFaceNormals();
geo.computeVertexNormals();

```

What I ended up using:

```
geo.computeFaceNormals();
//geo.computeVertexNormals();

```

With computeVertexNormals()...

Without:

While not a perfect light effect (very flat), it should get me by. Thanks for the help posters.

# Answer
> 1 votes
Your triangles might be specified in a clockwise order instead of WebGL's preferred counter-clockwise order. To verify, switch your material side to `THREE.FrontSide` and run it again with `THREE.BackSide` and see if one gives you the correct results. If the `THREE.BackSide` works, then you have to go back and flip your ordering in all the `Face3` creations.

Regarding shading looking similar with stacked objects: *three.js* does not take other objects into account when lighting each object in the render stage. Let's say you wanted to make a Minecraft clone with a bunch of boxes all stacked on top of one another. Well, *three.js* will calculate each individual box's lighting as if it were the only one in the world. Even if you stack them densely on top of each other, they will all look the same - light on top, dark beneath.

The lighting effect you are probably wanting is achieved by ShadowMaps in *three.js*. Shadowing portions of an object that are obscured by other objects is a complex and expensive task which is still being hashed out by the creators of *three.js*.

The normal ShadowMap mode in *three.js* looks OK for now however and it works in most cases.

---
Tags: lighting, webgl, three.js
---


# Question
Title: C# Unity3D - How can I use a INT from other classes?
I have 3 Objects Capsule 1, Capsule 2 and Capsule 3. Every Capsule has a script on it for health/damage. It also contains an int for hits and points. Hits should be increased by one for every bullet that hits the target. Points if it gets destroyed (After 3 hits). These ints for points and hits should be displayed as a TextMesh. But how can I add 3 different ints to an Textmesh? Tried this code, but middle and right doesn't exist in context.

```
meshPoints.text = "Points: " + (points_right + points_middle + points_left) + "\nHits: " + hits_right;

```

How is that possible?

Using one script "health" on all of the objects doesn't work as well because after an object gets destroyed the ints become resetted...

# Answer
You should collect the 3 capsule objects like

```
GameObject[] capsules = GameObject.FindObjectsWithTag("capsule");

```

(perhaps you should add a tag to your gameobjects) and then your line will be

```
meshPoints.text = "Points: " + (capsules[0].GetComponent<ScriptAttached>().points_right + capsules[1].GetComponent<ScriptAttached>().points_middle + capsules[2].GetComponent<ScriptAttached>().points_left) + "\nHits: " + hits_right;

```
> 0 votes

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


# Question
Title: Legal issues for a "fangame" of a commercial franchise?
I've played around in the past of the 2D Flash fan-made version of the popular Valve game Portal. It has basically the exact same mechanics, but as a 2D side-view flash game.

Lately I've toyed around with creating a simplified flash version of some of my favorite franchises (such as Zelda, Mario, Splinter Cell, etc.). Of course, nothing is "stopping" me from just using the same mechanics and just changing the name to something not copyrighted.

I have witnessed projects that have tried to *directly* port a 3D game into a 2D simplified version, with the exact same plot and puzzles (Ocarina of Time in 2D comes to mind), and I have seen them being shut down. But I am not likely going to exactly duplicate any game...just borrow some of the source material and basic underlying mechanics.

For example, if I were to make a Zelda-influenced fan game, I would have items such as the Hookshot, Boomerang, and all other sorts of ones from the Gameboy Zeldas; just with a custom plot and dungeons. With likely the same mechanics.

What are the legal issues involved in this? I used to think it was a "Don't do this ever; it's a bad idea."

But then I've seen the Portal clone, and now I'm curious.

# Answer
Have a read of this. Here are some quotes.

> The original copyright holders have full legal justification to order a cease and desist upon fangame projects, as by definition, fangames are unauthorized infringing uses of copyrighted property.
>
> Most companies that don't outwardly promote or challenge fangames have in the past exacted a de facto policy of non-involvement or neutrality, officially stating that their copyrighted material may not be used without permission, but refusing to prosecute fangamers for doing so, in much the same way as fanfiction is tolerated.
> 26 votes

# Answer
Fangames (or fanart) are really a gray area in copyright laws since that protects the "work" itself. Here is the dirty secret lawyers don't want you to know; *characters cannot be copyrighted*. Character portrayals can be protected by copyright, since that is actual work, which is what lawsuits specifically on copyright usually hinge on. If you are using someone else's actual art assets then that is a direct violation of copyright.

The closest anyone got by fully protecting a character portrayal was Disney company who managed to trademark Mickey Mouse's ears. Which is, as Tetrad mentioned, the reason why companies usually send out cease-and-desist on *trademark issues*. Using trademarked names of the game or game characters is an violation of trademark. The reason is that the trademark is rendered useless if the protected name is used regularly in daily speech or denote something different. This is why Google's lawyers have been so adamant about sending cease-and-desist letters telling people to stop "google" for stuff. Another well-known example of trademark under fire has been Xerox.

As far as I know gameplay mechanics could be patented by software patents (something you can ignore if you're not a US-resident). Patenting gameplay mechanics is ludicrous at this point because the gaming industry hinges on copying mechanics between each other.

The worst thing that could happen is the offended company sends you a cease-and-desist order, in which your response is to stop working and/or spreading your fan game.
> 17 votes

# Answer
Just because things exist doesn't mean that they aren't violating copyrights or trademarks. I'd recommend reading up on those two terms first and understanding them fully.

I'm not a lawyer, but from my understanding the breakdown basically goes like this:

Brand names, logos, etc. fall under trademarks. So if you call your fan game Sonic anything you can pretty much expect a cease-and-desist from Sega. Trademarks are funny things in that companies are practically required to defend them lest they end up losing them.

Things like individual graphics or other art assets, level design, etc. fall under copyright law. If you aren't the copyright holder, you don't have legal authority to distribute them without the permission of the copyright holder. However, things like overarching game design are not.

Then there are a few patents here and there. These aren't as common, but do exist. For example, I think the scoring mechanism in Tony Hawk Pro Skater 2 is patented.

There are some things that probably fall under both categories. I'm pretty sure an image of Mario can be seen as both a trademark of Nintendo, as well as a copyright of them.

So basically, don't do it. You can use game mechanics, and you can make "spiritual successors" all day long, but don't use the name of the game or any non-generic names of items used in the game, or any graphics/sounds/levels from the game.
> 11 votes

# Answer
This is the answer I gave on Am I allowed to release a fan-made version of a Trading Card Game on a fansite?, which was marked as a duplicate of this one. I hope nobody minds if I re-post here as I think it mentions some points that haven't been raised here and summarizes a bit better:

I am not a lawyer, but as a software developer and occasional artist, I've investigated this a bit so I know what I can do to protect my work and also so I don't accidentally screw myself over. While it would help to know what country you're in, because different countries have different laws that may also affect you, I'll make an attempt at answering your question.

You'll likely run afoul of Copyright. The owner of Copyright over a certain work (and Copyright in most countries is implicit, and does not require it saying something is copyrighted explicitly) has full control over how and whether at all something may be distributed. This applies to any graphics in the game, any sounds. While it's OK in most countries to make a photocopy of something for personal use, and sometimes even pass it on to a friend, most courts will consider posting something on the internet (where it's publicly accessible) as redistribution. So unless all of this is in a closed, password-protected area, you shouldn't be doing this. It would be treated about the same as pirating software or movies.

Also, keep in mind that many countries have higher fines for commercial infractions. And in many countries (e.g. where I live in Germany) just having ads on your page or having a link to your company's (unrelated) store in the navigation will make it considered commercial (as you could be using it to draw customers there).

Names are usually covered under trademark law. So if anyone already uses that name, and it's not a generic term, you can not use that name. If they've registered the name as a trademark, they can cause even more damage more easily (but a trade mark doesn't have to be registered to let them sue you). So you can't use the others' name either. At most, you might get away with saying that your game is "in the style of" another game, but that's a risky proposition.

So in short: Don't do it. Just make placeholder graphics (or hire someone to do them), make up your own names. The rules are not protected, but even though you can draw your own graphics for a deck of regular French playing cards, the graphics of commercial decks being sold out there are copyrighted, unless they explicitly say otherwise or you can prove that the artist has been dead the requisite 70 years.

**Note:** There are fan productions out there that don't adhere to these rules and get by fine. That usually is totally due to benevolence on the part of the Copyright owners, you can't expect this in every case. E.g. Anne Rice was known for a long time to go after fan fiction web sites asking them to take down stories.

**Update:** Here's a recent case where Nintendo is requesting a takedown of a fan-game, though apparently they actually took graphics and sounds from original games, so this is a much more clear-cut case than most fan-games: http://www.eurogamer.net/articles/2015-03-31-nintendo-issues-takedown-notice-for-super-mario-64-hd-project

**Update 2:** Another interesting recent case is the recent hoopla over Star Trek fan films. It was surprising Paramount/CBS/Viacom/whoever else is involved right now let fans get away with this much for this long.
> 1 votes

---
Tags: legal, commercial
---


# Question
Title: After sometime increase the speed of Instantiated object
This may look similar to "increase speed after every N seconds" type question but it's different because objects are being Instantiated and getting destroyed.

In my `start()` method I'm calling a method called `CreateObstacle()` after a certain time interval using `InvokeRepeating` method:

```
InvokeRepeating("CreateObstacle", 1, 3f);

```

For those who don't know about the parameters of `InvokeRepeating` method. The first one is the method name which you want to call. The second is the number of seconds to delay these repeated calls. And the third parameter is the number of seconds between method calls.

In `update()` method I'm simply storing time per seconds in a float `translation`:

```
translation = Time.time;

```

Then finally in `CreateObstacle()` method I'm checking that `if` the seconds are less than 10 then `Instantiate ((rocks), new Vector3 (11, -3, 0), Quaternion.identity);` else `if` seconds are greater than 10 do the same `Instantiate ((rocks), new Vector3 (11, -3, 0), Quaternion.identity);` **but with more speed.**
So, how to increase speed of the object that is being Instantiated after a certain time interval say 10 seconds. On in which method I should call the `InvokeRepeating` to decrease it's speed?

**but with more speed** Explanation:
Rocks are moving from right to left in the screen. And after every 3 seconds a new rock appears, move right to left and get destroyed. So what I want is that after sometime say 10 seconds the speed of right to left motion increase.

# Answer
In each Rock GameObject, just have a script that fires off a StartCoroutine in the Mono Start() method. The method the Coroutine calls can either have a yield WaitForSeconds call or your own custom timer logic before firing off the increase in speed.

In regards to adjusting the speed of each object, I'm assuming you have something like a RockController script on each Rock GameObject. In that script each rock could have their own Speed variable which you'd then increase in the method you call from the Coroutine.

In short, when you instantiate a new rock object, it will automatically delay a call to increase it's own speed by a set amount of time.

\*** UPDATE

Here's an even simpler quick example to give you a rough idea. Place the RockController on each rock and then the speed should increase every few seconds as you define. I tend to stay away from SendMessage but it'll do in this context. \[untested code\] :

```
public class World : MonoBehaviour {
    private float increaseSpeedTimer = 3f; // 3 secs
    private float speedToIncreaseBy = 1.5f;

    void Start() {
        InvokeRepeating ("DoTimer", 0.001f, increaseSpeedtimer);
    }

    void Update() {

    }

    private void DoTimer() {
        gameObject.SendMessage("IncreaseSpeed", speedToIncreaseBy);
    }
}

public class RockController : MonoBehaviour {
    public float speed = 10f;

    void Start() {

    }

    void Update() {
        // move the rock
        transform.position.x = transform.position.x + speed * Time.deltaTime;
    }

    private void IncreaseSpeed(float s) {
        speed += s;
    }
}

```
> 1 votes

# Answer
as `Instantiate` creates a duplicate of a prefab, just attach a script defining your Rock to the rock `GameObject` and make sure you have in the `Start()` function a constructor that takes the elapsed time and modify your rock speed consequently.
> 0 votes

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


title: Flushing KeyboardState

text:
# Question
Title: Flushing KeyboardState
I'm using a simple InputManager class for an XNA game with keyboardState and lastKeyboardState that gets updated and has KeyDown/KeyReleased/KeyPressed functions... but ran into a small problem:

I have the 'Enter' key being used to select a tile on the map, which brings up a menu to build something on that tile... but once the menu is up, then it's updating to check whether the Enter key has been pressed to select a menu option. So the logic ends up something like this: IsKeyPressed(Keys.Enter) is true -\> Open Menu -\> IsKeyPressed(Keys.Enter) still true -\> Menu Option 1 selected. Obviously, I don't want the game to automatically select whatever the first menu option is. Sooo, I thought maybe I could just 'flush' the old KeyboardState for one frame after IsKeyPressed so it can't still be true when the menu pops up... but apparently a KeyboardState isn't nullable.

Any ideas as to how I could flush the lastKeyboardState?

Here's the class:

```
using System;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace Your_Quest.GameEngine
{
    public class InputManager : Microsoft.Xna.Framework.GameComponent
    {
        #region Variables

        static KeyboardState keyboardState;
        static KeyboardState lastKeyboardState;

        static GamePadState[] gamePadStates;
        static GamePadState[] lastGamePadStates;

        #endregion

        #region Properties

        public static KeyboardState KeyboardState
        {
            get { return keyboardState; }
        }

        public static KeyboardState LastKeyboardState
        {
            get { return lastKeyboardState; }
        }

        public static GamePadState[] GamePadStates
        {
            get { return gamePadStates; }
        }

        public static GamePadState[] LastGamePadStates
        {
            get { return lastGamePadStates; }
        }

        #endregion

        #region Constructor

        public InputManager(Game game) : base(game)
        {
            keyboardState = Keyboard.GetState();

            gamePadStates = new GamePadState[Enum.GetValues(typeof(PlayerIndex)).Length];

            foreach (PlayerIndex index in Enum.GetValues(typeof(PlayerIndex)))
            {
                gamePadStates[(int)index] = GamePad.GetState(index);
            }
        }

        #endregion

        #region Methods

        public static void Update()
        {
            lastKeyboardState = keyboardState;
            keyboardState = Keyboard.GetState();

            lastGamePadStates = (GamePadState[])gamePadStates.Clone();
            foreach (PlayerIndex index in Enum.GetValues(typeof(PlayerIndex)))
                gamePadStates[(int)index] = GamePad.GetState(index);
        }

        public static bool KeyReleased(Keys key)
        {
            return keyboardState.IsKeyUp(key) && lastKeyboardState.IsKeyDown(key);
        }

        public static bool KeyPressed(Keys key)
        {
            return keyboardState.IsKeyDown(key) && lastKeyboardState.IsKeyUp(key);
        }

        public static bool KeyDown(Keys key)
        {
            return keyboardState.IsKeyDown(key);
        }

        public static bool ButtonReleased(Buttons button, PlayerIndex index)
        {
            return gamePadStates[(int)index].IsButtonUp(button) && lastGamePadStates[(int)index].IsButtonDown(button);
        }

        public static bool ButtonPressed(Buttons button, PlayerIndex index)
        {
            return gamePadStates[(int)index].IsButtonDown(button) && lastGamePadStates[(int)index].IsButtonUp(button);
        }

        public static bool ButtonDown(Buttons button, PlayerIndex index)
        {
            return gamePadStates[(int)index].IsButtonDown(button);
        }

        private static void Flush()
        {

        }

        #endregion
    }
}

```

Note: Ideally, I'd like to be able to just use KeyPressed 90% of the time without it always being true that the key has been pressed a moment afterward, and I have a TimeManager class that keeps track of the individual frames where I could do a simple InputManager.Flush() every other frame if I knew some way of actually 'removing' the current state of the lastKeyboardState.

# Answer
Actually you can simply do:

```
private static void Flush()
{
    lastKeyboardState = new KeyboardState();
}

```
> 0 votes

# Answer
I'm assuming the rest of your code goes somewhat like this:

```
        if(KeyPressed(Keys.Enter))
            bringUpMenu();

        if(KeyPressed(Keys.Enter))
            selectMenuOption();

```

and you want to flush the values somewhere in the middle? Well the solution I thought of would be to add the line "keyboardState = lastKeyboardState" to the first if statement...

```
        if(KeyPressed(Keys.Enter))
        {
            bringUpMenu();
            keyboardState = lastKeyboardState;
        }

        if(KeyPressed(Keys.Enter))
            selectMenuOption();

```

That way, it sort of "jams up" the keyboard until next frame. That way, the user will have to release and then press enter again to activate any menu selections.

One thing I'd advise against doing though is using this workaround too much - otherwise to the user it might almost seem as if their keyboard is swallowing all their keypresses whenever they select a tile / menu option - which is sort of what it looks like you want to do, but not always a good idea to do a lot.

Hope this helps!
> 0 votes

---
Tags: xna, input
---


# Question
Title: Input.mousePosition gives a NullReferenceException
I'm trying to Add raycast shooting to my player but when I get the Vector2 mouse position it give this error

> NullReferenceException: Object reference not set to an instance of an object

This is my code

```
   Vector2 mousePosition =
         new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
                     Camera.main.ScreenToWorldPoint(Input.mousePosition).y);

```

How can i fix this ?

# Answer
> 3 votes
`Camera.main` will be null if you don't have a camera in your scene with the tag `MainCamera`.

If you don't want to tag the camera, you can't use `Camera.main` but you can specify the `Camera` script you want to use. Something like:

```
GameObject cameraObject = GameObject.Find("MyCamera");
Camera myCamera = cameraObject.GetComponent<Camera>();
 Vector2 mousePosition =
                 new Vector2(myCamera .ScreenToWorldPoint(Input.mousePosition).x,
                 myCamera .ScreenToWorldPoint(Input.mousePosition).y);

```

Though, it's easier to just tag your main camera.

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