# Question
Title: How to make an Assert.IsNull test pass when the value is reported as <null>?
I've just started using unity tests with the built in editor tests. After making my test and finding out that it constantly failed I debugged the code and found that a static object was set to a new game object when running the test while it is set to null when playing in the editor.

Is there a way to force unity to treat the test the in the same way that it treats scripts at run time?

**Edit**

After changing some code around i get another strange error:

does anyone know why "null" isn't "null". The null objects are stored in an array, but that shouldn't make a difference right?

**Edit Edit (Edit 2?)**

Here is the code that has the issue

```
public class StatCollector : MonoBehaviour {

    public static StatCollector running;

    //ensure that there is only one object running at the same time
    public void Awake () {
        if(running == null)
        {
            DontDestroyOnLoad(gameObject);
            running = this;
        }
        else if(running != this)
        {
            DestroyImmediate(gameObject);
        }
    }
}

```

and here is the test:

```
[Test]
public void SingleTest()
{
    //create gameobjects
    GameObject[] collect = new GameObject[2];
    collect[0] = new GameObject("one");
    collect[1] = new GameObject("two");
    collect[0].AddComponent<StatCollector>();

    //see if gameobjects were created correctly
    if (collect[0] == null || collect[1] == null) Assert.Fail("failed to create game objects");

    //test what happens when the second stat collector is added to the scene
    collect[1].AddComponent<StatCollector>();
    collect[0].GetComponent<StatCollector>().Awake();
    collect[1].GetComponent<StatCollector>().Awake();
    Assert.IsNull(collect[1]);
}

```

I'm assuming that there is no way to keep Awake private which is why it is public (just so that the test case has access to it)

# Answer
> 9 votes
## First some background...

There are two flavours of "null" in Unity:

* Actual `null`
* "Pseudo-Null" - this is a non-null Unity object (usually a `GameObject` or `MonoBehaviour`) that has been removed from the scene using `Destroy` or unloading a scene.

(In-editor, this is also used for reference fields in an Inspector that have been left blank)

The reason this is called pseudo-null is that for an object in this state, `(destroyedObject == null)` evaluates to `true` using an overloaded operator.

Using `DestroyImmediate()` should put an object into this state immediately, while using `Destroy()` will do so at the end of the current frame's updates but before rendering, which can often help avoid order-of-execution bugs when multiple scripts are referencing an object.

The thing is that a "pseudo-null" reference isn't actually `null`, which you can confirm by calling:

```
System.Object.ReferenceEquals(destroyedObject, null); // returns false

```

...or by trying to access any of the object's members - you won't get a null reference exception, but a Unity `MissingReferenceException` (which is handy, because the debugging tools can tell you more about *which* object got destroyed while a script was still trying to use it - something we don't get from real nulls).

This psuedo-null stub will remain until all references to it are cleared/go out of scope, using normal C# garbage collection rules. Read more about the reasons this exists in this Unity blog post.

---

## How this applies to your test

My guess is that `Assert.IsNull()` at the end of your test is internally checking for *real* `null` instead of comparing with the overloaded operator.

(Especially if you're using Microsoft.VisualStudio.TestTools.UnitTesting.Assert rather than Unity's version \- I don't see any `using` statements in your code so I'm guessing)

Since the destroyed object is only *pseudo-null*, this check comes back false, tripping the assertion.

We can ensure it uses the overloaded operator to also detect pseudo-null by rephrasing the assert at the end of your test as:

```
Assert.IsTrue(collect[1] == null);

```

We know this `==` will return `true` for a Destroy()ed object, whether it's recently-destroyed or long-dead, so this phrasing reliably checks for what we want.

---
Tags: unity, debugging, testing
---


title: Moving a ship forward from rotation

text:
# Question
Title: Moving a ship forward from rotation
I am making a simple space simulator, where the player can control a ship using 2 controls, one for pitch and one for bank. The ship is properly rotated but I cannot figure out how to make the ship move forward based on that angle. Here's what the code looks like right now:

```
func renderer(renderer: SCNSceneRenderer, updateAtTime time: NSTimeInterval) {

    let t=CGFloat(time - lastTime)

    ship!.transform = CATransform3DRotate(CATransform3DRotate(CATransform3DRotate(ship!.transform, ud*t, -1, 0, 0), 0.00, 0, 1, 0), lr*t, 0, 0, 1);

    ship!.position = ?

}

```

I tried every combination of vector, euler angles, matrices, quaternions that I could think of/read about with no success. I am probably missing something stupid but cannot find what it is.

The code is in Swift using Scenekit, but language doesn't matter that much to me and I can translate any algorithm. It's also worth noting it does not work like Unity and Quarternions/Vectors don't have properties like .forward() etc.

Thank you for your help!

# Answer
You will need a forward vector which represent the forward direction of your ship, and the velocity of your ship.

```
// Stuff that you need (or already have)
vec3 shipForwardVector; // This is according to your game infrastructure
                        // and ship model; make it a unit vector.
mat4 worldSpaceRotationMat; // assuming ship!.transform is only the rotation.
float maxVeolicityPerSecond; // Your game settings
float requestedVelocityRatio; // User request; from a keyboard, it's 0 or 1,
                              // from a joystick, 0..1

// Computation
vec3 rotatedForward = worldSpaceRotationMat * shipForwardVector;
float requestedVelocity = maxVeolicityPerSecond * requestedVelocityRatio;
// scale the movement according to the time that has passed
vec3 displacementThisFrame = rotatedForward * (t * requestedVelocity)

ship.position = ship.position + displacementThisFrame

```

---

*Based on Jon's comment, here is an addendum.*

This is an implementation with the suggestion I have already made:

```
// Assuming the following:
float mSideThrustersRadPerSec;// Used to compute how much a ship can turn per second
Matrix mTransform;            // Used to track the orientation of the ship
Vector2 mFrontVector;         // Used to determine where your ship model is pointing in its
                              // local space
float mRearThrustersKmPerSec; // How much are your thrusters able to push the ship
Vector2 mPosition;            // Position of the ship.

if ( sf::Keyboard::isKeyPressed( sf::Keyboard::Left ) )
  mTransform = mTransform.rotate( sfUtil::radiansToDegrees(
    -mSideThrustersRadPerSec * Global::GetInstance().getFrameTime() ) );

if ( sf::Keyboard::isKeyPressed( sf::Keyboard::Right ) )
  mTransform = mTransform.rotate( sfUtil::radiansToDegrees(
    mSideThrustersRadPerSec * Global::GetInstance().getFrameTime() ) );

if ( sf::Keyboard::isKeyPressed( sf::Keyboard::Up ) )
{
  sf::Vector2f offset = mFrontVector *
    ( mRearThrustersKmPerSec * Global::GetInstance().getFrameTime() );
  sf::Vector2f orientedOffset = mTransform * offset;

  mPosition = mPosition + orientedOffset;
}

```

Here is the result:

And this is based on if your ship has a velocity and no external resistance.

```
// Assuming the following:
float mSideThrustersRadPerSec; // Used to compute how much a ship can turn per second
Matrix mTransform;             // Used to track the orientation of the ship
Vector2 mFrontVector;          // Used to determine where your ship model is pointing in
                               // its local space
float mRearThrustersKmPerSec;  // How much are your thrusters able to push the ship
float mFrontThrustersKmPerSec; // How much are your thrusters able to slow the ship (and
                               // eventually make it go reverse)
Vector2 mPosition;             // Position of the ship.
Vector2 mVelocity;             // Speed and direction of the ship
float mSpeedMax;               // Maximum speed of the ship

if ( sf::Keyboard::isKeyPressed( sf::Keyboard::Left ) )
  mTransform = mTransform.rotate( sfUtil::radiansToDegrees(
    -mSideThrustersRadPerSec * Global::GetInstance().getFrameTime() ) );

if ( sf::Keyboard::isKeyPressed( sf::Keyboard::Right ) )
  mTransform = mTransform.rotate( sfUtil::radiansToDegrees(
    mSideThrustersRadPerSec * Global::GetInstance().getFrameTime() ) );

bool shouldApplyOffset = false;

sf::Vector2f offset;

if (
     sf::Keyboard::isKeyPressed( sf::Keyboard::Up )
  && sf::Keyboard::isKeyPressed( sf::Keyboard::Down ) )
{
  offset =
      (  mFrontVector * ( mRearThrustersKmPerSec  * Global::GetInstance().getFrameTime()))
    + ( -mFrontVector * ( mFrontThrustersKmPerSec * Global::GetInstance().getFrameTime()));
  shouldApplyOffset = true;
}
else if ( sf::Keyboard::isKeyPressed( sf::Keyboard::Up ) )
{
  offset = mFrontVector * (mRearThrustersKmPerSec  * Global::GetInstance().getFrameTime());
  shouldApplyOffset = true;
}
else if ( sf::Keyboard::isKeyPressed( sf::Keyboard::Down ) )
{
  offset = -mFrontVector * (mFrontThrustersKmPerSec * Global::GetInstance().getFrameTime());
  shouldApplyOffset = true;
}

if ( shouldApplyOffset )
{
  sf::Vector2f orientedOffset = mTransform * offset;

  mVelocity += orientedOffset;

  float currentSpeed = sfUtil::lenght( mVelocity );

  if ( currentSpeed > mSpeedMax )
  {
    sf::Vector2f direction = mVelocity / currentSpeed;
    mVelocity = direction * mSpeedMax;
  }
}

mPosition = mPosition + mVelocity;

```

With the result:

You can get the working VC2013 code here (it uses SFML).
> 1 votes

# Answer
Well, I generally use to ask this questions in interviews :)

Although I don't know Swift but I can give you a general idea about to achieve this.

You have to play with some trigonometry to get current direction vector according to your current angle.

Here is the pseudo code.

```
float speed = 0.01

void GameLoop()
{
    // I don't know that how Vector2 works at your end, but I hope you will get this.
    Vector2 currentPosition = currentPositionOfObject;
    float currentAngle = currentAngleOfObject;
    float directionX = Cos (currentAngle); // check if your Cos method takes angle in radians of degrees.
    float directionY = Sin (currentAngle); // check if your Sin method takes angle in radians of degrees.

    Vector2 newPosition = (currentPosition.x + (directionX * speed),currentPosition.y + (directionY * speed));
    currentPositionOfObject = newPosition;
}

```

I have already answered the same question but in Unity (C#) here. Just for reference if you want more details.
> 0 votes

---
Tags: rotation, movement, vector, quaternion
---


# Question
Title: How to identify entrances of a cluster in HPA*?
Recently I've become interested in understanding and implementing HPA\* in a RTS game. I've found the following presentation which is really good for explaining how HPA\* works: https://harablog.files.wordpress.com/2009/06/beyondastar.pdf

At slide 28 it says "identify entrance points between clusters". Slicing my map into several clusters is easy, but I can't get the idea how to identify the points between clusters. "Should I take the middle? Border points? All of them?"

I've struggled to look at some implementation in java, C# or C++ but games like 0 A.D. use a different strategy for implementing hierarchical graphs mixed with Jump-point search. Others like libgdx-ai use multi-level HPA\* and can't find an implementation simple enough to understand and reproduce, specially on the matter regarding entrances and how to connect them.

Can anyone enlighten me?

Thanks

# Answer
> 1 votes
"Entrances" are simply the rectangles where both clusters have open squares on their side, right?

Computing them in pseudocode is something like this:

* Iterate along edges shared by two clusters
    + For each tile, if tile is open
        - Check if tile on the other side of the edge is open. If so,
            * If currently tracking an entrance, add these two tiles to it.
            * Otherwise, start tracking a new entrance, and add the tiles to it.
        - Otherwise it's not open, so
            * If currently tracking an entrance,
                + Close out the entrance (stop tracking and record it)

In the example on slide 28, you can imagine they were iterating downwards along the orange middle vertical divide. They found (for those 8 tiles) that both sides of the orange divide were open. So, they marked those 8 as an entrance. Later they did as in slide 29 and computed a central transition point, which is the two opposite-side (different cluster) tiles that are closest to the center.

Then the algorithm continues on, joining those transition points, etc.

Does this answer your question?

---
Tags: path-finding
---


# Question
Title: How can I randomly spawn circles on a screen but make sure they don't overlap?
I just need a general idea for how to do this.

I have a list of Circle objects.

```
Circle {

private int yCoord;
private int xCoord;

Circle(int a, int b) {

xCoord = a;

yCoord = b;

}
}

```

I randomly spawn circles on a screen:

```
private void spawnCircles() {

   //Spawns new circle in a rectangular region that starts at top corner
   //of screen and has 100 pixels length and width.
   Circles.add(new Circle(rand.next(100),rand.next(100));
}

```

The radius of the circles is 20 pixels.

How can I spawn these circles randomly so they don't overlap?

All I need is pseudo code or a rough outline.

# Answer
> 3 votes
You did not specify whether you will have many circles or just a few. However, by the measures you mentioned I assumed it's just a few (by the way, if the measures you are thinking of are correct, only 4 circles will fit perfectly into the rectangle...).

So, if you have just a few circles, you can opt for a very naive solution: save each new valid circle in a list and check if the next to be generated overlaps any of those already in the list. In a bit more detail, you would run a "while" type of loop, doing the following at each iteration:

1) generate the center point (X,Y) of a new circle with your random generator code;

2) check whether that circle is overlapping any of the other circles already present in the list of circles. Although it's iterative since you will have to check each pair of circles each time, that is a very cheap test in terms of computation.

To test whether two circles overlap you just have to check whether the distance between their center is smaller than the sum of their radii: if such distance is:

1. is smaller, then they overlap;
2. identical, then they just touch each other at one single point;
3. greater, than they don't neither touch nor overlap each other;

3.1) if the new circle does not overlap any of the other circles in the list, that is fine and you can include add it to the list and move back to step one.

3.2) if the new circle does overlap any of the other circles, you can don't include the new circle in the list and go back to step one.

# Answer
> 2 votes
If you're not in need of a very fancy way to deal with this problem you could just brute-force it by doing these steps:

1. Randomize the circle coordinates.
2. Check if the distance vs all other circles that you have drawn. If it is greater than the sum of the radius of the two circles (40, in your case) you can go ahead and draw the circle.
3. If it is equal to or less than the sum of the radius of both circles, re-randomize the coordinates and perform these steps again until a preferred amount of circles has been drawn.

Distance method:

```
public float checkDistance(float x1, float y1, float x2, float y2) {
    // If you use this, make sure the x and y values are the center of the circles.
    float distanceX = x1 - x2;
    float distanceY = y1 - y2;
    float distance = distanceX*distanceX + distanceY*distanceY;
    return distance;
}

```

Or preferable might be to add this method inside your Circle class:

```
public float checkDistanceTo(Circle circle) {

    float distanceX = this.xCoord+radius - circle.getXcoord()+radius;
    float distanceY = this.yCoord+radius - circle.getYcoord()+radius;
    // In your case, radius would be 20.
    float distance = distanceX*distanceX + distanceY*distanceY;
    return distance;
}

```

---
Tags: java, android
---


# Question
Title: Combining raster textures with vector graphics. How can I do this? (See image)
I'm developing an art style that combines pixel art with simple vector graphics, but I'm feeling lost and need clarity what is technically possible within game engines.

First of all, take a look at this image:

How can I achieve this look with game engines/libraries? Is it even possible? What can you recommend?

The game is supposed to run on PC, 60fps preferable, uses pixel sprites for smaller objects, while using simple shapes to represent very large objects. I want it to have a lighting system, all shapes must be able to rotate, move and scale at runtime and have seamlessly tiling pixel art textures drawn on top of them.

# Answer
> 2 votes
You can achieve this with any graphics API or 3D engine/framework. Your vector graphics can be created from polygons, then you map a texture onto them.

---
Tags: vector-art, pixel-art
---


title: Procedural rock algorithm

text:
# Question
Title: Procedural rock algorithm
I'm looking to create some procedural low poly rocks and boulders for a game.

I haven't found much interesting information on the internet other than 3D software articles. Not sure what way to go.

# Answer
> 4 votes
One approach could be to start with a sphere, perhaps pick some random parameters to stretch it varying amounts so some rocks are roughly round, while others are roughly egg shaped, then use 3D perlin or simplex noise and it's fractal variants (see the fbm methods in the link) to push vertices in towards the center, or pull them out, by some multiple of the perlin noise result. You would just pass the 3d coordinate of each vertex to the 3d perlin noise function, get back a float in the range \[0,1\], and use that to push or pull the vertex.

If you let me know what environment/language you are working with I can go into more detail.

# Answer
> 3 votes
When I create rocks in modelling softwares, I start from an icosaeder, fhen stretch it around, scale it a nit, then I just pick random vertices and I pull them a bit out. I suppose, the same can be made with code

---
Tags: 3d, 3d-meshes, procedural
---


title: "Normal" Blend Mode with OpenGL Trouble

text:
# Question
Title: "Normal" Blend Mode with OpenGL Trouble
I've been having a lot of trouble trying to get a OpenGL blend function to work as I'd expect it to with like what I'd expect (or from any sensible image editing program). As an example, I'll use these two images to blend (bit difficult to see on white backgrounds so the colors are labeled):

**Images to be blended**

This is what I expect to happen (and what happens in paint.net):

**Expected Result**

Obviously opengl's default blend function makes it look like this (very wrong):

**glBlendFunc(GL\_SRC\_ALPHA, GL\_ONE\_MINUS\_SRC\_ALPHA)**

After a ton of testing, this is the closest I could get to creating a "good" blend function:

**glBlendFuncSeparate(GL\_SRC\_ALPHA, GL\_ONE\_MINUS\_SRC\_ALPHA, GL\_ONE, GL\_ONE\_MINUS\_SRC\_ALPHA)**

Looking back at the original expected result though, you'll notice that some of the colors are a bit dimmer than they should be (the middle left part). Specifically, they are premultiplied to half their color value (because of the .5 alpha), and I can't seem to make a function that does not do this (without causing odd blending issues with the barely visible red transparent part).

Does anyone know a solution to this issue? One that I had was to use premultiplied alpha in the sources (while I dont want to do this because it requires extra work to convert every color I use in my game to premultiplied or just write some stuff in each shader) and do it like that:

**glBlendFuncSeparate(GL\_ONE, GL\_ONE\_MINUS\_SRC\_ALPHA, GL\_ONE, GL\_ONE\_MINUS\_SRC\_ALPHA)** (No premultiplication)

Obviously thats wrong too, but this is actually the only correct result I've gotten so far:

**glBlendFuncSeparate(GL\_ONE, GL\_ONE\_MINUS\_SRC\_ALPHA, GL\_ONE, GL\_ONE\_MINUS\_SRC\_ALPHA)** (Premultiplied inputs)

Only problem is, how would I get rid of the premultiplication to display it on the screen? It would probably require an additional render cycle for each thing I blend and that seems way too complex for this issue, so I'm still looking for an answer (its interesting that I cant find anything on this, because OpenGL is so widely used that I'd image someone else ran into this problem).

**Sources:**

Online blend function testing - http://www.andersriggelsen.dk/glblendfunc.php
Bottom Layer Image - https://i.stack.imgur.com/XjLNW.png
Top Layer Image - https://i.stack.imgur.com/9CN6w.png

# Answer
> 6 votes
In your first example (`glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)`), you're telling it to blend colors based on the alpha of the image which gets drawn on top (the "Foreground" one). So when you're blending 50% between the foreground color `(38,50,168)` and the background color `(38,50,168)` in the bottom left corner of the image, you unsurprisingly get exactly the same color `(38,50,168)`. Because that cross-blend is exactly what you told OpenGL to do.

Judging by your "expected" image, you don't want to do a cross-blend between the two colors -- you want to overlay the foreground color over the full-strength background color, not cross-blend between them.

To do that, you want to use glBlendFuncSeparate (since you're treating the background's color differently than its alpha), and specify that during the blending operation, the background alpha value should be treated as 100%.

To make it easier to view, here's the final RGB values being output:

And here's the final transparency values being output.

(That '100%' transparency area should actually be labelled as 99.7% transparent, and the bottom right '50%' area should be labelled as 49.7% transparent, both due to the red-tinted bit on the right side the first image. Also, sorry for listing numbers using "transparency" rather than opacity; possibly a little confusing.)

If there are specific problems, please point out the area of either the RGB or the alpha image which are producing incorrect values.

# Answer
> 1 votes
I had the exact same problem when I wanted to render a set of overlapping framebuffer objects like layers. The problem is Open GL blending functions is linear and it works when destination background is opaque. But actual blending equation for blending two transparent layers is not a linear equation and contains a division part.

out\_color = {src\_color * src\_alpha + dest\_color * dest\_alpha * (1-src\_alpha)} / out\_alpha

I don't think it is possible to do this with current OpengGL implementations. So as a work around I had to user a pixel shader to manually calculate the output of each pixel.

---
Tags: opengl, blending, alpha-blending
---


title: Inverting a Font?

text:
# Question
Title: Inverting a Font?
How can I invert a font like so:

See here:

This is my own `.ttf` font, I can edit it. The image that I posted was inverted manually by me. I am searching for a way to invert automatically all characters of the font.

Invert means: convert 1 to 0 and 1 to 0. Which will convert the filled (black) parts to transparent and the transparent parts to filled.

I want a "Font Invertor" software or a simple way to achieve this. Does `High-Logic FontCreator` do this? I didn't find a way with the latter.

# Answer
> 3 votes
The way outline fonts (such as ttf) work is by defining a set of curves by vector graphics (quadratic Bézier in the case of ttf).

What is inside or outside? At the moment of rendering the target area has a set of pixel where the character will be drawn. The following is a simplification of the algorithm to do so:

* Go row by row:
    + Start by considering we are "outside"
    + If we are "outside" and we crossed an outline, are now "inside"
    + If we are "inside" and we crossed an outline, are now "outside"
    + If the current pixel is "inside" color it
    + Advance to the next pixel

Visually:

These are the outlines:

Now, we start outside. We advance to the first pixel. We have not crossed any outline, so the pixel is outside and we don't color it (highlighted in ligh gray):

We are outside, We advance to the next pixel. We crossed an outline, so now we are inside. Since the pixel is inside, color it:

Continue advancing, we don't cross any outline for the next few pixels - so we keep coloring them:

When we cross the other outline we are outside again:

If we do this for each row, we will have the character fully colored:

Note: this is disregarding antialias, subpixels, and any transformation applied to the character. Also, since this is a didactic explanation, I'm pretending the outlines alway fall between pixels, in reality you will have - for example - pixels that are 60% outside and 40% inside. For a more detailed explanation (and a bit of history) see the video The Font Magicians - Computerphile.

---

**Getting the inverse outline**

Now, see what happens if I **remove the exterior outline**:

If we follow the steps described above, the result is this:

**Note**: To do this in FontCreator select all the points - and only the points - of the exterior outline and hit delete.

Adjust the size and position of the character as needed.

---

**Getting the inverse bitmap**

Also if you are rendering without antialias, you may always take the character bitmap...

Fill the exterior (that may be tricky, as you need to start a flood fill on a pixel that you know is outisde, the key is to check the color first):

And then get the inverse of the image:

Note: this is proably ruined if you have antialias.

# Answer
> 0 votes
Your expected outcome contains a step that will become a problem.

To get to the result you must first determine what part of the graphic is considered a letter. Your original font is basically an outline.

So what you're looking for is to detect what part of the letter is the 'inside' and fill that.

The problem here is that it becomes hard to detect. How would you find the tittle (the dot on a **i** or **j**) to be part of what you want filled? And how to find if the inside of the **p** should not? And the complication added here is that you made a bitmaplike font where diagonals may be consist of separate blocks entirely. So computationally this ttf font will be complex to invert.

Since the ttf font is monochromatic you can't actually this in post processing either. Draw a text to a bitmap and inverting the bitmap will not produce the desired result. Conside the top left empty block in your image. It is white in both the normal *and* the regular version.

So what to do? Since you are using a bitmaplike font anyway... Use a bitmap font for this. You could use two colors to distinguish the outline and inside and use a shader/code to replace the colors with whatever you want. Use just the inside or just the outside or combine them with fancy color effects!

Note: the inverted process of **creating** an outline for a vector font is a lot easier, as it is basically enlarging the existing data (since that data is actually describing what *is* part of the glyph.

---
Tags: fonts, ttf
---


# Question
Title: Scene2d How to make it work for a Visual Novel
I kinda understand that you can use Scene2d for a Hud or stuff like that, I'm new to Java and so far I've done games that update in real time like let's say Flappy bird (simple games), so i wanted to try something different and now I'm kinda stuck, instead of having all the level be decided at the start of the game i want to instead have a forward and backwards button (Visual Novel) that lets me update the screen on each click, the problem is that i don't know how to do it in a clean way, is there a way to update the button on real time or any technique to have an entire "dialog level" scripted? (sorry if this sounds confusing i don't know how to phrase it properly, if you have played or seen a visual novel you would understand what I'm talking about)

# Answer
> 1 votes
Scene2d would probably be good to use for a visual novel, it's not limited to UI, you could design a whole game with it if you wanted to. You could make a scene2d stage and then add back and forward buttons to it. You could have several buttons that you change label on and use for selecting what your characters says/does. If you find something scene2d can't do, you can just do it yourself or extend one of it's classes. Scene2d actions are really cool.

This playlist does a good job of explaining scene2d, both for UI and for other stuff, and comes with example code linked. https://www.youtube.com/watch?v=DPIeERAm2ao&index=11&list=PLS9MbmO\_ssyCZ9Tjfay2tOQoaOVoG59Iy

If you want branching dialog you probably want to implement some way of loading that into your game. I would look into json, that way you could write all your dialog in files that you can load into your game and you won't need to hardcode that stuff in.

https://github.com/FasterXML/jackson

This is what I used to load my maps in my last project: (removed getters and setters to save space)

```
ObjectMapper mapper = new ObjectMapper();
Level[] loadedLevels = new Level[20];
private int id = 0;
private String image = ("image.png");
private String tileMap = ("mesh.png");
private String description = "default";

public void loadLevels() {
    try {
        String levelFile = "levels.json";
        loadedLevels = mapper.readValue(new File(levelFile), Level[].class);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

```

This read a json with all my levels called levels.json

```
[
  {
"id": 0,
"image": "res\\image0.png",
"tileMap": "level\\tilemap0.tmx",
"description": "GENESIS"
},
{
"id": 1,
"image": "levels\\lab.png",
"tileMap": "levels\\lab.tmx",
"description": "A lab"
}
]

```

I am sure there are some messy and wrong stuff here, but this is the gist of it. The method reads the json and loads every level into an array of levels. This way you can store all the text and stuff in json and read those. Makes editing a lot easier. There are a lot of different libraries you can use to serialize json into objects, with the one I used (jackson) it was as easy as making sure the the variables matched and it would create my objects.

Also, I would probably just start doing it, there isn't really any wrong way to do stuff. If you have your text and choices outside of the main code you can just rewrite the "engine" if you realize it needs to be improved as the projects grows in complexity.

**Edit: Didn't see the android tag, I would assume that you can use json files in a android project, but I don't know anything about android specific stuff.**

---
Tags: android, scene2d
---


# Question
Title: How to make the game run at 60 FPS in Irrlicht?
I want my game run at 60 fps, but I don't know where to start, I have the simple loop:

```
while(device->run()){

```

How do I lock the frame rate to 60 FPS?

# Answer
Sleep is a very bad idea for the reasons already pointed out - the only justifiable case to use it is for saving battery on mobile devices.

If you want to lock to 60 fps one way would be to measure the time that's elapsed since the last frame ran; if that equals or exceeds (1.0 / 60.0) seconds then run a frame. Of course you'll need a high resolution timer to get this right, and of course it's a busy-wait loop that will chew up CPU time, but it works.

(You might even find some useful work to do during that busy-wait period, such as updating dynamic resources or whatever).

Another way is to use vsync. Most monitors nowadays will run at 60hz, and those that don't are extremely likely to support it, so just enable vsync, set your refresh rate if needed, and run as normal.
> 2 votes

# Answer
There are a better solution to get 60fps: set vertical syncronisation (vsync) to true when you create Irrlicht device

```
//Here is the easiest common function to create irrlicht device
irr::createDevice   (
    video::E_DRIVER_TYPE    deviceType = video::EDT_SOFTWARE,
    const core::dimension2d< u32 > &    windowSize = (core::dimension2d< u32 >(640, 480)),
    u32     bits = 16,
    bool    fullscreen = false,
    bool    stencilbuffer = false,
    bool    vsync = false,
    IEventReceiver *    receiver = 0
)

```

For example, use this function:

```
IrrlichtDevice* device = createDevice(EDT_OPENGL, dimension2du(800, 600), 16, false, false, true);

```
> 2 votes

# Answer
Do you want to synchronize on vsync ? There are differents solutions depending on your platform. Search vsync on google. On directx, you can limit on fullscreen app with D3DPRESENT\_INTERVAL\_ONE or use WaitForVerticalBlank on windowed app.

Look this article
> 1 votes

# Answer
Depends what you mean by saying "you want to lock the game at 60fps".

If you want to limit the game rendering at max 60fps its very simple :

Each frame, just check if the game is running to fast, if so just wait :

```
//to call each frame
while( true )
{
    int elapsed_time = getcurrenttime() - oldtime;
    if(elapsed_time >= minimum_elapsed_time)
      break;
    sleep(1); //yield cpu to other game thread or processes...
}

```

Please note that if vertical sync is enabled, rendering will already be limited to 60fps.

But if you want to have your game logic locked at 60fps, no more no less, that's different. Then you have to separate code you want to run at 60fps from rendering code and make necessary changes to make sure that code is called at same fixed time intervals. It is called "fixed timestep". Make a search on gamedev or google. There is a lot of info on this.

---

EDIT : as Roy T. pointed out, code is not guaranteed to works because `sleep(1);` may wait more than 1ms. calling `timeBeginPeriod(1);` at game start (and `timeEndPeriod(1);` at end) should fix the problem (but have some consequences). I choose to call sleep instead of busy-wait loop to give other threads and processes a chance to run while game is waiting...
> 0 votes

# Answer
If you are measuring time you also really need to be using QueryPerformanceCounter as timeGetTime jumps in large increments.

There is a fairly involved blog post on the subject of windows timing:

http://www.geisswerks.com/ryan/FAQS/timing.html

Also, if there are no other threads needing to work Sleep(0) will return immediately, you need to use SwitchToThread, and if that 'fails' call Sleep with a non-zero amount instead to actually go to sleep.

That said, I would still recommend using the vsync features, as that can be turned into a kernel wait on an interrupt behind the scenes and also context switch out properly while waiting, much like the sleep. Also, sleeping is a bit odd of a thing to do as you dont actually know when the vsyncs really occur, even with vsync enabled, so it is hard to sleep a proper amount and not miss the vsync on the next frame in a lot of cases (esp if youre CPU overhead is pushing 15+ milliseconds)
> 0 votes

---
Tags: game-loop, irrlicht
---


# Question
Title: Multitexturing depending on given variables?
I'm having trouble with rendering multiple textures. Using XNA gamestudio: working with 3D meshes and texturing. Effect.fx HLSL

I do have a map/level that loads from a heightmap. - This works

I have created an effect.fx file that renders the textures. - This works

Multitexturing shader works to a degree where I hardly can alter the function.

So I can fade from different textures if I pass a height value, would have worked fine if the world was meant to be solid/static, but that's not the case here.

I want to hold certain variables to the vertex/faces and alter them in realtime while the vertexshader and the other drawing components renders it correctly as the variables is being altered.

If I wanted to paint a vertex/face red on a Grass-textured plane then this mentioned vertex/face would then be red.

I'm having a hard time finding the problem. Wasn't able to make a 2 dimensional for loop within the Pass technique loop "that just made too much thinking and almost crashed the application"

Have looked trough the source codes for a few example app with no success.

I even bought a book on the subject, but all I've got so far is how to render different textures when the vertex/faces reaches a certain height value on the Y axis.

# Answer
> -1 votes
I found that rendering dynamic Entity-textures in XNA such as cubes or "planes" needs alot of HLSL knowledge, how to throw in shaders and more.

I scrapped my XNA project and started with Java OpenGL "LWJGL". ThinMatrix had a good tutorial series with a quick runtrough of the glsl shader system.

with "dynamic" I meant rendering and changing the entity-texture in realtime.

---
Tags: xna, 3d, textures, rendering, hlsl
---


title: Where do assets for Minecraft mods go?

text:
# Question
Title: Where do assets for Minecraft mods go?
I found this link: Where do I store (or how do I refer to) textures for custom blocks?

Unfortunately, the answer did not explain where that assets folder actually is. As such, I can't figure out where the textures themselves go.

I'm trying to replicate the tutorial on minecraftforge.net, so the mod's ID is "generic". For some reason, though, the assets folders all contain folders called "genericmod".

Basically: Can someone give me the exact path I should go to, starting from forge\_1710\_src, to put my graphics in?

# Answer
```
forge_1710_src/src/java <--this is where your code lives, possibly inside more directories

forge_1710_src/src/resources/assets/[MODID]/textures/blocks <--where block textures go

```

http://www.minecraftforge.net/wiki/Icons\_and\_Textures
> 1 votes

# Answer
Why not store fhem inside the jar file? Then you could reference them as YourMainClass.class.getResourcesAsStream(new File(path fo your file))
> 0 votes

---
Tags: java, assets, minecraft-modding
---


title: How does copyright on sources work

text:
# Question
Title: How does copyright on sources work
If I want to create a game in which I use sources from another game that has copyright is illegal. But what if I use screenshots from a 3D game to make another 2D game (something like a questionnaire)? Or what if I use the 3D models from the first game, render them with a program like cinema4D or blender in 2D and use them in the 2D game? And if it is illegal please explain me why and what laws of copyright would apply in that case.

I know that observing how a game works or any software for that matter and then reverse engineering it is legal so doing the same thing with resources from a game is legal. That's why I wanted to make clear my question is not related to reverse engineering.

# Answer
> -1 votes
You use them in the procedure, to create your game. That's pretty much illegal. Just create models yourself, that's tbe easiest way to avoid license and copyright issues.

It's like uploading an image from a random person to your facebook page. The person isn't the picture, the person is only on the picture, but it is still illegal.

# Answer
> 0 votes
It depends, sadly. You might want to consult a real lawyer to determine exactly what should be done, however there is a great answer in general about using one form of art to make another at another website. Highlights:

* If you are using a large number of sources to get a feel, but putting together your own work, you are probably okay.
* If you are directly copying a work, you probably aren't okay.
* If it is your own interpretation of the artwork, you are probably fine. Using a 2D model to build a 3D model is probably okay, especially if you put your own edge to it.
* If in doubt, contact the artist.

So bottom line, don't directly copy anyone's work, but you can use other people's work to make your own if you are using it for inspiration.

---
Tags: assets, legal
---


# Question
Title: Make a sprite jump to a certain direction in libGDX
I was wondering how you can make a sprite jump to a certain direction in libGDX just like the brick does in the famous mobile game "Amazing Brick'

I want to make my sprite jump up a bit to the right when I tap the right part of the phone and make it jump up but to the left direction when I tap on the left part of my phone.

I am using libGDX on android studio and I am on a beginner level, trying to develop a unique game for android. Plz help. Thanks in advance. ^o^

# Answer
Short answer:

```
public void update()
{
    if (Gdx.input.justTouched())
    {
        //Touched left side of screen
        if (Gdx.input.getX() > Gdx.graphics.getWidth() / 2)
        {
            //give actor upforce and and a bit of force to the left
            someActor.setVelocity(new Vector2(-25, 100));

        }
        //touched right side of screen
        else
        {
            //give actor upforce and a bit to the right
            someActor.setVelocity(new Vector2(25, 100));
        }
    }
}

```

The problem is this won't work on it's own. You would need a class for your sprite and give it appropriate down force as well. The amounts you use depend on the units you give in your game.

You could add some drag to the sideway movement by multiplying the X velocity by something like .95. For the downforce/gravity you could use need to subtract something each update so it will eventually fall down. You could use realistic numbers here or make something up and tweak it until it's right.

To move your sprite you use the velocity the actor has.

`position.add(velocity);`

Your best bet is to get familiar with the basic vector math. Start coding and if you run into unsolvable problems come back and ask something more specific.
> 0 votes

---
Tags: android, libgdx, android-studio
---


# Question
Title: How can I save a score for a web game made in Unity and load it when the game starts again?
In other words, how can I load the progress for a game? I only want to store a score and load it again when the game starts (ex. if I get the 100 score and close the game, when I come back, I want to continue my progress from the 100 score)

# Answer
You're looking for `PlayerPrefs`. Take a gander at the documentation.
> 1 votes

---
Tags: unity, savegame
---


title: Unity C#: Game Object Movement Issue

text:
# Question
Title: Unity C#: Game Object Movement Issue
I'm trying to move a game object within a set x and y range. I thought the code below would work, but it does nothing. The idea is the player controls the platform and tries to move under the ball. Any suggestions would be appreciated.

```
using UnityEngine;
using System.Collections;

[System.Serializable]
public class Boundary{
    public float xMin, xMax, yMin, yMax;
}

public class PlatformController : MonoBehaviour {

    public float speed = 10f;
    public Boundary boundary;
    public Rigidbody platformRB;

    void Start(){
        platformRB = GetComponent<Rigidbody> ();
    }

    void FixedUpdate(){

        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHorizontal, moveVertical, 0f);
        platformRB.velocity = movement * speed;

        platformRB.position = new Vector3 (
            Mathf.Clamp (platformRB.position.x, boundary.xMin, boundary.xMax),
            Mathf.Clamp (platformRB.position.y, boundary.yMin, boundary.yMax),
            0f
        );
    }
}

```

Here's how the rolling ball works (as is intended)

```
using UnityEngine;
using System.Collections;

public class BallMovement : MonoBehaviour {

    public Rigidbody ballRB;
    public float thrust;

    // Use this for initialization
    void Start () {
        ballRB = GetComponent<Rigidbody> ();
    }

    // Update is called once per frame
    void FixedUpdate(){
        ballRB.AddForce (Vector3.right * thrust);
    }
}

```

# Answer
> 0 votes
There are multiple things I can think of that could be causing you problems. Here are some things to look at:

* If your rigidbody is set kinematic, setting velocity will have no effect.
* Add debug statements like those in the code below to see what is or isn't working as intended
* Try removing the boundary checking statement to eliminate that as a potential cause of problems
* Movement applied by changes to the velocity property of a rigidbody happens between LateUpdate frames, rather than in the middle of them. So when you set position after applying velocity, the movement
* Apply movement directly yourself (as detailed in code below) rather than relying on the physics engine to do it. This has the added benefit of ensuring the gameobject doesn't leave the bounding box, as movement caused by rigidbody.velocity is applied *between* FixedUpdate() iterations. This means that your code as is will have stuttering at the edges.
* Lastly, is this a 2D game? It sounds like it might be, especially with the X/Y orientation for your movement. If this is the case, you might want to look at using Rigidbody2D components instead of Rigidbody.

If these don't help you figure out the cause, please update with your results and I'll look deeper. Here's my suggested code (assuming a 3D project):

```
using UnityEngine;
using System.Collections;

[System.Serializable]
public class Boundary{
    public float xMin, xMax, yMin, yMax;
}

public class PlatformController : MonoBehaviour {

    public float speed = 10f;
    public Boundary boundary;
    public Rigidbody platformRB;

    void Start(){
        platformRB = GetComponent<Rigidbody> ();
    }

    void FixedUpdate(){

        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Debug.Log("Boundary: (" + boundary.xMin + "," + boundary.xMax + "," + boundary.yMin + "," + boundary.yMax + ")");

        Vector3 movement = new Vector3 (moveHorizontal, moveVertical, 0f);

        Debug.Log("Movement: " + movement);

        //platformRB.velocity = movement * speed;

        // Calculate per-frame movement based on movement, speed, and fixedDeltaTime
        Vector3 move = movement * speed * Time.fixedDeltaTime;
        Debug.Log("Move: " + move);

        /*
        platformRB.position = new Vector3 (
            Mathf.Clamp (platformRB.position.x, boundary.xMin, boundary.xMax),
            Mathf.Clamp (platformRB.position.y, boundary.yMin, boundary.yMax),
            0
        );
        */

        Debug.Log("Pre-move position: " + platformRB.position);

        Vector3 newPosition = new Vector3(
            Mathf.Clamp(platformRB.position.x + move.x, boundary.xMin, boundary.xMax),
            Mathf.Clamp(platformRB.position.y + move.y, boundary.yMin, boundary.yMax),
            0
        );

        Debug.Log("Desired Position: " + newPosition);

        // Using rigidbody.MovePosition instead of setting the position property directly makes the movement respect interpolation settings
        platformRB.MovePosition(newPosition);

        Debug.Log("Post-move Position: " + platformRB.position);

    }
}

```

*Note: There may be typos in my code that will cause compilation errors - if so let me know*

---
Tags: unity, c#, movement, platform, rigidbody
---


title: Multiple Colliders in Collision

text:
# Question
Title: Multiple Colliders in Collision
I have an object that has a front collider, left collider and right collider. When a collision occurs, I notice that there are situations where the front collider and left collider/right collider has collided with the object. I need to somehow figure out which collider made contact "first". Is there anyway to do this? The reason I need this is because I have different code that needs to run depending on which collider made contact first.

# Answer
> 1 votes
You can always use OnColliderEnter (or OnCollisionEnter2D), and store the first collision. So consider something like this:

```
Collider FirstCollider;
int CollisionCount;

void OnCollisionEnter(Collider collider)
{
     if (FirstCollider == null)
         FirstCollider = collider;

     CollisionCount++;
}

void OnCollisionExit(Collider collider)
{
     CollisionCount--;

     if (CollisionCount == 0)
        FirstCollider = null;
}

```

You would want to make sure none of your colliders are colliding before you set FirstCollider back to null.

I haven't tested it, but I figure it should work.

# Answer
> 1 votes
Actually and hopefully you did attach all three colliders on same gameObject. What you have to do is create 3 children gameObject and attach one collider to one child. In that way you can detect what you want.

Attach a Jon's script to each collider then in my OnCollisionEnter you can from which collider collision is occured through tag, any attribute or even with gameObject's name. Like,

```
void OnCollisionEnter( Collision col)
{
    Debug.Log("Collided with: " + name);
}

```

**Update:**

If your only problem is to avoid your own colliders then one of the many solutions is to assign a separate `layer` for your character for example layer name is `Player`.

* Add layer as

* Assign it to parent and children.
* Goto Edit -\> Project Settings -\> Physics, in collision matrix, remove check from Player to Player like,

In this way your player colliders will never fire any event on their own collision.

# Answer
> 1 votes
I'd just like to add, for completeness, that you could always try using a single collider for your GameObject, then infer what side it was on from the collision point.

You can access the point like so:

```
void OnCollisionEnter(Collision collision) {

    foreach(var contact in collision.contacts) {

        Vector3 pointOfImpact = contact.point;

    }

}

```

---
Tags: unity, collision-detection, physics
---


# Question
Title: Is this converting from or to premultiplied alpha?
I found this code buried under some rocks:

```
var divAlpha = 0xff00/color.A;
var r = (byte) (color.R*divAlpha >> 8);
var g = (byte) (color.G*divAlpha >> 8);
var b = (byte) (color.B*divAlpha >> 8);

```

The fields on `color` are bytes, of course. My guess would be it's avoiding using floating point operations to handle premultiplied alpha, but is it converting *from* or *to*? How does this work out?

Example output:

```
0x44112233 -> a: 0x44, r: 0x3f, g: 0x7f, b: 0xbf

```

# Answer
This code is converting *from* premultiplied alpha:

Expanding one of the assignments by substituting for ***divAlpha***:

```
var r = (byte) (color.R*(0xff00/color.A) >> 8);

```

which on rearrangement of the multiplicative terms becomes

```
var r = (byte) ((color.R*(0xff00) >> 8)/color.A);

```

which in turn simplifies to:

```
var r = (byte) (color.R*0xff /color.A);

```

or

```
var r = (byte) (color.R * (0xff /color.A) );

```

which is clearly seen to be a division by the (fractional) alpha channel value.

This can be verified by computing the reverse operation:

```
R: (0x3F * 0x44 + 0x80) >> 8 = 0x113C >> 8 = 0x11
G: (0x7F * 0x44 + 0x80) >> 8 = 0x223C >> 8 = 0x22
B: (0xBF * 0x44 + 0x80) >> 8 = 0x333C >> 8 = 0x33

```
> 3 votes

---
Tags: c#, color
---


# Question
Title: Design basics for Unity game: sport management type
I am planning the classes for my game; and I am having problems to figure out the best way to connect them.

In my game I do not have the classic structure of say a FPS; where you have the player class; with stats, and AI class with enemy AI. my game is more like a sport simulation manager type; so there are various entities:

* The player; which take over a team (or play in a team)
* The NPC: other players, managers, people that work in the club.
* The team (club) itself; where either the player take control of it, so NPC will join it, or will play in it, so the team will have both player and NPCs.
* Competitions: self explanatory; team participate in it.

I was thinking to make different base classes, one for team, NPC, player and competitions, but then I need to establish relations between them.

This look more like a DB with relation between tables, compared to a standard FPS game, where everything is strictly divided and you don't get class that "belong" to some other class.

I am using Unity BTW, so far I ahve the GameManager class; which initialize the main menu, the scene manager and UI manager.

Then I have 4 different class (player, NPC, competition and team), and this is where I am stuck. Should I create references to other classes, so when I instantiate for example a team class; then I will put in it a dataset to represent the NPC classes and the player class?

Or should they not know about each other at all, and all the interaction and logic should go in the gamemanager class?

# Answer
> 1 votes
The relations of your data-model (club *has* players, competition *has* participants...) are part of the model. Trying to represent these connections between entities in the controller will likely lead to a complete duplication of them.

It is often a good idea to try to keep the connection one-sided (either the club has a list of players or the player has a reference to a club).

First, this makes it far easier to enforce the separation of concerns. When a player switches clubs, which class is responsible for making sure the transfer is consistent: `Player` or `Club`? Do you call `player.ChangeClub(club)` which then internally calls `club.AddPlayer(this)` or the other way around? With bi-direction references this can be muddy. But when you only have one-sided references it is clear that the class which holds the reference has full responsibility.

Second, this protects you from creating bugs which cause the references from becoming inconsistent. To avoid the problem of the last paragraph, you could decide that references must only be updated by the controllers. But with bi-directional references it is possible that a bug in a controller causes inconsistent references: Club A says they own Player X, but Player X says they are owned by Club B. Because you have two ways to get player-club relations, that bug might not manifest immediately but only far later in execution. When that happens, you often can not easily find out how that inconsistency was created. Happy debugging!

This being said, enforcing strict one-sidedness of references *can* become difficult and inconvenient in the long-run. Depending on what operations you want to perform on your data-model, there might be cases where either direction is far superior. So sooner or later you might end up creating back-references even when you promised to yourself you won't. When that happens, remind yourself of the separation of concerns principle and which class you decided to be "the boss in the relationship".

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


# Question
Title: Unity3D - Using AddRelativeForce to push an object forever in zero gravity environment
Ok, I use `AddRelativeForce` to basically push an object. But it suppose to keep flying and keep accelerating as I hold down the key because I didn't set gravity. I just started Unity3D last month, so pls give me some advice.

```
// Force of individual thrusters
public float thrusterForce = 10000;
// Whether or not to add force at position which introduces torque
public bool addForceAtPosition = false;

private bool thrusterIsActive = false;
private Transform objectTransform;
private Rigidbody objectParentRigidbody;

void FixedUpdate() {
    if (thrusterIsActive) {
        if (addForceAtPosition) {
            objectParentRigidbody.AddForceAtPosition (objectTransform.up * thrusterForce, objectTransform.position);
        } else {
            objectParentRigidbody.AddRelativeForce (Vector3.forward * thrusterForce);
        }
    }
}

```

# Answer
Then I'd suggest to play with velocity directly. It'd be easy to handle. I writing an untested code for doing the same but with velocity on Space Bar. Give it a try if this would help you.

```
Rigidbody _rb;
Vector3 _velocity = Vector3.zero;
float _speed = 0.1f;

void Start ()
{
    _rb = GetComponent<Rigidbody> ();
}

void Update ()
{
    _rb.velocity = Vector3.Scale (_velocity, transform.forward);
    if (Input.GetKey (KeyCode.Space))
        _velocity += Vector3.one * _speed;
}

```

**Update**

To do the same in your code, you can try the code below. But let me know if you get any problem as it is untested.

```
// Force of individual thrusters
public float thrusterForce = 10000;
// Whether or not to add force at position which introduces torque
public bool addForceAtPosition = false;

private bool thrusterIsActive = false;
private Transform objectTransform;
private Rigidbody objectParentRigidbody;
private Vector3 _velocity = Vector3.zero;

void FixedUpdate() {

    if (thrusterIsActive) {
        if (addForceAtPosition) {
            objectParentRigidbody.AddForceAtPosition (objectTransform.up * thrusterForce, objectTransform.position);
        } else {
            objectParentRigidbody.AddRelativeForce (Vector3.forward * thrusterForce);
        }
        _velocity = objectParentRigidbody.velocity;
    }
    else
        objectParentRigidbody.velocity = _velocity;
}

```
> 0 votes

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


# Question
Title: How to render water reflections on multiple heights
I'm making a voxel game on OpenGL, and are trying to find a way to render semi-realistic water (At least partially good looking, it doesn't need to be strictly scientific accurate).

All sources written about that topic I find seem to assume that all the water in the scene has the same height, which is not the case on a voxel game, where you can have (And see at the same time) multiple bodies of water, with different height each.

The tricky detail lies in the multi-height part of the problem, which makes really difficult to render the scene in real time using typical water reflection algorithms aimed at single level water surface.

As an example, consider the following image:

The dirt pillar at the left should be reflected on the water at its front, as so should be the mountains near the horizon. The water collindant to the pillar is ~20m higher than the general sea water, so traditional reflection methods (Considering a fixed water level) would simply not work in this case. Considering that a lot of different water levels can be seen in a single scene, performing a traditional water reflection method for each water body height is not an option if we want to achieve a acceptable frame rate execution.

How can I overcome this problem? There is any way to render it in real time? If it isn't actually possible to do, what approximation should I take to get a good looking result, even if reflections aren't 100% realistic?

# Answer
There are two possibilities I can come up with that don't involve ordinary planar reflection.

The first is to perform screen-space reflection, which is fairly cheap and works for any manner of surface. However, it will be prone to artifacts, and of course it will not be able to reflect objects that are not visible from the regular point of view.

The other way is to go volumetric. You represent the world using voxels, inject lighting into it, and then use ray/cone tracing to perform reflections. An added benefit is that you then have the infrastructure in place to do more general global illumination. There's details pertinent to this method in the Voxel Cone Tracing paper.
> 4 votes

---
Tags: opengl, rendering, voxels, water, reflection-rendering
---


# Question
Title: How to reregister gamecontroller changedvalue handler upon game scene reload
I'm working on a tvOS game that uses the siri gamepad controller. Everything works fine the first time out. If the user loses the round I reload the same scene using presentScene. After reloading the scene any reference to self.xxxxx don't work in the valuechangehandler closure because the it references the first scene not the new one.

In my didMoveToView there is the usual

```
NSNotificationCenter.defaultCenter().addObserver(self,
        selector: Selector("gameControllerDidConnect:"),
        name: GCControllerDidConnectNotification,
        object: nil)

```

In the gameControllerDidConnect function we have:

```
if let controller = notification.object as? GCController {

        if let mGPad = controller.microGamepad {

            let gamePad = mGPad
            gamePad.allowsRotation = true
            gamePad.reportsAbsoluteDpadValues = true

            gamePad.buttonA.valueChangedHandler = { (buttonA: GCControllerButtonInput, value:Float, pressed:Bool) -> Void in

                    print("buttonA")        // <--- this still works
                self.theBall.alpha = 0.5    // <--- this does not

            }}}

```

Since the observer is added every time the scene is loaded should this not reflect in the self reference to the scene being updated?

Out of sheer desperation I filed a bug report with apple and this is the answer they gave:

When "reloading" the scene, the scene instance is recreated. The old value changed handler for the controller references the ball object in a SKScene instance where it is garbage collected. **You need to re-register value changed handler for the controller whenever the scene is reloaded.**

So if the addObserver doesn't do this every time then how do I do this inside the didMoveToView method? My apologies if this is a really dumb question. I'm migrating from a lua based SDK to spritekit/swift.

# Answer
> 0 votes
Well, I finally found a tutorial here: \[link\]http://cartoonsmart.com/how-to-support-external-game-controllers-with-swift-2-and-sprite-kit-for-the-new-apple-tv/ that addressed how to get around the issue. The trick is to extend the gamescene class and place the listener functions in the extension. These then get called at the start of didMoveToView everytime the scene is loaded.

---
Tags: spritekit, controllers, scene, swift
---


# Question
Title: How to Programm A Dialog box with a typewriter effect in Java?
Im am very new to java and programming so I might be a bit annoying to work with but please bear with me :D So As the title says I'm trying to figure out how to properly program a working dialog box with typing text animation for a game I'm working on. I've seen some posts about swing timers but Im having trouble properly understanding them. If anybody has an idea please share it!

# Answer
> 1 votes
First of all if you don't already know the basics of Java, you should learn them first. :)

When you have, you will need some kind of graphics library.

---

I know that LWJGL is a good graphics library.

LWJGL Link :)

According to some people over at stack overflow, Minecraft was made with this.

---

**But**, as I said it's probably best (if you don't already know this) to learn the basics of Java first.

---
Tags: java, animation, text, effect
---


# Question
Title: In Unity3D, how do I move the camera with the mouse without spinning it on its axis when looking down/up?
I'm currently trying to recreate how Space Engineers work with their first-person acmera in Unity 3D. I'm currently stuck on how to make sure the camera doesn't spin around its axis when looking downwards or upwards, like a sphere. I've looked through several available online snippets for assistance however they all use quaternion to rotate their camera around an axis; this isn't what I want.

Any advice or examples? I'm new to Unity3D by the way so I'd appreciate a basic overview of how it works before the "scientific" language.

This is what currently happens when I look up or down and move left/right:

What I want to happen wherever I look up/down or not at all:

My current code:

```
using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Look")]
public class MouseLook : MonoBehaviour
{

    public float rotationspeed = 6f;

    private float x, y = 0;

    void Update()
    {
        x += Input.GetAxis("Mouse X") * rotationspeed;
        y += -Input.GetAxis("Mouse Y") * rotationspeed;

        transform.eulerAngles = new Vector3(y, x);
    }

}

```

Inspector:

# Answer
The trouble you're encountering can be solved by applying small **relative** rotations to the camera's current transform rather than setting an **absolute** rotation with a Euler angle.

Sadly the Unity API is rather cryptic when it comes to this; I believe this code should work, but the concept is correct either way. When updating the camera take the mouse deltas and apply rotation around the current transform's up and right axes.

```
//Pitch rotates the camera around its local Right axis
transform.Rotate(Vector3.right * Time.deltaTime * Input.GetAxis("Mouse Y") * rotationspeed);

//Yaw rotates the camera around its local Up axis
transform.Rotate(Vector3.up * Time.deltaTime * Input.GetAxis("Mouse X") * rotationspeed);

```

For reference take a look at Unity's transform.Rotate documentation which I believe is what you're looking for.
> 2 votes

# Answer
*EDIT: this answer was addressing the problem as originally formulated by the OP, i.e. "how to make sure the camera doesn't spin around its axis when looking downwards or upwards". For that, the answer was perfectly useful (I suggest fellows to always look at previous versions of edited questions before down-voting answers). That said, now, in the question's current state (i.e. how to implement a 360 degree turn to any direction a mouse-moved-camera looks at), the OP needs precisely what @Vector57's answer provides correctly and elegantly*

---

It is very hard to give a proper answer without seeing anything that you have implemented so far. So, I can only give you a general-case answer, and I do that only because I suspect what you might be talking about is a rotation effect that can be easily solved by clamping the Y axis of the camera rotation.

So, I suppose that you are retrieving the mouse position with something like:

```
    x += Input.GetAxis("Mouse X") * rotationspeed;
    y += -Input.GetAxis("Mouse Y")* rotationspeed;

```

And then you are probably rotating the main camera with something like:

```
Camera.main.rotation = Quaternion.Euler(y,x,0.0f);

```

If that is what you are doing, you just have to clamp `y`before that last step. Clamping y means to force the above variable `y to be greater than a given`lower\_limit and smaller than another given upper\_limit (usually -+85º works fine for me).

Bonus tip: although it is not exactly what you are asking, don't forget also to, first of all, convert the angle degrees in a way that they are always in the 360º scale, i.e. they are always both \>=-360º and \<=360º.
> 0 votes

---
Tags: unity
---


# Question
Title: How do I deal with AABB sweep ghost collisions?
I've been trying to wrap my head around this for some time now.

I wrote an implementation of AABB sweep collision detection. I though I understood the idea but it didn't work as expected. I rewrote it from scratch following the first part of this article but adapting for two moving objects (relative velocity instead of velocity of one of them) and normalized time (divide time by dt to know if collisions happen on this frame) but it still detects collisions wrong.

A similar question was asked on Stack Overflow last year but went without answers.

**¿How wrong?**

This is a stationary state of the simulation. Red rectangles represent hitboxes. What's happening here is that the green cube is "resting on top" of the black pillar to its right after a vertical fall. If the pillar was right under the green block, it would detect it anyway and all would be allright but, as it is, it's giving a false positive.

I believe my last if condition might be responsible for this but still I don't think I'm fully grasping the meaning of AABB sweeping.

```
if (entryTime > exitTime
      || (xEntry < 0.0
      && yEntry < 0.0)
      || xEntry > 1.0
      || yEntry > 1.0) {
  // there's no collision
  return false;
}

```

So... As I understand, I'm checking that:

1. The entry happens before the exit. (this is not supposed to ever happen)
2. xEntry and yEntry haven't both happened yet (time left for them isn't negative)
3. Neither xEntry nor yEntry are going to happen after the frame is over. (?)

That said, here are some proper questions (in descendant priority):

* Is the lack of horizontal velocity the problem? Should I add an explicit check if I know some axis collision is not going to happen, to see if the object is in collision range in that axis or not? This sounds like the way to go but I would like to avoid unnecesary special cases. (It's also very surprising to me that such an obvious problem wouldn't be taken into account).
* Else, how is AABB sweep supposed to detect A is hitting B and not just passing by as it's the case?
* Is the problem caused by any of my two "fixes" (namely, relative velocity and normalized time?)

Here's the relevant code:

```
function aabb_sweep(e1, e2, dt) {
  var p1 = e1.pos;
  var size1 = e1.hitbox;
  var p2 = e2.pos;
  var size2 = e2.hitbox;
  // DEVIATION ONE: RELATIVE VELOCITY
  var rel_vel = e1.vel.add(e2.vel.scale(-1));
  var xInvEntry, xInvExit; // distance between edges
  var yInvEntry, yInvExit;

  if (rel_vel.x() > 0.0) {
    xInvEntry = (p2.x() - size2.x()) - (p1.x() + size1.x());
    xInvExit = (p2.x() + size2.x()) - (p1.x() - size1.x());
  } else {
    xInvEntry = (p2.x() + size2.x()) - (p1.x() - size1.x());
    xInvExit = (p2.x() - size2.x()) - (p1.x() + size1.x());
  };

  if (rel_vel.y() > 0.0) {
    yInvEntry = (p2.y() - size2.y()) - (p1.y() + size1.y());
    yInvExit = (p2.y() + size2.y()) - (p1.y() - size1.y());
  } else {
    yInvEntry = (p2.y() + size2.y()) - (p1.y() - size1.y());
    yInvExit = (p2.y() - size2.y()) - (p1.y() + size1.y());
  };

  var xEntry, xExit; // entry time
  var yEntry, yExit;

  // in case edge distance is 0, to avoid NaN.
  if (rel_vel.x() == 0.0) {
    xEntry = -Infinity;
    xExit = Infinity;
  } else {
    // DEVIATION TWO: NORMALIZED TIME
    xEntry = xInvEntry / rel_vel.x() / dt; // divide by amount of time in the frame
    xExit = xInvExit / rel_vel.x() / dt; // to know if it happens this frame
  };

  if (rel_vel.y() == 0.0) {
    yEntry = -Infinity;
    yExit = Infinity;
  } else {
    yEntry = yInvEntry / rel_vel.y() / dt;
    yExit = yInvExit / rel_vel.y() / dt;
  };

  // erliest collision time
  var entryTime = Math.max(xEntry, yEntry);
  var exitTime = Math.min(xExit, yExit);

  if (entryTime > exitTime ||
    (xEntry < 0.0 &&
      yEntry < 0.0) ||
    xEntry > 1.0 ||
    yEntry > 1.0) {
    // there's no collision
    return false;

  } else {
    // there's a collision
    var normalx = (xEntry < 1.0) && (xEntry >= yEntry) ? 1 : 0;
    if (rel_vel.x() > 0.0) normalx *= -1;
    var normaly = (yEntry < 1.0) && (yEntry >= xEntry) ? 1 : 0;
    if (rel_vel.y() > 0.0) normaly *= -1;
    var normal = V(normalx, normaly);

    var time = entryTime;
    var distance = (xEntry > yEntry) ? xInvEntry : yInvEntry;

    console.log(e1.name + ' collided with ' + e2.name);
    console.log('e1.pos' + String(e1.pos));
    console.log('e2.pos' + String(e2.pos));
    console.log('e1.hitbox' + String(e1.hitbox));
    console.log('e2.hitbox' + String(e2.hitbox));
    console.log('xEntry ' + xEntry);
    console.log('yEntry ' + yEntry);
    console.log('normal ' + normal);
    console.log('time ' + time);
    console.log('distance ' + distance);
    console.log('velocity ' + rel_vel);

    e1.collisions.push({
      against: e2,
      normal: normal,
      time: time,
      distance: distance,
      rel_vel: rel_vel,
    });

    return true;
  };
};

```

Thank you for your attention.

# Answer
> 2 votes
I asked just this question on SO a while ago, same language aswell, and no one didn't really care, so when I found the solution I didn't really bother to put it up there, but now more people are interested and I am glad for that, so now I will post the answer here.

Here's my original code, it's the exact same thing as yours, just a bit more clear of what it's about, since it checks for every axis in a loop (You can even add one more loop and boom, it's 3D if you want):

```
var fTime = 0;
var lTime = 1;
var oTime = new Vec();

for (var i = 0; i < 2; i++) {
    var d = "xy".charAt(i);

    if (vel[d] < 0) {
        if (bMax[d] < aMin[d]) return false;
        if (aMax[d] < bMin[d]) fTime = Math.max((aMax[d] - bMin[d]) / vel[d], fTime);
        if (bMax[d] > aMin[d]) {
            oTime[d] = (aMin[d] - bMax[d]) / vel[d];
            lTime = Math.min(oTime[d], lTime);
        }
    } else if (vel[d] > 0) {
        if (bMin[d] > aMax[d]) return false;
        if (bMax[d] < aMin[d]) fTime = Math.max((aMin[d] - bMax[d]) / vel[d], fTime);
        if (aMax[d] > bMin[d]) {
            oTime[d] = (aMax[d] - bMin[d]) / vel[d];
            lTime = Math.min(oTime[d], lTime);
        }
    }

    if (fTime > lTime) return false;
}

```

So, `vel` is the relative velocity (divided by dt), `a/b Min/Max` is the upper left / lower right bounds of each object, `fTime` is the first (entry) time, and `lTime` is the last (out) time of intersection.

EDIT: The `oTime` (o = overlap) might be a bit confusing for you, you can remove it if you want, but it's really good to have, because after that code, if you have the oTime, you can calculate the hit normal very easy, which is necessary in order for collision response, simply:

```
if (oTime.x > oTime.y) {
    hitNormal = new Vec(signum(v.x), 0);
} else {
    hitNormal = new Vec(0, signum(v.y));
}

```

Where signum is a function that simply looks like this:

```
function signum(x) {
    return x > 0 ? 1 : x < 0 ? -1 : 0;
}

```

Here's also a video of it: https://vid.me/FZwL

These ghost collisions occur when there is no velocity on for example the x axis, but there is velocity on one, the y axis in this case.

They occur because we know that there only is velocity on that axis, and therefore we only check that axis, there is one very easy and very good way to fix this.

This fix will only not fix this problem, but it will also improve the performance. So, what you want to do is this:

Let's say your checking collision between A (blue) and B (red), before you perform the sweep/continouos collision test to get the time of impact, check if they even **can** collide during that frame, to do so, wrap them into these green boxes, which are created by using the `Math.min` and `Math.max` of both A's and B's position (min and max corners) in this frame and in the next frame. If these green boxes intersect, do the sweep test, otherwise, just move on to the next two objects. This will not only fix the problem, but also as I said, improve the perfomance drastically, since you dont need to run unnecessary code.

This took me a while to figure out, but it's rather easy to implement and it works nice and smooth.

That article you found is good, but not really when it comes to collision response, which I think is horrible. I know it is very hard to find information about sweep testing, since only a few even know what it is, but if you get the concept, you can kinda play around with it and find your own solutions. There is almost no information about collision response for sweep testing either, which is kind of annoying, but you can ask me if you want.

Also I am quite curious what kind of project you need this is for, not many use sweep testing in their games/apps but I think people should, because it's much more accurate and smooth imo.

---
Tags: 2d, collision-detection, javascript, aabb
---


# Question
Title: Manual orbit motion jerks at a certain point
So I've been trying to make a simple sphere-orbiting-another-sphere test. The smaller sphere is supposed to circle the bigger one based on the mouse location.

Here is my code:

```
    //script is assigned to the smaller sphere
    screenpos = Camera.main.ScreenToWorldPoint (Input.mousePosition);

    if (screenpos.x <= centerball.x + 2f && screenpos.x >= centerball.x - 2f) //orbit radius is 2
    {
        xpos = screenpos.x;
        ypos = (Mathf.Sqrt(4f-Mathf.Pow((xpos - centerball.x),2)))+centerball.y;
        //generated value of y from an equation
        //equation of circle -> y = sqrt[(r^2)-(x-h)^2]+k

        if(screenpos.y <= centerball.y)
        {
            ypos = -(Mathf.Sqrt(4f-Mathf.Pow((xpos - centerball.x),2)))+ centerball.y;
            //equation of circle when square root has negative sign
        }

    transform.position = new Vector3(xpos ,ypos,0);

```

The code is quite straightforward. Basic math equations and all. And it works all fine except for when xpos gets close to the values of "centerball.x ± 2f ".

It stops moving as I approach the value and then jerks forward, skipping an entire set of values of ypos in between.

So I checked my formula and it is absolutely correct. There is no value of xpos where ypos cannot be obtained (no negative squares).

I did a little thinking and came to the possible conclusion that the value of screenpos was rounded off too much (debug.log showed only 1 decimal place), causing the value of ypos to lose accuracy and jump as the value of xpos approached the previously mentioned bounds. If this is the cause, is there a way to record screenposition more accurately or any other way to get around this problem?

And if this is NOT the cause, can someone please explain what is going on here?

# Answer
I figured this problem out a little while ago. Trick is to just use polar equations for the orbit motion. Does the job perfectly, though I still do not know exactly why the cartesian equation did not work. Anyway, thanks Urist for your response.
> 0 votes

# Answer
A much simpler approach to this would be to use vector math. I'm assuming you're trying to get the closest point to the mouse on the outer sphere. All you really have to do is get the vector from your center point to the mouse point, normalize, and then multiply by the radius of your sphere.

```
screenpos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
Vector3 toMouse = screenpos - centerball;
transform.position = centerball + toMouse.Normalize() * radius;

```
> 1 votes

---
Tags: orbit
---


# Question
Title: Simulation of supersonic, hypersonic flight with user defined surfaces
I want to create a small rocket-launching game, inspired by Kerbal Space Program.

Since there's nothing in orbital mechanics, that I still don't know. I decided to make this as close to reality as possible. The only moment I needed to discover is how to implement aerodynamics.

Well, this became a very problematic, since I discovered the way the fluid is simulated. My first idea was to implement small virtual aerotube, which collects data from solid object and calculates it aerodynamical properties, in dependency of its form. I want to collect this data as a part of build rocket process.

This is hard-but-possible-to-implement part, since there are lot of information of how to make incompressive fluid solvers. But rockets fly at supersonic and hypersonic speeds, so I need to discover how to calculate this forces in apropriate conditions. But, I can see, that implementing incompressive flows is a kind of almost-impossible-to-solve-problem.

So, I decided to ask a very generous question. How did those guys implemented aerodynamics in Kerbal Space Program game? And how usually people modelling it when things are getting little further than "basic understanding".

For me sub-sonic aerodynamics (in games) now seems almost clear. But trans-sonic, supersonic and hypersonic, seems like "Have no idea what to do".

# Answer
> 4 votes
Kerbal certainly didn't go for the realism you're seeking. For a game, it's much easier to just fake it.

While the ships designed in Kerbal are configurable, the parts are predefined in a very detailed way. Just look at what goes into making a part. That's a pretty big hint. All the parts have their drag defined. So, it's really just a matter of summing up the drag of the parts defined, factoring in their orientation, then using that value in your drag equation.

You can do some raycasting from the heading of your craft to see what parts are "visible" to that velocity. Include those parts in your sum of drag, factor in the atmosphere density and speed.

Improving the simulation is to not sum the force of drag and apply to the whole craft, but instead apply it to the individual parts producing the drag and let your connection system figure out how to distribute the forces. Further improvement means adding elements like heat, and shearing forces for damage. Finally you can add features such as lift to your model. This is really just a matter of adding perpendicular forces based on the forces that part is already experiencing. If you want things to get hairy at higher speeds, add some noise to your lift forces to simulate turbulence.

# Answer
> 2 votes
The stock KSP model is known to be quite poor, especially in versions prior to 1.0. In 1.0, they replaced it with a semi-accurate model, where essentially the effectiveness of various parts varied depending on the speed. The best Aerospace model for KSP is a mod known as Ferram Aerospace Research, which has a very detailed description on their page. What they do includes mainly varying the effectiveness of parts depending on the speed. This includes wings, fins, etc. The code is open sourced, feel free to take a look.

---
Tags: physics
---


# Question
Title: Sign APK of several games with same or different key?
When you choose a key for signing your APK for publishing in GooglePlay, you need to care of this key for the next 25 years if you want to do updates.

* The key should not be shared with anyone.
* The key should not be lost.

If you do several games, you face the question of having your key `DeveloperName` and sign all games with it, or have multiple keys like `DeveloperName_GameOne` for one game, `DeveloperName_GameTwo` for another, and so on.

Google says here http://developer.android.com/intl/es/tools/publishing/app-signing.html that if you sign several APPs with the same key, they may talk to each other. So it **seems** that having all with one key will allow future interoperability between games easier.

Instead, if at some point someone wants to buy you one of your games, but not the other, you don't want to give the keys to the non-sold games but still you don't want the buyer to break the update-flow. So it **seems** that having each game with a different key is better.

**Question 1**

What exact benefeits will one have if one signs 2 games with the same key? Is that necessary? Is that worth for future interop between games?

**Question 2**

What is the correct practice for an indie doing several games regarding the signature of them?

# Answer
Signing each game with a different key allows you to sell the rights to the game to another party. When all your games are signed with the same key, you need to give them your one private key, allowing them technically to impersonate you and release updates for your other games. Contractual obligations can be used to prevent that, but it's still not very elegant to share a key that way.

The only reason to use the same key for all apps is if you want to make use of the data sharing feature. If you don't need that, don't use it.
> 2 votes

# Answer
The best thing is to sign with the same key in most instances. You could in theory transfer data from one app to another. It also makes it easier to remember which key you are using. If someone wanted to buy the rights to one game, then yes, you might have an issue. But that same issue would be faced with your account. Bottom line, I'd recommend using the same key everwhere.
> 0 votes

---
Tags: android, google-play
---


title: How to save variables into a file unity

text:
# Question
Title: How to save variables into a file unity
I've wanted to save progress of my game (i don't have the code , sorry) without using *PlayerPrefs*. If it's possible ; with UnityEngine.

# Answer
Let's say you've got a set of variables that stand for your save game entity. You can, for example, create a class within your save manager script like this:

```
[Serializable]
public class GameSave {
    public DateTime lastMod  { get; set; }
    public int games { get; set; }
    public int coins { get; set; }
    public int bestScore { get; set; }
}

```

Don't forget the `[Serializable]` attribute. Then you can write a couple of methods that helps you handle the loading/saving logic, as follow:

```
public void SaveGame(GameSave gameSave) {
    BinaryFormatter bf = new BinaryFormatter();
    FileStream file = File.Create(Application.persistentDataPath + "/save_game.dat");
    bf.Serialize(file, gameSave);
    file.Close();
}

public GameSave LoadGame() {
    if (File.Exists(Application.persistentDataPath + "/save_game.dat")) {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/save_game.dat", FileMode.Open);
        GameSave gameSave = (GameSave) bf.Deserialize(file);
        file.Close();
        return gameSave;
    } else {
        Debug.Log(string.Format("File doesn't exist at path: {0}{1}", Application.persistentDataPath, "/save_game.dat"));
        return null;
    }

}

```

Consider also that in this way your save game data will be easily accessible from malicious users who want to hack your game. A much better approach involves an encryption/decryption logic. You can, as a simple example, save your SaveGame object as a json string and than encrypt+save into a file. Anyway, the only way to implement a robust encryption logic is through a client-server handling of encryption keys.
> 0 votes

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


# Question
Title: can someone help me with this code for my platformer. ive been working on the script for an eternity but unity keeps saying there is an error
```
using UnityEngine;
using System.Collections;

public class player_controler : MonoBehaviour {

    public float moveSpeed;
    public float jumpHeight;

    // Use this for initialization
    void Start () {
    }

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

        if(Input.GetKeyDown) (KeyCode.Space))
        {
            rigidbody2d.velocity = new vector2(0,jumpHeight;)
        }

    }
}

```

This is what shows up:

Assets/scripts/player\_controler.cs(16,53): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement

# Answer
Replace

```
    if(Input.GetKeyDown) (KeyCode.Space))
    {
        rigidbody2d.velocity = new vector2(0,jumpHeight;)
    }

```

with

```
    if(Input.GetKeyDown(KeyCode.Space))
    {
        rigidbody2d.velocity = new vector2(0,jumpHeight);
    }

```

It seems like you are missing some of the most basic concepts of C# syntax. Doing some basic C# tutorials (not necessarily Unity-specific) might help you to get a better feel for how the language is structured.
> 1 votes

# Answer
Is the semicolon after "jumpheight" just a typo, or is that really the problem. More information needed otherwise.
> 0 votes

# Answer
First, @peethor is correct in the comments. Your semi-colon is in the incorrect spot. (Should be at the end of the line. Also, your if statement syntax is incorrect.

Second, you need to get the component of the RigidBody2D before trying to set the velocity. (Make sure that the component exists on the same gameobject that this script is on. If not, you'll have to find the gameobject before getting the component.)

```
    public float moveSpeed;
    public float jumpHeight;
    private RigidBody2D rb;
    // Use this for initialization
    void Start () {
        rb = GetComponent<Rigidbody2D>(); //Store a reference to it since you'll access it every update.
    }

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

        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity = new vector2(0,jumpHeight);
        }
    }

```
> 0 votes

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


# Question
Title: OpenGL ES, orthographic projection and viewport
I want to make some simple 2D game on iOS to familiarize myself with OpenGL ES. I started with Ray Wenderlich’s tutorial (*How To Create A Simple 2D iPhone Game with OpenGL ES 2.0 and GLKit*). That tutorial is quite good, but I miss some parts of a puzzle.

Ray creates an orthographic projection using some magic numbers like 480 and 320. It is not clear to me why he took these numbers, and as far as I can see - sprites are not mapped to the iPad simulator screen one-to-one pixel. I tried to play with parameters with which the ortho matrix is created, but I cannot figure out the maths in here.

How can I calculate numbers (bottom, top, left, right, close, far) which will be parameters to the orthographic projection matrix creation and have the sprite on the screen shown in its original size?

# Answer
> 1 votes
I did a lot of experimentation with this as well. When I first learned OpenGL I also wanted pixel for pixel relationships between the graphics I create in photoshop and my placement of those on the screen. For some games you will want exactly that. I'm not classically trained in OpenGL. Instead I taught myself. So I don't know if it's normal or kosher or whatever. And I guess I don't care.

But because all OpenGL variable have a precision hint, it's actually better not to use the actual pixel values. Instead use math. Also, keep in mind that at least for another year or so we might want to support non-retina devices. So those don't have the same number of pixels. But you don't want your game to have to be coded for multiple screen resolutions. And OpenGL can do a very decent job of resizing your graphics, although it does come at a speed price.

My suggestion is to pick a scale factor for your units. 1 unit = 10 pixels or 1 unit = 100 pixels. In my games, I've chosen 1 unit = 20 retina pixels at a specific depth.

Another tip.. don't do orthographic. Go ahead and do a perspective view. Why? This will give you the opportunity to move things in Z space if/when you want to. You're just going to place your objects at a z depth that has pixel for pixel "unity" (not to be confused with the 3d game engine).

If you do use ortho though you can use this frustum:

```
int frustumScale = 400;

if (retina) {
    frustumScale = 800;
}

matrixFrustum(-(float)backingWidth/frustumScale,(float)backingWidth/frustumScale,
               -(float)backingHeight/frustumScale, (float)backingHeight/frustumScale, 40, 1000, frustProjection);

```

Where frustumScale is 800 for a retina screen and 400 for a non-retina screen. Then at a distance of 800 from camera (-800) the sprite is pixel for pixel the same as photoshop.

Check out this question and my answer here: In 3D camera math, calculate what Z depth is pixel unity for a given FOV

Note.. I don't use glKit. I didn't want to learn an apple specific way of doing OpenGL. Instead I wrote my own math library and engine. But the basics are probably the same in glKit.

# Answer
> 0 votes
In general i don't think you will ever need to fiddle with the values inside a matrix unless you are writing a math library. So for this you should take a function that creates and orthographic projection and works (or take a math library that has everything)

The orthographic projection is like a box has two main components `width` and `height` (your magic numbers i think) and those represent the size of the view frustrum(or box in case of orthographic) in world space. That's why if you have fixed values there the picture will be the same on all screen sizes, but it will be of a different resolution because the content that fits in 480x320 units (inside your world) gets projected on a bigger/smaller surface.

So now to make rendered content size(in pixels) match the screen size you must first know how big is your world and how many pixels you are fitting inside a unit. For this i will take you are rendering one sprite with 1024x1024 pixels over 2 world units. For a device that has the resolution 1024x768 the size of the view projection will be: `(2 / 1024,2 / 768)`

# Answer
> 0 votes
He too those numbers, because of the same reason some people uses 800 * 600 for computers. It is one of the smallest screen size wich can be found on the market. It's just easier to handle, than something like 1600 * 900.

---
Tags: ios, opengl-es2, projection
---


# Question
Title: In Unity, how do I make a mesh change its opacity during runtime?
I'm trying to make a isometric game. I want to make it so that when the player goes behind a wall, the wall's alpha goes down.

How do I go about doing this?

I have this code that I made, but I don't understand what's wrong with it.

I already have the wall that's meant to disappear on the "Wall" layer.

```
using UnityEngine;
using System.Collections;

public class WallAlpha : MonoBehaviour {

    public LayerMask mask =LayerMask.GetMask("Wall");

    void Update() {

        if (Physics.Raycast(transform.position, transform.forward, 100, mask.value))
        {
            transform.GetComponent<Renderer>().material.SetColor("_Color", new Color(1,1,1,0.1f));
            Debug.Log("Something in the way");
        }

        else
        {
            transform.GetComponent<Renderer>().material.SetColor("_Color", new Color(1,1,1,1.0f));
            Debug.Log("Nothing In the Way!");
        }
    }
}

```

# Answer
> 2 votes
Actually Unity create a default material for meshes if you don't assign any material explicitly. And the `Rendering Mode` of that default material is set to `Opaque` that prevents you to play with transparency. Although `_Color` property is declared in Standard Shader. Means your code is right. Well, it's totally another topic. What you can do is to create your own material, set its `Rendering Mode` to `Transparent` and drop it on your mesh.

1- Create a New Material.

2- Set it's `Rendering Mode` to `Transparent`.

3- Drop that material on your mesh.

Now you can play with transparency.

---
Tags: c#, rendering, unity, mesh, alpha
---


# Question
Title: How can I add an IsTrigger propriety from code? Unity
I made an gameobject in my script and i made it a rigidbody, and added it a boxcollider, but I dont know how to tell the program to make it a trigger. Here's my code until now:

```
multi = new GameObject();
                multi.AddComponent<Transform>();
                multi.transform.position = new Vector2(1f, 1f);
                multi.AddComponent<Rigidbody2D>();
                multi.AddComponent<BoxCollider2D>();

```

# Answer
Assign `BoxCollider2D` in a variable then access `isTrigger` property from that.

You can do something like,

```
BoxCollider2D bc = multi.AddComponent<BoxCollider2D>();
bc.isTrigger = true;

```

By the way, there is no need to add `Transform` explicitly as `Transform` is a basic property of any world object to handle transformation (translation, rotation, scaling).
> 1 votes

---
Tags: unity
---


# Question
Title: Technical names for camera styles in 2D games
In 2D gaming, the camera movement method has a lot do with the play style of the game. I'm not super familiar with the technical terms for camera styles, so I'm going to describe them in hopes someone can tell me the name I could google to find out more info. I'm also interested in hearing about any common styles I might have left off.

### Latching camera style

The camera has fixed positions in the world where it cam be located and when a transition is made from one to the next, the whole world pauses while the screen moves. An example of this would be like the camera in the original Zelda game. There are "screens" and as you move from one screen to the next, the camera shifts to it's new fixed position in effect moving you to the next area.

### Balloon camera style

The camera follows your every move. In most games it lags slightly behind the player's movement as if the camera were attached to a balloon being held by the central character. When the player stops moving, the balloon floats up, eventually coming to it's resting point directly above the central character's current location. In some games, it just always stays directly on top, but it's effectively the same mechanic.

---

These are not the technical names (I googled them and nothing comes up, so I'm pretty sure they are not), but can someone tell me what the technical names are? Also, are there any major styles of camera movement in 2D games that I have left off?

# Answer
I think the first one you are describing most closely matches a Fixed 2D camera and the second is a smooth floating or smooth sidescrolling 2D camera
> 1 votes

# Answer
The first scenario is called Panning or sort of Parallex without having Camera Follow. It will totally up to you that how you handle behavior of Camera. That means pausing game, move camera ahead, you can do it manually like other objects.

In second case I think you are asking about Smooth Camera Follow that would follow your character in smooth manner. Well, have a look on these, let me know if you need more assistance.
> 1 votes

---
Tags: 2d, camera
---


# Question
Title: Problems making a smooth character rotation
My character has an angle rotation, when the player touches the screen it automatically face to the place that the player touched, using `atan2(y,x)` and `Math.radiansToDegrees` methods, but I want it to do that smoothly, is to say, save the required angle in a variable, and the current one in another, and depending of the 2 values, make it to rotate to left(if the required angle is to the right side of the current) or to the right. I've been almost an hour thinking about this, but I couldn't solve it.

# Answer
> 1 votes
Have a *currentRotation* and a *desiredRotation* you will also want some helper function to give you the shortest angle distance, so let's just call that angleDist or whatever. (You want that because sometimes going clockwise is shorter or vice versa).

Then all you need is to interpolate between them somehow.

```
currentRotation += expFactor * angleDist(currentRotation, desiredRotation);

```

You can do any interpolation or tweening or whatever that you want there.

As a sidenote, in almost all cases converting away from radians seems like a bad idea.

If your question was specifically about how to figure out which way to rotate.

```
//Assuming both angles are between 0 and 2Pi
double diff = desiredAngle-currentAngle;
//If diff is smaller than 0 we add 2Pi so that it ends up in the 0 to 2Pi range
//You can imagine this as making the current angle zero, but preserving the relative difference
if(diff<0)diff+=2*Math.Pi;
//Now if the angle we want to get to is bigger than half a rotation we go the other way
return diff<=Math.Pi ? diff : diff-2*Math.Pi;

```

Hope this helps.

---
Tags: java, rotation
---