title: Generating Arrow Maze puzzles

text:
# Question
Title: Generating Arrow Maze puzzles
I have picked this puzzle shown here as training in programming games.

> In these mazes you follow the arrows. From each arrow you can move to any of the arrows it's pointing to, in the same row, column, or diagonal.

More explanation can be found here.

As you can see the Arrow on a yellow background in the top-left corner marks the beginning of the maze. Since this arrow is pointing to the right, the player can move from here to either of the two spaces to the right. The player then chooses which arrow to should move to. If they choose the Down arrow in the top-middle, then for their next move they can travel to any of the spaces in the column below it. If they choose the diagonal arrow, then they can move diagonally.

In short, the arrow direction indicates the path direction the player can move. The player continues making these moves until they arrive at the bulls-eye which marks the end of the maze. Here is a solution to this maze:

What I want is to generate a brand new puzzle each time the player starts the game, so they will have to find a different solution path. The player then makes their choices of moves to solve the puzzle. Then they can generate a new puzzle to solve.

Unfortunately, I'm stuck on this step. How can I generate this kind of puzzle? Do I need some path finding methods and which one will help me to achieve this goal?

I'm using the C# language.

Thanks!

# Answer
> 1 votes
Here's a way I'd try:

1. Pick a cell in the maze where you want to start. Add it as the first step in our solution.
2. Pick a random direction for that arrow. For cells on one or more edge of the maze, that direction can't point outside the maze.
3. Pick one cell in the direction of that arrow to be the next step in the solution.
4. Mark all cells in the direction of the starting arrow as "reachable on step 1" - we'll use this to avoid accidentally creating trivial shortcuts.
5. From the next solution cell we chose, pick a new random direction, again being careful not to point outside the maze.
6. Find a cell in that direction that's not yet marked reachable (so we couldn't have gotten there at an earlier step even if we tried) and add it as the next step in our solution, marking all thus-far-unmarked cells in the direction we chose as "reachable on step 2" (or step 3, 4... depending on how many times we've looped) Then continue from 5.
7. If there are no non-reachable cells in that direction, choose a new random direction from those remaining.
8. If no direction lets you continue further, then mark this cell as the destination instead. Now our solution is done.
9. Now, we fill in the remaining cells. Starting with those reachable in step 1, choose directions that don't point to any cell in our solution later than the first. Then we proceed to those reachable in step 2, choosing directions that don't point to any cell in the solution later than the second, and so on. This way we ensure these cells never short-cut the solution.
10. You can fill in any remaining non-reachable cells randomly - they can even all point straight to the goal, it won't matter, since the player can't reach them.
11. If in step 9 you run into a situation where no direction avoids shortcuts, oops, we messed up, try starting over from 1. (I currently don't have a better idea for how to avoid this, but on small maps this should still run fast enough even with this naive guess-and-check approach).

# Answer
> 0 votes
For storage, use N by M array of enums: ARROW\_UP, ARROW\_UP\_LEFT and so on. If field is 3 by 3 with arrow pointing to up-left in the middle, then you'll need an 3 by 3 array, and middle field will have value ARROW\_UP\_LEFT.

Now, regarding the puzzle, let me confirm: player can set an arrow to any direction he wants, or he can only swap fields?

For first option, there is no need for you to check anything, it'll be always possible for a player to find a way. There should be more than one 'correct way' - just shuffle and don't confirm anything.

For second option, You can just randomize all fields and then backtrack from goal to starting position. Also, you can try to implement some kind of maze generation algorithm (https://stackoverflow.com/questions/22305644/how-to-generate-a-maze-with-more-than-one-success-full-path seems to be somewhat related).

---
Tags: c#, algorithm, path-finding, puzzle
---


# Question
Title: 1-bit game - How to change the palette for the entire game at runtime?
So I'm making a 1-bit color game, and would like to have an option in the menu to change what those two colors are so the player can adjust it to their liking. What is the simplest and/or best method to go about this? This would apply to the entire screen, not individual sprites/meshes, as I want to preserve the 1-bit color look.

Most of my assets are sprites, with a few flat meshes that are rendered without anti-aliasing so that they blend in with the sprites. They're all exported with the two standard colors I'm using (a yellow-ish off-white and a dark grey-ish-blue), but I can go back and re-export them in black and white if that is necessary for the suggested method.

My eventual plan is to support the basic black and white, a few monochrome monitor color schemes, and some color combinations that you'd see on 8-bit computers (C64, Apple, etc.).

# Answer
> 3 votes
There are many ways to achieve this.

* Have a list of all materials, all materials have the same **2-color mapping shader** \+ alpha test, update all materials with the same two colors whenever they change.
* Draw everything in black-and-white into a **render texture** then draw the entire texture on screen while mapping black to one color and white to the other color using a 2-color mapping shader & material. You only need to change that single material.
* Use `SpriteRenderer.color` to recolor a white-or-transparent sprites using the vertex color. The camera's clear color is the other color. This only allows you to create 1-color sprites.

---
Tags: unity
---


title: Sniper aim prediction

text:
# Question
Title: Sniper aim prediction
I'm trying to make a sniper aim prediction for an Unreal Engine 4 game. I've found this interesting question Projectile Aim Prediction with Acceleration, and I tried to implement in C++ what DMGregory said. The result I got isn't bad at all, but I've some doubts about something in his explanation. First, what does he mean with `v_T`? Should I calculate it as
`FVector v_T = targetVelocity - myVelocity;`
or as
`FVector v_T = targetVelocity - myPosition;`?
The vectors `myVelocity` and `myPosition` are respectively the velocity and the position of the shooter (me).
Then, I noticed that the sniper projectile trajectory doesn't seem to be a perfect parabola, so I avoided the `v_p` calculation, and I've simply calculated the predicted target position as

```
FVector predictedTargetPosition = targetPosition + targetVelocity * deltaTime + targetAcceleration * deltaTime * deltaTime * .5f;

```

where the 3 vectors `targetPosition`, `targetVelocity` and `targetAcceleration` are relative to the game world axis.
After that, I simply added to the Z component of the predictedTargetPosition the following amount:

```
recalculatedTargetPosition.Z += fabs(bulletAcceleration.Z) * deltaTime * deltaTime * .5f;

```

in order to compensate the loss of height of the projectile in time.

What do you think about it?

Thanks in advance.

# Answer
> 1 votes
First, as noted in the comments, it's not geometrically or physically meaningful to subtract a position from a velocity. So we start by computing the relative velocity like so:

```
relativeTargetVelocity = targetVelocity - myVelocity;

```

Then we can proceed through the steps of the other answer like so...

```
// See linked answer for the full derivation of this math.
timeToImpact = SolveForImpactTime(
                 relativeTargetPosition,
                 relativeTargetVelocity,
                 targetAcceleration,
                 projectileSpeed,
                 projectileAcceleration );

relativeImpactPoint =  relativeTargetPosition
             + relativeTargetVelocity * timeToImpact;
             + targetAcceleration * timeToImpact * timeToImpact * 0.5f;

```

Let's introduce your "recalculated target position" with a slightly tweaked notation:

```
pointAboveImpact = relativeImpactPoint
              - projectileAcceleration * timeToImpact * timeToImpact * 0.5f;

```

If we want to fire the projectile along the line to this point in the shooter's relative coordinates, we can form the projectile's initial velocity by dividing this offset by time. Let's manipulate that a bit...

```
relativeLaunchVelocity = pointAboveImpact / timeToImpact

  = (relativeImpactPoint
    - projectileAcceleration * timeToImpact * timeToImpact * 0.5f) / timeToImpact;
  // Distributing the division through....
  = relativeImpactPoint / timeToImpact - projectileAcceleration * timeToImpact * 0.5f;

```

Which is exactly the formula from the original answer:

```
  v_p = travel / t - (a_p/2.0) * t

```

So you haven't changed the underlying math here, just written the steps differently.

Remember that this launch velocity is still in the shooter's inertial frame, so if the shooter is moving, don't neglect to add the shooter's velocity to get the projectile velocity in the world frame of reference.

If you're finding your predicted velocity is not giving the desired results, you'll need to include explicit error cases so we can diagnose the problem.

---
Tags: c++
---


# Question
Title: Unity MonoBehaviour seems to have another scope
I have a class (EnemyBehaviour) which extends MonoBehaviour, this class has the following two methods:

```
    private Enemy enemy;

    public void set(Enemy enemy)
    {
        this.enemy = enemy;
    }

    public Enemy get()
    {
        return this.enemy;
    }

```

This class also has the unity method:

```
    public void Update()
    {
        Debug.Log(this.enemy);
    }

```

This method always prints Null.

But, If I call the get() method outside the self MonoBehaviour it returns the right instance.

```
    var eb = enemy.getGameObject().GetComponent<EnemyBehaviour>();
    Debug.Log(eb.get()); // it returns UnityEngine.Debug:Log(Object)

```

The Enemy class is a class which encapsulates the EnemyBehaviour.

```
public class Enemy
{
    private GameObject gameObject;
...

```

Then, I don't understand why inside the Update(), Start(), OnMouseDown(), or any "Unity method" the enemy property is Null. But if I access the property outside these methods (enemy.getGameObject().GetComponent().get()) it works.

I suspect that Unity MonoBehavour has it's own scope and the GetComponent() other scope.

Another strange thing is if instead of storing the "Enemy" class inside the Behaviour I store a string or Vector3, it works like a charm.

Any idea? Thanks

Edit:

Simplification of the problem: I have an Empty Game Object (Kernel) which instantiates all the other game objects, this has a Kernel class which extends the MonoBehaviour:

```
    public void Start()
    {
        var enemyGameObject = Resources.Load<GameObject>("Prefab/Enemy");
        var enemyBehaviour = enemyGameObject.transform.GetComponent<EnemyBehaviour>();
        var foo = new Foo();
        enemyBehaviour.Foo = foo;
        Instantiate(enemyGameObject);
        Debug.Log(enemyBehaviour.Foo); // OK, This one works
    }

```

Foo is a dummy class.

```
public class Foo
{
}

```

EnemyBehaviour just does:

```
public class EnemyBehaviour : MonoBehaviour
{
    public Foo Foo;

    public void OnMouseDown()
    {
        Debug.Log(Foo); // When I click on the GameObject, prints Null, it's not working
    }

```

Strange thing: If I replace the var foo = new Foo(); by var foo new Vector3(5,5,5); (Including chaning the type in EnemyBehaviour of course (public Foo Foo; -\> public Vector3 Foo;)) everything works fine :S

Edit 2:

Found the issue, was related with the prefab, I was setting the Foo to the Prefab instead of the instance, Fix:

```
        var instance = Instantiate(enemyGameObject);
        var enemyBehaviour = instance.transform.GetComponent<EnemyBehaviour>();

```

# Answer
The problem was related with the prefab, I was setting the Foo to the Prefab instead of the instance, Fix:

```
    var instance = Instantiate(enemyGameObject);
    var enemyBehaviour = instance.transform.GetComponent<EnemyBehaviour>();

```
> 1 votes

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


# Question
Title: Playing Audio Source in Unity 2d game on destroy
I'm trying to play a sound when an enemy is destroyed. I created a child game object and put this in the `OnEnterCollision2D` function:

```
 private void OnCollisionEnter2D(Collision2D collision)
{
    effect = GetComponent<AudioSource>();
    effect.transform.parent = null;
    effect.Play();
    Destroy(effect.gameObject, 1);
    Destroy(gameObject);
}

```

However, it doesn't seem to fire this event when the bullet enters the enemy character.

# Answer
> 1 votes
It looks like this code expects the audio source to be in two different places:

1. `GetComponent<AudioSource>` says the audio source is on "this" object, the one that just collided with something.
2. `effect.transform.parent = null` and `Destroy(gameObject)` seem to assume the audio source is on a child game object, which can "eject" to safety before the parent object is destroyed.

These two assumptions aren't compatible. Either the source is actually on a child object and the first line returns `null`, or the source is on "this" game object and it goes down with the ship, getting destroyed this frame. Both possibilities lead to no sound being played.

To know how to fix it, we'll need to see a bit more about how your scene is set up.

You can also consider using the static method AudioSource.PlayClipAtPoint() to fire a "posthumous" sound without manually managing another game object.

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


# Question
Title: How do I render light propagation volume without aliasing?
I have two major problems in my LPV implementation:

1. The "blockyness" of my LPV light rendering (yes am using trilinear interpolation when sampling for the coefficients)
2. The flickering that happens as I rotate the camera (see this question )

Is see on the internet people do manage to get very smooth lighting and almost zero flickering across a surface, don't see how that's possible given how coarse the LPV (32x32x32 in my case) is..

Here is one with trilinear sampling, you can see it aliasing, specially in the slanted wall in the background:

Here is one with GL\_NEAREST, this I use to tell me which pixels are falling on which LPV boxes. The coarseness of the LPV is obvious, I can't comprehend how you reconstruct smooth lighting from this.

# Answer
I've done lots of research on this problem and I think I've found some hints as to why things look so blocky. This is text straight from **"Octree-Based Sparse Voxelization using the GPU and Hardware Rasterizer"**:

> Once voxel-fragments have been generated in the fragment shader, their values can be written directly into the destination 3D texture using image load/store operations. However, multiple voxel fragments from different triangles can fall into the same destination voxel in arbitrary order. Since voxel fragments are created and processed in parallel, the order in which they will be written is not predictable, which leads to write-ordering issues and can create flickering and non–time-coherent results when dynamically revoxelizing a scene. In standard rasterization, this problem is handled by the ROP units, which ensure that fragments are composed in the framebuffer in the same order as their source primitives have been issued.

I'm using deferred shading in my program, which means that multiple fragments from the G-Buffer can contribute to one voxel, as I rotate the camera I get flickering because it all depends on which fragment gets selected to contribute to the voxel, that's pretty much random. The paper goes on to discuss solutions to this problem which rely on OpenGL 4.2 and above, Apple only supports up to OpenGL 4.1.

In hindsight, othographic projection could help here, as long as I adjust the glViewport in such a way that the LPV fits tightly in the rendered scene, that way every pixel matches exactly to a texel in the LPV.

The blockyness issue has to do more with under-sampling the scene and I don't know if there is a solution that fixes it perfectly. (search for Nyquist Theorem from signal processing)

If you look at the demos from people who have implemented this, you see lots of straight line walls lit by sunlight (orthographic proj. is perfect for this because is a directional light) which I bet are aligned to the LPV. In my demo scene, I happen to choose the worst case scenario inadvertently. Look at the plane in the screenshots I posted, it looks very smooth, this is because is aligned with the LPV, this is in contrast to the slanted wall in the background.

One last thing: in order to avoid cracks when you render the LPV in meshes where the incident angle of the camera to the normal of the mesh/triangle is large, it is a good idea to consider Conservative Rasterization.
> 0 votes

---
Tags: global-illumination, volumetric-light
---


# Question
Title: Get type of the object where attribute was declared - Hide In Derived Inspector Attribute
I want to implement a custom Unity inspector attribute, like usual ones `[HideInInspector]` or `[Range(0, 100f)]`.

This attribute should hide a field from the inspector if it's inherited from a base type, rather being defined directly in the type of the object we're inspecting.

So, for example, if I have these classes...

```
public class Enemy : MonoBehaviour {
    [SuperField]
    public int EnemyHealth;
}

public class GiantMonster : Enemy {
    [SuperField]
    public int Armor;
}

```

then the inspector for a base `Enemy` should show a control for the `EnemyHealth` variable, but when inspecting a `GiantMonster` we should not see a control for this variable.

So far I have my attribute:

```
public class SuperFieldAttribute : PropertyAttribute {}

```

which has its own `PropertyDrawer`:

```
[CustomPropertyDrawer(typeof(SuperFieldAttribute))]
public class SuperFieldDrawer : PropertyDrawer {

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
        // ...
    }
}

```

Inside `OnGUI` I need to access/find the type where the field we're drawing was declared with the `[SuperFieldAttribute]`.

So if `SuperFieldDrawer.OnGUI()` is called for the `SerializedProperty` corresponding to `GiantMonster.EnemyHealth`, I should be able to determine that the type where `EnemyHealth` was declared is `Enemy` and not `GiantMonster`. (I'll use this to hide the field so it's not drawn)

And if `SuperFieldDrawer.OnGUI()` is called for the `SerializedProperty` corresponding to `GiantMonster.Armor`, I should be able to determine that the type where `Armor` was declared is `GiantMonster` itself. (Meaning I should proceed and draw the field)

So far I've found ways to access the type of the component we're inspecting, but not the type where the field was first declared, so that's the missing piece I need to fill in.

It's OK if I use reflection and so on; any method is good, performance isn't a concern.

# Answer
> 2 votes
As luck would have it, the `PropertyDrawer`'s `fieldInfo` has a handy `DeclaringType` property that tells us exactly where the field was defined, without needing to walk the inheritance hierarchy ourselves - at least for fields directly on the object we're inspecting. As we discovered in the comments, we still need to do a bit of manual walking for fields in a child object or struct.

Here's how we can implement that `[HideInDerived]` attribute drawer using this:

```
using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(HideInDerivedAttribute))]
public class HideInDerivedDrawer : PropertyDrawer {

    bool? _chachedIsDerived;
    // Cache this so we don't have to muck with strings
    // or walk the type hierarchy on every repaint.
    bool IsDerived(SerializedProperty property) {
        if (_chachedIsDerived.HasValue == false) {

            string path = property.propertyPath;
            var type = property.serializedObject.targetObject.GetType();

            if (path.IndexOf('.') > 0) {
                // Field is in a nested type. Dig down to get that type.
                var fieldNames = path.Split('.');
                for(int i = 0; i < fieldNames.Length - 1; i++) {
                    var info = type.GetField(fieldNames[i]);
                    if (info == null)
                        break;
                    type = info.FieldType;
                }
            }

            _chachedIsDerived = fieldInfo.DeclaringType != type;
        }
        return _chachedIsDerived.Value;
    }

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
        // If we're in a more derived type than where this field was declared,
        // abort and draw nothing instead.
        if (IsDerived(property))
            return;

        EditorGUI.PropertyField(position, property, label, true);
    }

    public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {

        if (IsDerived(property)) {
            // Collapse the unseen derived property.
            return -EditorGUIUtility.standardVerticalSpacing;
        } else {
            // Provision the normal vertical spacing for this control.
            return EditorGUI.GetPropertyHeight(property, label, true);
        }
    }
}

```

## Known issues

* **This does not stack with other property drawing attributes** like `[Range(min, max]`. Only one attribute will take effect, depending on their order. Internally it seems Unity tracks only one inspector attribute per field.

It may be possible with some heavy-duty reflection to identify other attributes on the field with their own CustomPropertyDrawers, and construct a corresponding PropertyDrawer to delegate the drawing to, but it would get messy fast. It might be simpler to make a combined attribute like `[HideInDerivedRange(min, max)]` for specific cases.
* **Types with their own custom property drawer will fall back to the default drawing style** if marked `[HideInDerived]`. It works correctly for all of Unity's built-in property widgets though, showing colour pickers and vector/object fields as expected.
* **This does not correctly hide the label, fold-out, and size controls of an Array or List**, although it does hide the collection's contents.

As Candid Moon found, this is due to a change in Unity 4.3 to allow Attribute-targeted PropertyDrawers to apply to each element in a collection, which unfortunately makes it impossible to target the array itself in the present version.

A workaround suggested by slippdouglas here is to define a serializable struct containing your collection, so that the `[HideInDerived]` attribute hides the struct as a whole, like so:

.

```
[System.Serializable]
public struct HideableStringList {
     public List<string> list;

     // Optional, for convenience, so the rest of your code can
     // continue to behave like this is just a List<string>
     // without always referencing the .list field.
     public static implicit operator List<string>(HideableStringList c) {
         return c.list;
     }
     public static implicit operator HideableStringList(List<string> l) {
         return new HideableStringList(){ list = l };
     }
 }

```

Because of the way Unity draws the inspector, we can't use a single generic type to handle all these cases, so you'll have to copy this boilerplate for each array type (yuck). But at least it lets this work:

```
[HideInDerived]
HideableStringList myStrings = new List<string>(3);

```

---
Tags: unity, gui
---


# Question
Title: Should I draw a button using a single shape (triangle list) and draw call, or multiple shapes and draw calls (triangle strip and line lists)?
I know this is too simple for performance improvements to make much of a difference, but I find that knowing this information would be simple for many future scenarios. Basically, what I am trying to draw is a rectangle with text over it. I don't know whether it would be better to draw the entire thing using triangles, or use two draw calls (one using GL\_TRIANGLE\_STRIP for the rectangle, and the other using GL\_LINES for the text). My worry is that the cost of the draw call outweighs the cost of reducing the number of vertices used.

# Answer
> 2 votes
No two GPUs render `GL_LINES` the same way. You can be missing pixels at some of the corners on one GPU/driver, missing different pixels on another GPU/driver. Have it rendered thicker or thinner on different GPU/drivers. And more potential problems.

The look of the lines will also dramatically change according to the rendering resolution and anti-aliasing settings.

So you shouldn't use `GL_LINES` unless it's for displaying debugging information only during development. Never for a released product.

Here's an example of the inconsistencies with `GL_LINES`. Used here as a way to display the bounding boxes and mouse click events for **debugging** purposes during development.

Top is without anti-aliasing. Bottom is with MSAA 16x enabled.

---

The current methods commonly used to display text are:

* Put the text glyphs (characters) and possibly the background inside of 1 large texture called a texture atlas and render the text box in one `GL_TRIANGLES` draw call.
* "Bake" the text window with either the CPU or GPU into a texture and display that texture as a quad.

The first method saves on texture memory bandwidth and has better performance.

The second method is usually used when you want to do complex animated fades in and out of your entire text box in fancy ways (eg: make it look like it catches on fire and burns away).

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


# Question
Title: Best practice for 4x game management in Unity?
I'm trying my hand at creating a turn-based 4x game in Unity, with a galaxy map and 2D hexagon grid maps for each individual planet. The planet grid hexes would be gameobjects, with the overall grid being around 30x40 in size. The number of planets would be under 50.

What would be the best way to set this up? I'm looking for a solid approach regarding performance here, but one that also caters to easier design/programming would be a plus.

Some approaches I've come up with:

1. Load all of the grids for the individual planets at the start into a single scene, with each being under a "planet gameobject", and then set those gameobjects to inactive. The galaxy map would be its own scene that is loaded additively when needed; clicking on a planet to view it would set its associated gameobject to active and then unload the galaxy map scene.
2. Instantiate the gameobjects for planets as they're called up; the grid data for the planet is dynamically loaded as part of this. The planet gameobject is destroyed when no longer needed. Galaxy map would function the same as approach 1.
3. Individual scenes for each planet, loaded/unloaded additively when needed. A separate, single scene would be used for loading procedurally generated planets.
    1. Seems to have serious challenges for managing units/resources across planets/scenes.

Approach 1 seems to be the most straightforward, as the core of the game would be managed in a single scene, but I am concerned about performance. I'm setting up some test projects to stress test the approaches, but it'd be great to get feedback from someone with more experience.

Any help is appreciated!

# Answer
What are your minimum requirements?

Approach one could require a lot of memory if each planet has to keep its variables in stored there, but would have almost no loading times.
The other two approaches could slow down your game while instantiating or loading the scene for the planet, but would only hold one planet in memory at a time.

In the end it's trade-off between memory and harddrive speed, and the only way to know what works for your game is to test it for yourself.
> 0 votes

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


# Question
Title: How do I use Unity's OnPlayerConnected method?
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnPlayerConnected.html

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

public class SendData : MonoBehaviour {

    void OnPlayerConnected (NetworkPlayer player) {
        Debug.Log ("A player connected!");
    }

}

```

This code, surprisingly, doesn't work!

Expected: The server prints "A player connected!" in the Unity editor debug console.

What happens: Nothing is printed. It doesn't matter if I use print() or Debug.Log().

This script is applied to a standard object in the scene. It has a NetworkIdentity.

I really don't know what else to try. The Unity documentation is very short and gives an example very similar to this. My code should be even simpler than Unity's example but it doesn't work.

# Answer
`OnPlayerConnected()` and `OnPlayerDisconnected()` are part of the old networking API and not UNET what is currently being used. In order to achieve what you want you have to exted the Network Manager. Something like this will get you on the right track :

```
using UnityEngine.Networking;
using UnityEngine;

public class Send_data : NetworkManager
{

   public override void OnServerConnect(NetworkConnection Conn)
   {
     if (Conn.hostId >= 0)
     {
        Debug.Log("New Player has joined");
     }
    }
}

```
> 1 votes

---
Tags: unity, c#, networking, unity-networking, unet
---


title: Stacking cubes on top of each other

text:
# Question
Title: Stacking cubes on top of each other
How can I stack cubes on top of each other? I dont want to know the code of it just how can it be done? Imaging putting cubes on top of each other in a 3d world with the cube being freely moved in all directions (like click on the cube and you can move it) I dont see how you can "raise" the cube to put it on top. Any suggestions is appreciated!

# Answer
This is fairly simple to do. From what I gathered you want to have preexisting cubes in your game and when the player clicks/taps/holds on them they move. To make this a reality, unfortunately, you are going to have to write code and understand how colliders work.

1) Raycast a ray from the camera towards user input(finger, mouse pointer) on a distance mathf.infinite

2) If that raycast returns true, user clicked/hold his finger on a cube(I would suggest using layers here to differentiate your cubes from the rest of the objects in your scene) and you can create a fucntion that would look something like this

```
ClickedGameObject.transform.position += Input.mousePosition

```

PS. you get ClickedGameObject from raycast out in the raycast function parameters.
> 1 votes

---
Tags: unity
---


# Question
Title: How to become a Ph.D. in video game design?
The title says it all, I am wondering if it is possible and if so, how it would be possible, to become a Ph.D. in video game design. I'm quite sure you can become a Ph.D. in pretty much anything, but since video games are such an informal and relatively young sector, I thought I'd ask.

Thanks in advance!

# Answer
Obtaining a PhD in *game design* itself is likely impossible. Game design is an art rather than a science. PhD studies are conducted on scientific topics, with the goal of answering scientific questions, as to advance a field of technology.

It is however definitely possible to do PhD research on topics related to game design. Modern games draw from a lot of scientific fields, often sub-topics of computer sciences or information and communication technology. Some fields that are highly relevant in games include:

**Computer graphics** — The science generating a realistic rendering of virtual scenes on a display device. Important topics include: 2D rendering, 3D rendering, procedural generation, data visualization, lighting and shadows, materials, anti-aliasing, post-processing, virtual reality, augmented reality ...

**Artificial Intelligence** — The science of creating virtual agents that exhibit intelligent behavior. Important topics include: path finding, decision making, machine learning, computer vision, searching, probability theory ...

**Physics** — The science of studying physical phenomena, such as the behavior of matter reacting to various forces. Important topics include: rigid body dynamics, soft body dynamics, fluid dynamics, ballistics ...

**Software Engineering** — The science of studying software architectures, patterns, and best practices. Important topics include: game engine design, memory management, GPU programming, specialized data structures (octrees, scene graphs ...), specialized algorithms ...

**Signal processing** — The science of how signals can be modified through specific systems. Important topics include: frequency analysis, sound modelling, geometry processing and compression ...

**Psychology & Communication Sciences** — The science of studying social behavior, and how it is influences by various media. Important topics include: serious games (i.e. educational games), multimedia ...

I personally did PhD research on procedural generation, and got in touch with researchers of all the above topics. All of them had performed studies on the topic of games, in both smaller and greater degrees.

So in summary, pursuing a PhD in game itself is likely impossible as it is an art rather than a science. Game design is a very complex task however, and it draws from a plethora of scientific fields. It is very possible to perform research in one of those fields, and choose a topic relevant to games. As others have said though, a PhD is not per se a guarantee to be a good game designer.
> 1 votes

---
Tags: game-design
---


title: Calculating theoretical FPS

text:
# Question
Title: Calculating theoretical FPS
*I'm unsure if this question would be more appropriate in stackoverflow, so apologies before hand if it should be moved.*

Given that I know the user's hardware (Video Card, RAM, CPU, screen resolution, etc.) is it possible to make a rough estimate of the expected FPS when comparing with the game's minimum and recommended system requirements?

I see some gaming websites with those estimates and I was wondering how do they do it.

# Answer
> 1 votes
As *ratchet freak* said, the estimates are based on running the game on a set of different hardware configurations. Often, they will load a set of different game configurations on those computer systems as well. That way they can gather information such as "Game ABC runs at **72.4 fps** on a system with **CPU XXX**, **GPU YYY**, with **ZZZ GB of RAM**, on **Ultra High settings**."

Not all pieces of a **hardware configuration** contribute equally to the framerate of a game. Often, the GPU is the most important factor, followed by the CPU, the amount of RAM, and whether an SSD is used or a standard HDD.

In terms of **game configurations**, two important factors are graphical fidelity (i.e. low quality graphics all the way to ultra high quality graphics) and display resolution (i.e. how many screens are you rendering to, and what resolution do they run at).

By obtaining a set of benchmarks on various systems, and in various game configurations, you can often extrapolate your data to different hardware configurations to make an estimation of the framerate on unmeasured systems. You could simply use the benchmark that is the most similar to the user's configuration (looking at the most important hardware components), or you could calculate a weighted average across multiple benchmarks based on similarity.

---
Tags: hardware, requirements
---


# Question
Title: WinAPi OpenGL Borderless Fullscreen - Alt Tab problems
I'm implementing a borderless fullscreen functionality and managed to make something that almost works. Using: C++, Winapi, OpenGL 3.3.

When in fullscreen borderless mode, if alt tab the game window loses focus but is still on top, not even the alt tab window shows.

I managed to track it down to SwapBuffers. If i disable it, no problems but also no rendering.

If i force the window to hide when it loses focus, the entire screen flickers. And if i alt tab back, only the game window flickers.

If i put the game in windowed mode, it works as normal.

Window Styles are first set to(windowed mode stops here):

```
WS_OVERLAPPED | WS_MINIMIZEBOX | WS_SYSMENU | WS_VISIBLE

```

And then are set to(if fullscreen):

```
GetWindowLong(window, GWL_STYLE) & ~WS_OVERLAPPEDWINDOW

```

My gameloop:

```
while(isRunning)
{
    loopNewTime = timeGetTime();
    loopDuration = (r32)(loopNewTime - loopOldTime);
    loopTime = Clamp(0.0f, (loopDuration - sleepTime), 250.0f);

    loopOldTime = loopNewTime;
    loopAccumulator += loopTime + sleepTime;

    while(loopAccumulator >= loopFixedDeltaTime)
    {
        if(isFocused || canRunWithoutFocus)
        {
            DoStuff();
        }

        loopAccumulator -= loopFixedDeltaTime;
    }

    if(isFocused || canRunWithoutFocus)
    {
        DoStuff();

        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

        DrawStuff();

        SwapBuffers(deviceContext);
    }

    framerateTimeThreshhold += loopTime + sleepTime;
    ++framerateCount;

    if(framerateTimeThreshhold >= 1)
    {
        framerate = framerateCount;
        framerateCount = 0;
        --framerateTimeThreshhold;
    }

    sleepTime = Max(timeStep - loopTime, 0.0f);

    Sleep((u32)sleepTime);
}

```

So, how can i solve this problem?

Thanks in advance.

# Answer
To anyone with this problem, i found a 99% perfect answer here: https://stackoverflow.com/questions/23145217/flickering-when-borderless-window-and-desktop-dimensions-are-the-same

What i did: Set the window size to the size of the screen + 1. For some reason if the window and the screen are the same size Windows will act like it's a "normal" fullscreen.
> 0 votes

---
Tags: opengl, c++, winapi
---


# Question
Title: Toggle Button click doesn't count when the Mouse Up happens outside of the button area
I have a problem with my toggle buttons. When a user performs the Mouse Up of the toggle button outside the button area, the click is not counted.

Mouse Down and Mouse Up on the button area works. Mouse Down on the button and Mouse Up outside, does not work..

Just to avoid confusion, the Mouse Down is when you click, the Mouse Up is when you lift the finger from the mouse button.

Do you have any idea how to solve this?

I'm using Unity. Thanks for your help!

# Answer
I guess you could record the mouse down event on the button and then instead of waiting for mouse up on that button, waiting for `Input.MouseUp` before triggering the event.
> 1 votes

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


# Question
Title: How would a server handle sending entity updates to clients?
Lately I've been looking into networking and sockets and made small test programs to get the basics down. So far I've made a TCP turn-based game from where I learnt a lot and helped me getting some fundamentals down.

Recently I also got a basic game working where multiple clients can connect and see each other move, but I feel like the architecture is not the best though. This made me want to expand the game a little and build a more solid foundation but I've been struggling to find the answers on a few questions I have.

The approach I've had for 2D action games(which is my goal to make) is to have a dedicated server, a separate project written purely in java(I use LibGDX for clients) and in the server project I have a `Client` class which has a `x`, `y`, and an `id`. Then when a client connects to the server it creates a new `Client` object, gives it an ID based on the amount of clients connected and puts it in an `ArrayList` called `players`.

Then for movement I have the Game client send a message when it moves, structured like `id,x,y;`. The servers `Client` object receives the message and tells the server to `broadcast()` it to all the other clients which in turn receives a position message. The Game clients get a message, structured as above, and the Game client updates his own `playerList`.

This feels really clumsy and not well structured at all and this leads to my next question, what data should the server have?

Let's say we have a 2-player game where the players cooperate to kill mobs and receive items and exp. How would the server keep track of the mob entities? Would i create an identical `Entity` class from the Game Client and put in the Server project with everything but the `render` / graphical stuff? And collision with projectiles and stuff, do I collision check in the Game Client and then validate in the server?

All this feels very overwhelming and I would love if someone could give me some advice or point me to any forum posts they've read. I've searched around the forum but haven't managed to find anything that really answers this structuring part.

Thanks in advance, feel free to ask me anything!

# Answer
> 1 votes
First of all, you're using Java and LibGDX, so you have access to UDP. UDP is better in a lot of aspects than TCP if you make anything but a strategy or puzzle game (as a rule of thumb, UDP is better if missing a couple packets doesn't matter that much, but speed is crucial).

It's perfectly normal to have a single project with two entry points for a server and a client. This way you don't have to write everything twice. The only difference is the main game loop (the server doesn't render, just update) and the update method (the client should receive the updates to the entities and send inputs, the server should send updates to the entities and receive inputs)

---
Tags: java, libgdx, networking, socket, entity
---


title: Creating a scrollable area

text:
# Question
Title: Creating a scrollable area
I am trying to create a ListBox where each ListItem is just some text. I can make it so if a ListItem goes off the ListBox's height then don't show it. This is just a simple if statement in my render function checking to see if the ListItem's position is inside the ListBox's rectangle.

I want to improve this by making the ListBox scrollable. So similar to the picture below, I should be able to partially see the ListItem if I start scrolling down until it's fully in view.

How would I go about doing this? I'm thinking I would need some Camera and only render things inside the Camera's rectangle. Though, I do not know how to begin this.

My current code just doesn't render the ListItem if it goes off the ListBox's rectangle:

```
class ListBox {
  private:
    std::vector<ListItem*> list_items;

  public:
    ListBox();
    ~ListBox();

    void update();
    void render();
}

void ListBox::render() {
  // Loop through list items here
  if(item->rectangle.h + item->rectangle.y <= this->rectangle.h + this->rectangle.y) {
   item->render();
  }
}

```

Without the if statement, it looks like this:

I want "Test: 8" and "Test: 9" to be hidden inside the white rectangle until I scroll down.

# Answer
You need two checks, a scroll variable to move the items and enable clipping:

```
// set clipper
SDL_RenderSetClipRect(renderer, &this->rectangle);

//loop through items
for(auto item : list_items){
    if(
        ((item->rectangle.y - scroll.y) < (this->rectangle.y + this->rectangle.h))
     && ((item->rectangle.y + item->rectangle.h - scroll.y) > this->rectangle.y)
    ){
        item->render(-scroll);
    }
}

// disable clipper
SDL_RenderSetClipRect(renderer, NULL);

```

For 2D scrolling:

```
if(
    ((item->rectangle.y - scroll.y) < (this->rectangle.y + this->rectangle.h))
 && ((item->rectangle.y + item->rectangle.h - scroll.y) > this->rectangle.y)
 && ((item->rectangle.x - scroll.x) < (this->rectangle.x + this->rectangle.w))
 && ((item->rectangle.x + item->rectangle.w - scroll.x) > this->rectangle.x)
){
    item->render(-scroll);
}

```

Where the items render themselves using the offset parameter passed to the `render()` function.

By having the scroll value "backward" (negative) you can scroll to an item with

```
scroll.y = item->rectangle.y;
scroll.x = item->rectangle.x;

```

and is consistent with the way scroll bars are usually constructed. You may need to invert this depending on how your coordinate system and scroll bars work.

The items will need to calculate a **temporary** SDL\_Rect by adding the (x,y) offset passed to their render function to their rectangle.

```
SDL_Rect newrect;
newrect = rectangle;
newrect.x += offset.x; // offset passed as parameter
newrect.y += offset.y; // offset passed as parameter
SDL_RenderCopy(renderer, texture, NULL, &newrect);

```
> 2 votes

---
Tags: c++, sdl
---


# Question
Title: Make a trigger work for only a certain type of object
Is there a way you can make a trigger only exist to a certain type of objects while excluding other ones. I don't think the code will help but I just put anyway.

```
public class Girl : MonoBehaviour {

    public Attacker attacker;
    public Animator anim;
    public float girlHealth;
    public GameObject obj;

    // Use this for initialization
    void Start()
    {
        attacker = GetComponent<Attacker>();
        anim = GetComponent<Animator>();

    }

    // Update is called once per frame
    void Update () {
        if (!obj)
        {
            anim.SetBool("isattacking", false);
        }
    }
   void OnTriggerEnter2D(Collider2D collision)
    {
        obj = collision.gameObject;

        if (obj.tag == "Axe") {
            anim.SetBool("isattacking", false);
            anim.SetTrigger("ifAx");
        }

        if (obj.tag == "Stone") {
            anim.SetBool("isattacking", true);
        }
        if (obj.tag == "ActiveDefender")
        {
            anim.SetBool("isattacking", true);
        }

    }

}

```

I figured out a way to do it

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Attacker))]
public class Girl : MonoBehaviour {

    public Attacker attacker;
    public Animator anim;
    public float girlHealth;
    public GameObject obj;
    // Use this for initialization
    void Start()
    {
        attacker = GetComponent<Attacker>();
        anim = GetComponent<Animator>();

    }

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

        if (!obj)
        {
            anim.SetBool("isattacking", false);
        }

    }
   void OnTriggerEnter2D(Collider2D collision)
    {

       if(collision.gameObject.tag == "Stone")
        {
            obj = collision.gameObject;
        }
       else if (collision.gameObject.tag == "ActiveDefender")
        {
            obj = collision.gameObject;
        }

         if (obj.tag == "Stone") {
            anim.SetBool("isattacking", true);
        }
         else if (obj.tag == "ActiveDefender")
        {
            anim.SetBool("isattacking", true);
        }
        Debug.Log(collision.gameObject);

    }
    void OnTriggerExit2D(Collider2D collision)
    {

    }

}

```

# Answer
> 1 votes
You need to change the layer of the objects that you want to trigger with each other so that they are not on the default layer anymore (like all the other objects of your scene I assume). If you decide to create 2 different layers for instance if your interactions are a bit more complex), you will have to make those layers collide in the Collision matrix as well (under Edit \> Project Settings \> Physics 2D). Here is what you can find on Unity: Physics Best Practices

Depending on the type/characteristics of the objects that you want to trigger, you may want to check the following link on Unity website Colliders in particular the section entitled

> Collision action matrix

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


# Question
Title: Unity multiplayer (online) - How to connect to a 'Client-Host' without using Unity Paid Service
I'm slightly annoyed with the official Unity guides here, because I have been following through some, and they have indeed helped me create a local network mulitplayer situation. However, at no point did they mention that using these methods (ie. UnityEngine.Networking // NetworkManager // NetworkManagerHUD // NetworkIdentity) will require me to pay Unity for Pro, and a monthly server usage fee, if I wanted to play via internet.

I've set up my own Rust server in the past and it was very simple. I just installed a Rust Dedicated Server on my desktop PC (which I have fibre internet connection) and ran the server. I could then have 20 people playing with me and we didn't notice any slow-down or lag or any problems with it. (Rust is made in Unity I believe)

I've tried searching lots on this matter, and there are many many differing voices of how I can do this (many out-of-date, and many explicitly stating its impossible without hiring a server) - I disagree, and think I can make my desktop run the server, BUT I haven't a clue if I'm correct and also how I would be able to make it.

Unity docs seem to be trying to hide this solution if it exists (perhaps I'm being paranoid).

I have the NetworkManagerHUD all working and can play locally as I say.

So, it appears that the NetworkManager allows a user to start my game in 'Client-host' mode, it also allows another instance elsewhere to click "Connect Client" and has a space for IP address.

Would I even need a dedicated server if a player has clicked to start as 'Client-Host'? assuming I don't, how can I then connect to this host from another machine? Does typing the client-hosts external IP allow this?

Sadly, I don't have anybody to help me test this right now.

If a dedicated server version is the preferable way to go, could anybody please help me in the direction of how to start creating this?

For info: The game at this stage is a very simple FPS shooter. The NetworkManager is assigning the 'isLocalPlayer' flag correctly to one instance of the player object. I see in the Editor Hierarchy that it is handling the game overall and has two player objects once I have logged in with two instances locally.

# Answer
> 1 votes
You do not need to have a paid version of unity for this.

In my multiplayergame I used a client-host-system in a simple multiplayer shooter some time ago. In Unity in the tab "Services" you can implement multiplayer, then it is easier to connect to other players game without typing the IP.

You need to create a Unity Project Id, but that costs no money. I also used a lobby manager asset here it is made by Unity staff. This tutorials may help you (I think they still work in 2017-version): this one and this one. Both tutorials are well done and helped me a lot.

---
Tags: unity, networking, multiplayer, unity-networking
---


title: UE4 Image Asset From String

text:
# Question
Title: UE4 Image Asset From String
I have a custom widget with an image component. I want to change the image dynamically based on a string from a data table. How do I do this?

# Answer
> 1 votes
**C++**
You can use the `LoadObject` function to find and load and object at runtime. Full documentation is available from Epic Games here. For loading an image the following should work:

```
GridTexture = LoadObject<UTexture2D>(NULL, TEXT("/Engine/EngineMaterials/DefaultWhiteGrid.DefaultWhiteGrid"), NULL, LOAD_None, NULL);

```

**Blueprint**
As of yet there is no native implementation, but it is included in Rama's Victory Plugin.

Select the class you want to want to load and give it the reference path of your asset. The loaded asset will be an `Object` so you will have to cast it to `Texture2D`. Then you can store it as a variable or directly set the image of your widget.
Below is an example of using this with a DataTable with some assets.

To get a usable reference, simply right click an asset and select *Copy Reference*.

---
Tags: unreal-4, image, asset-management
---


# Question
Title: How to make non-static gameobjects brighter?
I placed non-static gameobject in the scene. Look at this picture:

You can see the lighter, but it's too dark, way darker than others. The only difference between the lighter and the other objects are the fact that other objects are static objects.

How do I make this object brighter in this case? Why do non-static objecs have different light results?

# Answer
> 2 votes
As @DMGregory said, I solved this issue to placing reflection probes in there and increase the intensity, is now non-static objects are brighter enough.

---
Tags: unity, lighting, lightmap
---


title: Unity Nav Mesh instantiation Issue

text:
# Question
Title: Unity Nav Mesh instantiation Issue
I've been working on a wave-based zombie game for the past few months and all of the systems have been working perfectly - until I upgraded to the latest version of Unity. Since then, spawning a zombie onto a nav mesh and then calling SetDesination is throwing the exception:

```
"SetDestination" can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.AI.NavMeshAgent:SetDestination(Vector3)

```

The zombies are spawned a random spawn point and their destination set as so:

```
 GameObject go;
        for (int i = 0; i < SpawnAmount; i++)
        {
            Vector3 location = new Vector3(transform.position.x + i + UnityEngine.Random.Range(-1, 1), transform.position.y, transform.position.z + i + UnityEngine.Random.Range(-1, 1));
            go = Instantiate(enemyPrefab, location, spawnRotation) as GameObject;
            go.GetComponent<NavMeshAgent>().SetDestination(players[0].transform.position);
        }

```

It is the setdestination line that is causing me issues.

I have a static baked nav area. The player characters (who also use nav agent to move) can move across the nav area perfectly - it is only the zombies which seem to have trouble.

I have spent a long while tweaking settings here and there. Adjusting the location of the zombie and even having a zombie in the game before starting the game. However I can't seem to correct this exception - all while the player characters are moving perfectly.

Any ideas on what I could be missing or areas I should be looking?

EDIT The updated and working code:

```
GameObject go;
for (int i = 0; i < SpawnAmount; i++)
{
    Vector3 location = new Vector3(transform.position.x + i + UnityEngine.Random.Range(-1, 1), transform.position.y, transform.position.z + i + UnityEngine.Random.Range(-1, 1));
    go = Instantiate(enemyPrefab, location, spawnRotation) as GameObject;
    go.GetComponent<NavMeshAgent>().Warp(location);
    go.GetComponent<NavMeshAgent>().SetDestination(players[0].transform.position);
}

```

# Answer
Just a shot in the dark here but I think that if you set a agents position with transform.position it does not know it's on the nav mesh. try using `NavMeshAgent.Warp(spawnPosition)` after you instantiate the zombie and the set its destination.
> 0 votes

---
Tags: unity, navmesh
---


# Question
Title: Should I develop with mouse in mind if I plan on targetting more than PC?
Pretty simple question but I am not sure of the answer.

Should I develop user controls that use the mouse, or ignore the mouse completely and use only button controls.

An example would be:

> Clicking on an item to pick up vs. Moving close to the item and pressing a button to pick it up.

What are your opinions on this, especially if you want to target more platforms than just PC?

# Answer
Yes, when you want your game to run on PC, you should think from an early design stage on how to best utilize the mouse. The same applies to the input features of all other platforms you consider targeting.

One of the main differences between a good port and a bad port to a different platform is how much effort you invested into accommodating the different input styles:

* Console players use gamepads. How they manage to accurately point at things with these clumsy thumbsticks will always be a mystery to me as a PC gamer. But all the different analog input axis' available on a standard gamepad offer some interesting possibilities. Text input keeps being annoying, but there are some really interesting UI solutions people came up with.
* PC users *sometimes* have gamepads but many don't have one or prefer using the mouse. They really dislike it when they have to navigate menus with keys when a mouse would be available. They also expect common actions to be available with keyboard shortcuts.
* Mobile users have touchscreens. They are much less precise than mouse input, but offer additional input methods like pressure sensitivity, swiping and multi-touch gestures. "Virtual Gamepads", i.e. putting your gamepad buttons in the corner and expecting players to press them, is a very lazy workaround which suffers from lack of haptic feedback and reduced screen space.

So when you want to make a good port to a different platform, you need to reconsider your input methods. That often means that you need to redesign your user interface from scratch. You can reduce the pain when you take that into account from an early point of the development and make sure that all game features can be properly implemented with the different input methods.
> 36 votes

# Answer
Yes you should.

PC users expect that they'll have a mouse to play your game. If you don't use it, your game risks to be labeled as a "poor mobile port", specially if some actions in the game should be more naturally accomplished with a mouse.

Also, keep in mind that some PC users will also expect that there will be more that the basic gameplay done with the keyboard.

I suggest you exploit as much as possible the target device's input features as possible to please both mobile and PC users.
> 6 votes

# Answer
It depends, as usual.

What genre? How much money/time do you have? Do you develop the application to make money?

Users are generally surprisingly forgiving about bad input controls in niche games (e.g. JRPGs by independent developers), but better input control is still a plus if you want to sell more.

If you are on a very tight budget and do not directly profit from sales (e.g. a charity fund paying you a fixed amount of hours to develop education software), it's sensible to stick to one single input method done well - doing multiple input methods well takes considerable amounts of time.

If you want to sell your game at a reasonable price ($20+) and aim to reach a reasonably large number of buyers (50'000+), you absolutely should keep in mind\* the different requirements of mouse, keyboard, touchscreen, and gamepad devices from the beginning. There's no way to simply "retrofit" gamepad input on a mouse/keyboard game or vice versa.

\*When thinking of how to make your game touch, gamepad and mouse friendly, you may find that there doesn't actually exist a good solution. Such cases are quite common (real time strategy games are rarely cross platform). In those cases the usual solution is to only release on devices that support the form of input your game requires.
> 5 votes

# Answer
This depends exactly on weekdays kind of have your developing.

**3D Games**
If you look at most first person games, the mouse is used only for looking around. When ported to console, analogue sticks and buttons are used and on mobile, swiping is used to look with as few as possible other controls are buttons on screen. For a good comparison, look at videos of the different releases of Minecraft.

**2D Games**.
For games where the interactions are in 2d space. Then using mouse interactions as you described can be possible; but the most important thing to consider is how often you have to move your hands from the keyboard to the mouse and back. On mobile you have no choice because all the buttons you may want to use have to be on screen. Though you can consider having buttons which only show up when needed on mobile, for example: when you approach an item a button can show up on screen only while the possibility to pick it up remains. In 2D games, point a x works well on PC and on mobile but can be a bit clunky on console due to the fact that analogue sticks may be used.

To your question though, the most important thing to consider when developing on PC for multi-platform is that you have a much larger wealth of buttons at your disposal than on other platforms. So provided you l your number of buttons needed minimal and (for the benefit PC) ensure that one hand Chan be kept on the mouse and one the keyboard, then t a be no problem print a games controls to other platforms.
> 1 votes

# Answer
Yes you should. However, I would develop against an abstract input class or interface, and then implement the various ways the user can interact with it against this, depending on the hardware type.

I don't know about your game specifically, but for an example, create an abstract class interface with a methods such as

```
bool lookingUp();
bool shooting();

```

And then implement them in a concrete class, e.g.:

```
bool lookingUp() {
    return mouseIsMovingUp(); // e.g. PC
}

bool lookingUp() {
    return isTrianglePressed(); // e.g. Gamepad
}

bool shooting() { // e.g. phone
    return screenPressedAt(10, 10);
}

```

Then in your game, create the concrete class based on the hardware type. This will make your code cleaner, and you can easily cater for different platforms.
> 1 votes

# Answer
I'm going to play devil's advocate. I'm a recent report issues by root metrics, more people use cellular apps vs PC's. That's right, not only have mobile taken over, but mobile apps have surpassed desktop users in sum.

With that said, consumers like convenience, and they may have a device which requires a mouse. Just a thought.
> -3 votes

---
Tags: input, user-experience
---


# Question
Title: How can i keep the spawned cubes to be inside the given area?
In this case the 4 walls and objects I spawn inside the 'wall area' are all cubes. This situation could change to where the walls will be spheres and the other objects can be cylinders or cubes (its not limited to cubes only).

What I'm trying to do is to spawn the objects in random positions but within the 'wall area'. The problem is when some cubes (objects) are spawning too close to the walls, part of the cubes will inside the area and some will be outside.

In the screenshot example on the right, a cube is going out of the wall area. In this case the walls area is sized according to the terrain (500x500) but it could be any size like 45x23 or 100x100.

In the script below I'm getting the 4 walls objects in array.

```
walls = GameObject.FindGameObjectsWithTag("Wall");

```

Now I wonder how can I use a ray cast to detect if each cube is spawning too close to one of the walls and if so then re-position the cube randomly, over and over again until it's inside the walls area. I'm not sure if using ray cast is the best way but that's what I had in mind.

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

public class SpawnObjects : MonoBehaviour
{
    public int numberOfObjects;
    public GameObject objectToPlace;
    public Vector3 newObjectsSize;
    public float spawnSpeed = 0.1f;

    private int wallsLengthX;
    private int wallsLengthZ;
    private int wallsPosX;
    private int wallsPosZ;
    private int currentObjects;
    private GameObject[] walls;
    private List<GameObject> objects = new List<GameObject>();
    private GameObject spawnedObjects;

    void Start()
    {
        var wi = GetComponent<Walls>();
        wallsLengthX = (int)wi.lengthX;
        wallsLengthZ = (int)wi.lengthZ;
        wallsPosX = (int)wi.wallsStartPosition.x;
        wallsPosZ = (int)wi.wallsStartPosition.z;

        walls = GameObject.FindGameObjectsWithTag("Wall");
        spawnedObjects = GameObject.Find("Spawned Objects");

        StartCoroutine(Spawn());
    }

    IEnumerator Spawn()
    {
        for (int i = 0; i < numberOfObjects; i++)
        {
            GameObject newObject = (GameObject)Instantiate(objectToPlace);
            newObject.transform.localScale = GenerateRandomScale(newObject);
            newObject.transform.localPosition = new Vector3(GenerateRandomPositions(newObject).x , GenerateRandomPositions(newObject).y + newObject.transform.localScale.y / 2.0f, GenerateRandomPositions(newObject).z);
            newObject.name = "Spawned Object";
            newObject.tag = "Spawned Object";
            newObject.transform.parent = spawnedObjects.transform;

            objects.Add(newObject);
            yield return new WaitForSeconds(spawnSpeed);
            currentObjects += 1;
        }

        var wp = GetComponent<WayPoints>();
        wp.FindMyObjects();
    }

    private Vector3 GenerateRandomScale(GameObject newObject)
    {
        Vector3 newScale = new Vector3(UnityEngine.Random.Range(5, 100), UnityEngine.Random.Range(5, 100), UnityEngine.Random.Range(5, 10));

        return newScale;
    }

    private Vector3 GenerateRandomPositions(GameObject newObject)
    {
        float paddingX = Mathf.Clamp(newObject.transform.localScale.x, 0, wallsLengthX) / 2f;
        float paddingZ = Mathf.Clamp(newObject.transform.localScale.z, 0, wallsLengthZ) / 2f;
        float originX = wallsPosX + paddingX - wallsLengthX / 2f;
        float originZ = wallsPosZ + paddingZ - wallsLengthZ / 2f;
        float posx = UnityEngine.Random.Range(originX, originX + wallsLengthX - paddingX);
        float posz = UnityEngine.Random.Range(originZ, originZ + wallsLengthZ - paddingZ);
        float posy = Terrain.activeTerrain.SampleHeight(new Vector3(posx, 0, posz));

        return new Vector3(posx, posy, posz);
    }
}

```

# Answer
```
using UnityEngine;
using System.Collections;

/// <summary>
/// Spawns a prefab randomly throughout the volume of a Unity transform. Attach to a Unity cube to visually scale or rotate. For best results disable collider and renderer.
/// </summary>
public class SpawningArea : MonoBehaviour {

public GameObject ObjectToSpawn;

    void Spawn() {

            // Random position within this transform
            Vector3 rndPosWithin;
            rndPosWithin = new Vector3(Random.Range(-1f, 1f), Random.Range(-1f, 1f), Random.Range(-1f, 1f));
            rndPosWithin = transform.TransformPoint(rndPosWithin * .5f);
            Instantiate(ObjectToSpawn, rndPosWithin, transform.rotation);

    }
}

```

This will allow you difene a spawning volume that you can adjust. Hope this helps.
> 1 votes

# Answer
There are two solutions that come to my mind for this one:

First one is to just do the math and check whether the object you're about to create is going to be outside the area you want it to be in or not.

The second one is to put invisible "wall" around the area you want your actual walls to stay inside. When you spawn a wall which collides with your invisible one (you will need colliders on both walls) then you just remove that wall from the game. This second method is how I generated "planets" for my game, so that they weren't too close to players or under some UI elements.

There are probably other methods for this, but these are the ones I could think of.
> 0 votes

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


# Question
Title: Cause a projectile to wait at the position initially fired for a second before flying off
I want to have a projectile that the character fires stay in the same place for a second or two before flying off in the direction of the mouse at the initial time of fire. The character can move away from the projectile after firing it, and the projectile wont move till after the time has passed.

# Answer
> 1 votes
Sounds like a job for Coroutines....

So you start off with something like this :

```
 IEnumerator WaitingBullet( float waitTime)
    {
        //Spawn bullet and set direction
        yield return new WaitForSeconds(waitTime);
        // give the bullet some velocity to fly off in its set direction
        yield return null;
    }

```

And then you use this to start the coroutine when you detect a fire input :

```
StartCoroutine(WaitingBullet(2.0f));

```

This will wait for 2 seconds between spawning the bullet and setting it's velocity. Hope this sets you on the right track.

# Answer
> 1 votes
You would have to use a coroutine. The usage of a coroutine looks something like this:

```
IEnumerator Wait()
{
    yield return new Waitforseconds(1f);// wait for 1 sec
    Shoot();// shoot your projectile
}

```

In order to use coroutines you have to say at the top of the script: using UnityEngine.System.Collections

To leave the bullet steady, you could unparent the bullet from the gun. Look for Gameobject.SetParent() or something similar on the Unity API

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


title: Jitters in collision reaction

text:
# Question
Title: Jitters in collision reaction
I'm working on a project for school and I'm having some trouble solving a bug. When the player collides with a rectangle the sprite/hitbox keeps jittering while the player has momentum in the direction.

I'm guessing that the reaction sometimes moves it so that they are right next to each other and sometimes it makes it so that there is a 1 pixel space between. Is this because I'm using float and it sometimes rounds up? If so what is a good way to solve it?

The order it happens in gameloop is:

1. Update player position
2. Check collision (move if there is one)
3. draw player to window

The code I use for collision detection and reaction is:

```
void Collider::collisionTest(Player &player, sf::RectangleShape &rec2, float push) {
    float intersectX;
    float intersectY;
    float deltaX;
    float deltaY;

    if(AABBCollision(player.getHitbox(),rec2, intersectX, intersectY, deltaX, deltaY))
    {
        push = std::min(std::max(push,0.0f), 1.0f);

        if(intersectX > intersectY){
            if (deltaX > 0.0f){
                player.playerMoveCollision(intersectX * (1.0f - push), 0.0f);
                rec2.move(-intersectX * push, 0.0f);
            }else
            {
                player.playerMoveCollision(-intersectX * (1.0f - push), 0.0f);
                rec2.move(intersectX * push, 0.0f);
            }
        }else{
            if (deltaY > 0.0f){
                player.playerMoveCollision(0.0f,intersectY * (1.0f - push));
                rec2.move(-intersectY * push, 0.0f);
                player.setIsJumping(false);

            }else
            {
                player.playerMoveCollision(0.0f,-intersectY * (1.0f - push));
                rec2.move(0.0f, intersectY * push);

            }
        }

    };

}

bool Collider::AABBCollision(sf::RectangleShape& rec1, sf::RectangleShape& rec2, float& intersectX,float& intersectY,float& deltaX,float& deltaY) {
    sf::Vector2f rec1Position = rec1.getPosition();
    sf::Vector2f rec1HalfSize = rec1.getSize() * 0.5f;
    sf::Vector2f rec2Position = rec2.getPosition();
    sf::Vector2f rec2HalfSize = rec2.getSize() * 0.5f;

    deltaX = rec2Position.x - rec1Position.x;
    deltaY = rec2Position.y - rec1Position.y;
    intersectX = abs(deltaX) - (rec2HalfSize.x + rec1HalfSize.x);
    intersectY = abs(deltaY) - (rec2HalfSize.y + rec1HalfSize.y);

    if (intersectX < 0.0f && intersectY < 0.0f){
        return true;
    }
    return false;
}

```

Edit:

So i kinda solved it in whats probably a bad way.

The problem was using abs(deltaX/deltaY) as i shaved off the decimal point of the float.

What i did to solve it was:

```
intersectX = abs(deltaX) - (rec2HalfSize.x + rec1HalfSize.x);
intersectY = abs(deltaY) - (rec2HalfSize.y + rec1HalfSize.y);

```

into

```
if(deltaX < 0)
{
    intersectX = (deltaX * -1) - (rec2HalfSize.x + rec1HalfSize.x);
}else
{
    intersectX = deltaX - (rec2HalfSize.x + rec1HalfSize.x);
}

if(deltaY < 0)
{
    intersectY = (deltaY * -1) - (rec2HalfSize.y + rec1HalfSize.y);
}else
{
    intersectY = deltaY - (rec2HalfSize.y + rec1HalfSize.y);
}

```

# Answer
So i kinda solved it in whats probably a bad way.

The problem was using abs(deltaX/deltaY) as i shaved off the decimal point of the float.

What i did to solve it was:

```
intersectX = abs(deltaX) - (rec2HalfSize.x + rec1HalfSize.x);
intersectY = abs(deltaY) - (rec2HalfSize.y + rec1HalfSize.y);

```

into

```
if(deltaX < 0)
{
    intersectX = (deltaX * -1) - (rec2HalfSize.x + rec1HalfSize.x);
}else
{
    intersectX = deltaX - (rec2HalfSize.x + rec1HalfSize.x);
}

if(deltaY < 0)
{
    intersectY = (deltaY * -1) - (rec2HalfSize.y + rec1HalfSize.y);
}else
{
    intersectY = deltaY - (rec2HalfSize.y + rec1HalfSize.y);
}

```
> 0 votes

---
Tags: c++, collision-detection, collision-resolution, sfml, aabb
---


# Question
Title: Does using a Community Script with Creative Commons - Attribution-NonComercial-ShareAlike prevent me from selling the game?
So I have been building a game in one of the RPG Makers with the end goal to sell it. while I have been working hard coding up my own scripts one in particular is a complex Active Battle System like that of Zelda which gives me more options for enemy verities and attack patterns.

The script has in the comments a Creative Commons - Attribution-NonComercial-ShareAlike license. I asked about NonComercial and I get 2 kinds of answers

* I can not sell the game at all if the script is in there as such I either have to replace the script or give the game away for free
* I can not sell the script or remixes of the script for others to use as such in a compiled game which isn't open source (ie. you have to hack/decompile it to get it's scripts) it's fine to sell the game with the script

now I am a long ways away from completing the game and it might be possible that later on my scripting skills get to the level that I can rebuild the Battle System to be similar but of my own code (or even hire someone to do it for me)

however, in the situation that I complete the game and I can not replace the script, does it prevent me from selling it? or does NonComercial prevent me from selling the script for others to use for themselves?

# Answer
> 3 votes
**tl;dr:** No, you can not use that script and sell your game.

The answer can be found in the license text of the CC-BY-NC-SA. This is version 3.0. You did not specify the license version. This answer assumes 3.0. When the script you are using uses a different license version, parts of this answer may be inaccurate. But the versions differ mostly in wording, not in spirit, so the tl;dr would likely be the same. Also, I am not a lawyer. This is a layman interpretation. Do not consider this leagal advise.

---

First of all, Creative Commons themselves advise against using CC licenses for software. They were designed for creative media like music or art. So some parts of it are unclear regarding how to apply them to software. Some people use the CC-BY-SA-NC for software regardless, because it's one of the few reasonably popular standard licenses with a "free for non-commercial use" concept.

The License section 3 gives you the right to adapt and redistribute the work. This is what you want to do. So far everything is fine. But later sections puts certain restrictions on it, for example the section 4c:

> You may not exercise any of the rights granted to You in Section 3 above in any manner that is primarily intended for or directed toward commercial advantage or private monetary compensation.

That's the Non-Commercial clause, and it means no, you are not allowed to use the script in any project which makes you money. Selling the game voids all your rights to use the script. That means you no longer have permission to use the script at all.

Another clause which might be problematic to you is 4b, the ShareAlike clause:

> You may Distribute or Publicly Perform an Adaptation only under: (i) the terms of this License; (ii) a later version of this License with the same License Elements as this License; (iii) a Creative Commons jurisdiction license (either this or a later license version) that contains the same License Elements as this License (e.g., Attribution-NonCommercial-ShareAlike 3.0 US) ("Applicable License").

That means the script must be redistributed under the same license conditions. Whether that means that your whole game must be CC-BY-NC-SA depends on whether a game which uses the script is an "Adaption" or a "Collection". The license defines these terms, but the definition is IMO not really applicable to software. An "Adaption" would be subject to this clause, a "Collection" would not. This ambiguity is one reason why one should not use CC licenses for software.

---

By the way, many people who create software libraries under such "inconvenient" license terms do that as a promotion measure. When you would like to use their work in a commercial project, they might be willing to provide it to you under more convenient license conditions if you pay them a license fee. You might want to contact them and check out if they can be negotiated with.

Paying for 3rd party components is almost always cheaper than developing it yourself. In those cases where the component is not, that's usually either because it is unsuitable or because of the work it takes to integrate it with your own components. But you have already evaluated that it's suitable and sunk the cost to integrate it, so it doesn't matter.

# Answer
> -1 votes
Firstly, I am not a lawyer.
Second, the creative commons licensing site has some simple break downs for their licenses.

https://creativecommons.org/licenses/by-nc/3.0/us/

According to this, it would seem that no commercial use is allowed, unless there is some legal exception based on your specific circumstances.

---
Tags: legal
---


# Question
Title: Rotate an object to face a point with glm::lookAt
I want to rotate an object to face a point, such as the monster look at the player.

For that I've decided to use the glm::lookAt function. However the following does not yield good results:

```
const glm::mat4 transformation = glm::lookAt(ghostPosition, cameraPosition, glm::vec3(0, 1, 0));
ghost.transformation = transformation;

```

The ghost is correctly oriented to the player but is located to the world origin. However the following works correctly (position and orientation):

```
const glm::mat4 transformation = glm::inverse(glm::lookAt(ghostPosition, cameraPosition, glm::vec3(0, 1, 0)))

```

But I don't get why I need to inverse the matrix ?

# Answer
Because the `lookAt` function is to position the camera to look at an object (not for an object to look at another object) and the way 3D **cameras** work is that mathematically they **move the entire world the opposite way** and the screen stays at the origin.

So because the matrix is intended for a camera and 3d cameras work "backward" you need to inverse the matrix to get an object to look at another object.
> 5 votes

---
Tags: mathematics, rotation, glm
---


title: Baking artifact in Unity

text:
# Question
Title: Baking artifact in Unity
I am using unity 2017.1.0 f3, Enlighten baking, with Generate lightmap UV ticked in import settings. Also the object has prioritized illumination and the light map resolution is high. An example of the artifact is shown.

The lightmapping settings is as follows.

The issue doesn't appear in Realtime illumination.

The object is marked static. Can someone help me?

# Answer
> 1 votes
*Lightmap stitching*

Lightmap seam stitching makes it easy to get rid of those annoying edge seams in lightmaps.

Fixed in newer unity version: 2017.2

What's new in Unity 2017.2

---
Tags: unity, lightmap, global-illumination
---


# Question
Title: 2d Scale width and height based on distance
I'm drawing a health bar on top of each player. I transform 3d position to 2d. I would like to draw it smaller when distance increases. Any simple math for that? Let's say bar width is 30 and height is 10 it looks good only on distance == 100. What formula should I use to make it decrease in size when distance increases?

Should resolution of the game be taken into consideration?

# Answer
> 6 votes
The very *complex* and *hard to understand* calculation people do to get an object's size at a specific distance is: divide by Z. Even the big APIs, like DirectX and OpenGL are basically just rasterizing APIs with a depth buffer. The 3d aspect comes from this. So:

Given a width, a height and a distance from the camera Z, the new width and height of the object is:

```
w' = w / Z
h' = h / Z

```

---
Tags: 3d, mathematics, linear-algebra, directxmath
---


title: Determine route between rooms

text:
# Question
Title: Determine route between rooms
Is there a general purpose algorithm to determine a route between rooms of a building?

Imagine a fixed-layout, single-level house with 50+ rooms. Assume I have a data structure that defines the exits of each room and the room to which each exit leads. I'd like to know how to get from room 4 in the NW corner to room 37 in the E side, say. I want the shortest list of rooms that need to be traversed. (I don't need to see this graphically in real-time.)

Is it worth finding such an algorithm or should I just 'map out' the level and use the pathfinding abilities of my game dev platform of choice..

edit: removed the A\* reference

# Answer
You have a common misconception. A\* isn't made for grids, it usually uses graphs. A grid is just a specialized graph with each node having 4 edges (apart from the edges and corners).
> 12 votes

# Answer
I cannot think of any particular general purpose solution for this, although most certainly there are people who have solved this multiple times, in various ways.

One could well use the available/built-in pathfinding abilities, this should work fine but is probably not the primary issue.

The challenge is to define an optimal node graph. This depends on how greedily the task should be solved, and also on the particular features of the environment. Apparently, a building has for example corridors, and apparently it is sometimes fastest to pass a corridor diagonally, ie. enter it by it's left wall and leaving it by it's right wall? Maybe there are rooms that need to be crossed diagonally or along some of it's walls? Staircases?

I would probably (as i like to control things myself) solve this by first creating a node graph that holds all possible nodes (points), ie. every corner and every door (even left and right edge of it separately?) is a node, or holds a node very nearby. Then I'd perform a "all nodes against all nodes" test and create a link between two nodes whenever they can see each other directly (could even use the 3D engines hit testing for that, if there is a building model available); at the same time calculate the distances as graph weights. This would create the "full set" node graph. Finally, I'd execute "go from each room to each other room" pathfinding tasks and mark any node/link that was ever used with 1. To naturally then remove from the graph all such nodes/links that were never used. This would create the minimum node graph that covers for all possible movement, suitable for runtime use, to be embedded with the application. And also be a test for the overall functionality - perhaps an extra node bust be inserted somewhere because of some unexpected reason?
> 0 votes

---
Tags: path-finding
---


# Question
Title: Character getting stuck when colliding from the top
when my character goes onto a box that I am trying to make him collide with he gets stuck. The way I have it configured is that at the end of every frame, the characters x and y values are stored in old x and old y, and if he is colliding with the box his x and y are reverted to old x and old y. This seems to work when walking into the box, but when the character jumps on the box he gets stuck and can't move. I think this has something to do with his x and y being infinitely pushed to oldX and oldY, but I don't know how to fix this. Thanks for the help!

```
 for(int x = 0; x < collidables.length; x++){
        if(collidables[x] instanceof QuestionBox){
            collidables[x].bottomCollision(mario);
        }

        if(mario.intersects(collidables[x].boxRectangle)){
            mario.setMarioX(mario.oldX);
            mario.setMarioY(mario.oldY);

        }
    }

        mario.oldX = mario.getMarioX();
        mario.oldY = mario.getMarioY();

```

Here is the code for what happens upon a collision. Thanks for the help!

# Answer
> 1 votes
**Short Answer**: you're going to have to treat "falling" and "moving" each as a separate action, each with the ability to be undone separately, instead of combining them into a single undo action.

**Long Answer**: Lets just simulate it out: `o` is current position, `x` is our saved position, `_` is a wall, `.` is empty space.

```
  ...o.......
  ___________

```

okay, we're holding down the "move right" button, so lets move Mario right.

```
  ...x..o....
  ___________

```

okay, now gravity moves Mario down

```
  ...x.......
  ______o____

```

uh wait, Mario's intersecting the wall! lets move back to our old location

```
  ...o.......
  ___________

```

Wait... where did my "move right" go?

---
Tags: collision-detection, slick
---


# Question
Title: When should you label something as a micro transaction, DLC or expansion?
Is it based on monetary cost, filesize, perceived value or something else entirety?

# Answer
> 4 votes
Let's look at the definitions:

* microtransaction: a very small financial transaction conducted online.
* DLC: additional content created for a released video game.
* Expansion pack: a separate product that builds on top of an existing game to add significant new features. (usually disc based)

Basically, microtransactions don't make the games bigger, they simply allow you to buy virtual items already in it.

For stuff that actually makes the game bigger, if it's downloadable online, then it's a DLC, if it's available as a physical copy, then it's an expansion pack. (DLCs are basically expansion packs, this just states the narrowest possible term you can use for them)

# Answer
> 0 votes
Micro transactions let you get new things like health kits, gun repairs,etc. Stuff you already can get in game but just want to pay money for to get quicker.

DLCs and expansions though give you new game play. A whole new weapon, a whole new area of the game map, or a new type of game play not available in the original game.

---
Tags: terminology, microtransactions
---