# Question
Title: Can't use one variable to store different data types. What's a better solution?
I'm trying to make my first game in Unity and I decided to have a go at making a 3D tower defence. I've created a UI Panel with 4 buttons used to upgrade the turrets. When the player selects a turret the panel appears and the button text and images are changed to match the type of turret selected. The buttons all call one function 'UpgradeButtonClick(int upgradeIndex)' which applies the upgrade to the selected turret.

In order to reuse a single panel and one set of buttons I created a class called 'Turret' which will be attached to every type of turret. This class stores the cost, materials and upgrades for the turret as well as a reference to the attack script for the turret. This was fine until I introduced a second type of turret (I.e. lazer turrets and fire turrets). Originally I had:

```
public LazerTurretShooting attackScript;

```

But that will obviously not work for the fire turret. Ideally I would like to test the type of turret and then declare the correct variable type. But I can't as the variable would then only be accessible where it is declared and not to the whole class.

The attackScript variable is used near the bottom of the UpgradeButtonClick function to modify the turrets damageMultiplier and apply the upgradeEffect. See below:

```
public class TurretManager : MonoBehaviour {

/* Removed unnecessary functions */

public void UpgradeButtonClick(int upgradeIndex)
{

    Turret turret = selectedTurret.GetComponentInParent<Turret>(); //Get the Turret script from the selected turret

    if (turret.turretUpgrades.Length > upgradeIndex) //Make sure there is an upgrade with the selected index
    {

        if (!turret.turretUpgrades[upgradeIndex].applied) //Check if this upgrade has already been applied
        {
            bool applyUpgrade = false;
            int prerequisiteIndex;

            //Check if the upgrade requires a previous upgrade to be applied first
            prerequisiteIndex = turret.turretUpgrades[upgradeIndex].requiredUpgrade; //Store the index of the required upgrade/prerequisite
            if (prerequisiteIndex > -1)
            {

                if (turret.turretUpgrades[prerequisiteIndex].applied) //If the required upgrade/prerequisite has already been applied
                { //Allow the upgrade
                    applyUpgrade = true;
                } else
                { //Don't allow the upgrade
                    applyUpgrade = false;
                }

            } else
            { //There was no prerequisite so allow the upgrade
                applyUpgrade = true;
            }

            if (applyUpgrade)
            {
                if (ScoreManager.Instance.Money > turret.turretUpgrades[upgradeIndex].upgradeCost) //Check if the player has enough money to buy the upgrade
                {
                    turret.attackScript.damageMultiplier += turret.turretUpgrades[upgradeIndex].damageMultiplier; //Apply the new damage multiplyer
                    turret.turretUpgrades[upgradeIndex].applied = true; //Set the applied flag so this upgrade cannot be applied twice
                    UpdateUpgradePanelButtons(); //Update the buttons to enable buttons for any upgrades which require this upgrade as a prerequisite

                    ScoreManager.Instance.Money -= turret.turretUpgrades[upgradeIndex].upgradeCost; //Charge the player for the upgrade

                    if (turret.turretUpgrades[upgradeIndex].applyUpgradeEffect) //If the upgrade enables the turrets additional effect, turn it on
                    {
                        turret.attackScript.applyUpgradeEffect = true;
                    }

                }

            }

        }

    }

}

}

```

Here is the full Turret class:

```
[System.Serializable]
public struct TurretUpgrade
{
    [Tooltip ("The damage multiplier is increased additively. So to increase damage by 20% enter 0.2 or to decrease enter -0.2")]
    public float damageMultiplier;
    [Tooltip("Tells the turret to play its additional effect (E.g. Dual Lazers on a lazer turret)")]
    public bool applyUpgradeEffect;
    [Tooltip ("Index of upgrade required before this upgrade can be applied. (-1 = none required)")]
    public int requiredUpgrade;
    [HideInInspector]
    public bool applied; //Has the upgrade been applied to this turret
    [Tooltip ("Text to display under the upgrade button (E.g. '10% Damage Increase')")]
    public string upgradeButtonText;
    [Tooltip ("The cost of the upgrade")]
    public int upgradeCost;
    [Tooltip ("A Sprite image for the upgrade button")]
    public Sprite buttonSprite;

}

public class Turret : MonoBehaviour {
    public Material opaqueMaterial;
    public Material translucentMaterial;
    public int cost;
    public LazerTurretShooting attackScript; //This variable would need to store different types

    public TurretUpgrade[] turretUpgrades = new TurretUpgrade[4];

    void Awake()
    {
        //I need to get the correct type of script for this turret
        attackScript = GetComponent<LazerTurretShooting>();
        //attackScript = GetComponent<FireTurretShooting>();
        //attackScript = GetComponent<etc>();
    }
}

```

What would be the best way to approach this? If I create separate 'Turret' classes (E.g. LazerTurret and FireTurret) the function which sets the text and images of the upgrade buttons wouldn't work because it usees:

```
Turret turret = selectedTurret.GetComponentInParent<Turret>();
for (...) //Loops all 4 buttons
textLabels[0].text = turret.turretUpgrades[i].upgradeButtonText;
//etc

```

I can provide this full function if its needed.

# Answer
Like @PompeyPaul says, Polymorphism is key. To expand on the idea, here is another possible design for a Turret class:

```
public abstract class Turret : Monobehavior {
    ...
    public abstract void Attack();
    public abstract void Upgrade();
}

```

Assuming that everything besides how the turrets attack and are upgraded is the same for every type, this would expose a common interface for all turrets. Now you could make different specific turret classes:

```
public class LaserTurret : Turret {
    public int statSpecificToLasers = 5;
    public void Attack() {
        //do something cool with a laser
    }
    public void Upgrade() {
        //Apply changes to statSpecificToLasers
    }
}

public class FireTurret : Turret {
    public int statSpecificToFire = 12;
    public void Attack() {
        //do something cool with fire
    }
    public void Upgrade() {
        //Apply changes to statSpecificToFire
    }
}

```

Because the Turret class has virtual methods, you can't really have a concrete Turret, so it cannot be constructed, and you wouldn't attach it to any GamEObjects, but since both LaserTurret and FireTurret inherit from Turret, both can be treated as if they were Turrets. Now, in your TurretManager, selectedTurret can still be declared as a Turret type, but you can pass in either a FireTurret or a LaserTurret. Which Attack() or Upgrade() method gets called depends on which type you pass.

```
Turret selectedTurret = ob1.GetComponent<FireTurret>();
selectedTurret.Attack(); //shoots fire
selectedTurret = ob2.GetComponent<LaserTurret>();
selectedTurret.Attack(); //shoots a laser

//You can even put them in the same collection
List<Turret> turrets = new List<Turret>();
turrets.Add(ob1.GetComponent<FireTurret>());
turrets.Add(ob2.GetComponent<LaserTurret>());

```
> 4 votes

# Answer
It sounds like you need polymorphism in your class design. I would start with a base turret, as you have, which has all of the base functionality. It also has virtual functions for accessing parts of it.

You then have an TurretAttackBase script which has the common attack base functionality. You then derive cannon attack, laser attack, etc from that.

You then create a turret prefab which has the type of turret, and attach the TurretAttackLaser or whatever to it.

Your script then calls the virtual functions to get the TurretAttack and calls request upgrade.

That way you have one consistent interface but with different derived turrets, attack types etc all handling correctly.

So for your turrent you would call

```
turret.attackScript.ApplyUpgradeEffect();

```

The turret would then get the attack script, call ApplyUpgradeEffect() and it will be called on either the TurretAttackLaser or TurretAttackCannon class depending on which type it actually is.
> 3 votes

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


# Question
Title: How to make buttons change in to another button when pressed in Game Maker
I am trying to make it so that when I click on a button in my games store that the current button changes to a new one right where the old one was and then has its own conditions.

ex. Press the button "Add 1/ps - $50", effects applied and now "Add 5/ps - $500" is now the button which will do the desired effect when clicked with conditions met.

How do I go about doing this?

# Answer
> 1 votes
`instance_change(obj_anotherButton, true)`

First parameter is which object you want to change the current object into.

Second parameter is either you want to execute the create and destroy events in the the new object. (True runs it, False does nothing)

More info at Game Maker Reference

# Answer
> 0 votes
You want to make 2 different objects, doing it in one would be too complicated. Make 2 different sprites with one having "Add 1/ps - $50" and another with "Add 5/ps - $500". Make sure both of the sprites are the same size and are centered on the same spot. Have your upgrade happen in your code, then call a script (what you name it is up to you)

```
//Have your code for upgrading your "ps" here.
//Now call your script here. ex: upgrade();

```

Now in the script, write:

```
var xx = x;
var yy = y;
instance_destroy();
instance_create(xx,yy,obj_newPsButton);

```

# Answer
> 0 votes
By creating and destroying objects, while it doesn't create overhead, it's inefficient. If I'm understanding your question right you want to have a button that changes from a 1 ps bought to a 5 ps bought.

In which case, you can just draw the text on top of the button sprite and change it when the button is clicked.

Drawing

```
draw_text(x, y, text);
/* Where text is the variable you change when the button is clicked
   and x/y are the position of the text on the button */
script_execute(effectApplied);
/* This being an object var with the data of the script to run */

```

Then whenever the button is clicked

```
text = "Add 5/ps - $500"; // Set the new button text
effectApplied = newScriptToRun; // Set the new Script to run

```

This, in my opinion, is the best way of performing this. If you want the button sprite to change then you can just have each of the button images be included as subimages in a single Game Maker Sprite and just change the `sprite_index`to the new sprite then change the `effectApplied` script var.

---
Tags: game-maker
---


# Question
Title: Algorithm to make an entity follow tile edges in a tilemap
I'm implementing something like the electric balls seen in this video https://www.youtube.com/watch?v=MWyB56AlAWw (skip to 1:55 and you will see this electrical balls follow tile edges in the tilemap).

I have an algorithm working but I feel like it is a bit of a mess. I could summarize it as:

1) Setup

1. The ball starts always falling
2. I have an enum holding what side the ball is engaged to (side of tile it is traveling. It could be Top,Bottom,Left, Right and None). This var is inited to "None" at start.

2) While the ball is falling, as soon as it touches a tile we set the engaged var to bottom (the ball is engaged to a tile that is at the bottom) and we make it move to the left.

3) Now we have 2 cases

1. the ball collides with another tile while moving to the left. In this case we set the engaged var to Left and start moving it upwards.
2. the ball gets into a situation where there's no tile at the bottom to continue going to the left. In this situation we use the engaged var to know what edge of the tile we were moving along. In this particular case as we where engaged to a bottom tile we fix the ball position to be right at the left of the last valid tile and start moving it down.

This applied to all possibilities makes the ball run across all the tilemap.

I would like to know if there's a more clean way to do this without all this "mini cases" or a better way to accomplish this.

Cheers

# Answer
You can simplify the problem, and try to implement a tile-based entity that follows a wall, a.k.a. the Wall Follower algorithm. There's very little state required - you only need to know what direction you are currently going.

Assume we're already following the wall to the right. The entity moves one tile at a time, and at each step:

```
while (there is a wall in front of us)
    turn left
move forward
if (there is no wall to our right)
    turn right

```

That's all you need; the only difference between this and your proposed solution is that it uses the entity's local directions, so you don't need to repeat those states for all four cardinal directions.

Once that's working, you can

* Add a setup state, where it's not following a wall yet
* Position the entity so that it's snug against the wall
* Animate it moving gradually, instead of one tile at a time
> 1 votes

# Answer
## A finite state machine

Instead of coding individual cases for *every* single state of being, a finite state machine provides a simple, and more importantly, expandable approach to coding such awkward case structures. This method is even more advantageous when used in conjunction with an object-oriented language as states can be represented as class instances.
> 0 votes

---
Tags: tilemap
---


# Question
Title: Is there a way to read a picture pixel by pixel in unity without any distortions
In my unity project I have an image file which contains information. I would like to be able to read this .bmp file pixel by pixel. So I tried simply loading a sprite, and then reading its texture. However when I do that, the loaded texture appears to be different than the image I'm using, as if it was compressed. I tried modifying the asset settings (making it an advanced texture with point filter mode, and setting format to argb32bit uncompressed) but it doesn't help. Any ideas?

EDIT: Some additional information,

The code with which I load the image into a pixel array

```
// sprites from which paths will be loaded
public Sprite[] path_maps;
// Color 24 array which contains the texture bitmap
private Color32[] pixels;
// graph with paths
public Graph[] graphs;

void Start () {
    // I skipped some  code that doesn't matter to the problem

    // go through all path maps
    for (int i = 0; i < path_maps.Length; i++) {
        // load sprite into pixels array
        pixels = path_maps[i].texture.GetPixels32 ();
        // create new graph
        graphs [i] = new Graph ();
        // get graph from path map
        graphs[i].pixels_to_graph(pixels, path_maps[i].texture.width, path_maps[i].texture.height, camera_width, camera_height);
    }

}

```

The function which reads pixels and creates node for each colored pixel (only relevant part of the function)

```
public void pixels_to_graph (Color32[] pixels, int width, int height, double camera_width, double camera_height)
{
    // assign pixels width and height
    pixels_width = width;
    pixels_height = height;
    // assign camera dimensions
    this.camera_width = camera_width;
    this.camera_height = camera_height;
    // First create as many nodes as there are colored pixels (simply read the pixel map)
    // Note that pixel map contains the bitmap from bottom to the top (left bottom to top right)
    // create nodes array
    pixel_nodes = new Node[width*height];
    // current position in pixel array. Made for easier calculations
    int carriage = 0;
    // go through all rows
    for (int i = 0; i < height; i++) {
        // go column by column
        for (int j = 0; j < width; j++) {
            // if it's transparent or white - ignore
            if (pixels [carriage].a == 0 || pixels [carriage].Equals (col_white))
                continue;
            // else add node to the node array
            pixel_nodes [carriage] = new Node (j, i, pixels_width, pixels_height, camera_width, camera_height); // note that i is the y position while j is the x position
            // add node to nodes list
            nodes.Add (pixel_nodes [carriage]);
            carriage++;
        }
    }

```

I detect the problem in the above `pixels_to_graph function`. When I debug it with a 1680x1050 image, that has pixels in its bottom left corner (three black squares with 1 pixel distance between them, of size 3x3px, 2x2px, 1x1px) it only detects the 3x3 one, the colour value at position of the other 2 squares is white. When I tried other shapes I also discovered other distortions, some 1px wide lines are not there, as well as single pixels.

My current texture settings (though note I tried different options but some of them don't display anything, this one at least displays something):

# Answer
Welp. It appears to have been a codding error. In the above code:

```
for (int j = 0; j < width; j++) {
        // if it's transparent or white - ignore
        if (pixels [carriage].a == 0 || pixels [carriage].Equals (col_white))
            continue; <------------ BUG LOCATION
        // else add node to the node array
        pixel_nodes [carriage] = new Node (j, i, pixels_width, pixels_height, camera_width, camera_height); // note that i is the y position while j is the x position
        // add node to nodes list
        nodes.Add (pixel_nodes [carriage]);
        carriage++;
    }

```

because of this continue the carriage position does not change when alpha is zero or when color white is found. Obviously I wasted 2 days debugging an error that was caused by trying to make code "better".
> 1 votes

# Answer
It looks like your texture format is set to `RGBA Compressed` (bottom of the texture panel), which might be why your output isn't pixel perfect. Try setting it to `RGB 24 bit`instead, which should disable compression and give you the result you're after. More details on texture formats can be found here under 'Per-Platform Overrides'
> 0 votes

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


# Question
Title: Are there any methods for generating rivers on-demand with Perlin/Simplex noise?
I'm aware of many methods for procedurally generating rivers, but they require an entire heightmap beforehand in order to work. For instance, they may require to find a high position on the map and find a path to the ocean.

But when working with on-demand / on-the-fly procedural generation (generating the map around the player as he moves), those requirements are unfeasible. For instance, Minecraft doesn't have "true rivers":

> the river does not in fact have a start and end point, it is actually just dividing the two biomes, this means that it uses the distance between the point and the edge of the biome to determine how deep the water should be, with some variance of course.

This mod seems to solve the issue, but how? Probably it takes advantage of the fact that entire chunks are generated and thus is not entirely on-demand per position.

So, the question is: how can I generate rivers procedurally on-demand? More preciselly, I want a function f(x, y) which tells me whether there is a river at (x,y) or not (and its flow direction). It seems pretty unsolvable for me, but maybe people have come with some solution.

# Answer
> 1 votes
It depend if you want an infinite terrain or not, if you don't have infinite terrain you might be able to generate an idea of where the sea is, it wouldn't be impossible in infinite terrain but you would have to planned it at design time (frequency of land).

But the biggest realization is that you should use **correlation** instead of cause. River always flow down, therefore you know it define the slope of a mountain, it's easier to place a mountain that follow a river than a river that follow a mountain (and have control), river are basically line segment.

The way I do it is that I tend to have a hierarchical implementation: for example infinite world can be define as increasing partition in the form of sector -\> region -\> area -\> chunk -\> block, let's say that each contain 10 division of the zone below, you can generate data that is global to this zone and pass it to his children to process through progressive refinement.

So a sector can have two point as a data that mark that mark the beginning that will be the basis for further generation in a lower level, like using the direction as a gradient to prescribe slope and distance field to be sure that thing are place relative to the river. The idea is also that big feature is also happening at parent, so ocean existence are a matter of the highest level, which would allow you to compute neighbor state and infer proper direction.

It's also possible to have infinite circulation across infinite distance (for example let say you are doing an infinite city) as long as the dependency is only on direct neighbor and no more. For example let say you generate one or more point inside a zone, you can compute circulation (how they are linked) then compute data (here points) from the neighbor to get the connectivity. Because you would use coherent generation the circulation will remain unbroken in both direction, how you generate the actual path is up to you.

---
Tags: procedural-generation, perlin-noise, procedural, simplex-noise
---


title: How to smooth scene2d ui default skin?

text:
# Question
Title: How to smooth scene2d ui default skin?
I am usng uiskin.png, default.fnt, uiskin.atlas to create my game UI, but the images is blurred, How do I make it smooth?

# Answer
Open **ui\_skin.atlas** in your GDX project and change the 3rd line to:

```
filter: Linear,Linear

```

It will apply linear min/mag filters to textures and they should look a little bit better. Main LibGDX skin is 'pixelated' by default. You can search here for some custom skins: https://github.com/czyzby/gdx-skins or implement your own in Photoshop/Illustrator with some youtube tutorials. Tutorials would take a week or two but they would help you in your entire life :)
> 2 votes

---
Tags: libgdx, scene2d
---


# Question
Title: Where do i start with game development when i'm terrible at art and 3d modelling?
I've wanted to try and make my own game for a while now but i'm i'm terrible at art, textures and 3D modelling but i want to learn it so has anyone got any pointers to get started with the whole shebang?

# Answer
> 1 votes
What do you want to do exactly? I mean, do you share any quality or have any qualification to do something in particular? For example i'm terrible at modeling and art but i'm not bad programming, then i'm focused on 3D engines(collisions, rendering, optimizations, algorithms...). The thing is to find what you are good at and you enjoy.

If you want to learn about my area i can easily give you a lot of information and recommendations.

---
Tags: game-design, textures, software-engineering, art, 3d-modeling
---


title: Find the closest point on a ray

text:
# Question
Title: Find the closest point on a ray
I've got a ray defined by P1 and P2, and then a target P3, and I want to find P4. How do I go about this? I've come to understand that I should use vector projection, but I can't get it to work. Any help? I'm using C# and XNA.

# Answer
Closest distance point segment:

```
float SqDistPointSegment(Point a, Point b, Point c)
{
    Vector ab = b – a, ac = c – a, bc = c – b;
    float e = Dot(ac, ab);
    // Handle cases where c projects outside ab
    if (e <= 0.0f) return Dot(ac, ac);
    float f = Dot(ab, ab);
    if (e >= f) return Dot(bc, bc);
    // Handle cases where c projects onto ab
    return Dot(ac, ac) – e * e / f;
}

```

Source: Christer Ericson Real Time Collision Detection. You can find all kind of algorithms for this things in that book, take it, it is a must.

Anyways to see the distance of a point to vector is easy just do:

vector.normalize().dot(point);

It gives you the distance. The vector must be normalized.

With this distance you can multiply it for the normalized vector and added to the P1 to get P4. Then:

```
Vector rayDir = (P2 - P1).normalize();
P4 = P1 + rayDir.Dot(P3)*rayDir

```
> 5 votes

---
Tags: c#, xna, mathematics, vector
---


# Question
Title: How do I make a highscore database for Unity?
I have been looking around, but I haven't found the perfect answer, yet.

I want to to send scores from Unity to a database, without a username, and display the high scores in the highscore menu. How do I do that?

# Answer
> 0 votes
There are plenty of pitfalls in designing a system like this. If you are opening up a path to post high scores to a server, you are opening it for everyone - not just your client application. The general rule of thumb is this kind of territory is to **never trust what the client is telling you**. As soon as you hand the application to someone you've basically given them the key to posting whatever they like.

For a start, you're going to need some way of accepting requests from over the internet - you're best bet is probably using HTTPS. You should also have a database that this interface can connect to (never directly expose your database to the open network, always write a middle-ware application to interface with the outside world and your database). You'd probably be best off with something like a PHP server, or a NodeJS server, or really any back-end technology that is relatively simple and can both connect to a database and accept HTTP requests; personally I'd choose NodeJS but that's because I like it and think it would serve this purpose well.

Next you'd probably want to start implementing a RESTful service on it, you'd need the ability to retrieve high scores, the ability to add them and *possibly* the ability to update them if you feel it is necessary. You'd simply make a `POST` request to your web-facing server, and your server's middle-ware would interpret the data and do what is necessary (either fetching the requested high scores, or inserting a new one in this case).

You could roll-your-own in this case and forgo using the ideas behind REST, but I'd suggest following some form of best practice.

# Answer
> 0 votes
Actually the answer is not short or concist of single line. You required Details guide line/tutorial for that and you can achieve it in two ways

You either require your own server with your code logic(back-end) or you can use free firebase as a backend.

1. Details guide given by unity wiki Server Side Highscores
2. Or you can check Firebase with unity

# Answer
> -1 votes
I'd do this by:

1. Get a server running with the ability to host on the open net (virtual or otherwise - virtual would probably be easier/cheaper at this stage.)
2. Install a LAMP (Linux, Apache, MySQL, and PHP/Python/Perl) stack on it
3. Build a small HTTP interface that updates, or inserts, into the database a name & score
4. Build a small HTTP interface that returns the high score table

Display in game, using the UI & control with http requests.

That gets you up and running.

Better way, but more effort, is to integrate with Steam and to use their high score table (Leaderboard) API

---
Tags: unity, c#, databases, php, mysql
---


# Question
Title: How can I give the mouse position to my GameObject nicely?
I am making a basic Asteroids game in SFML, and I want the Player ship to always look at the mouse. I have a LookAt(x,y) function which works, but I am not sure how to get the mouse position from the Player's Update() method!

I see several possible solutions to this:

* The LookAt(x,y) function is changed to be public, and instead of the Player calling it within its own Update() function, it is called externally (maybe in an Update() function in the GameManager class, which has access to both the Player and the InputManager)
* The Player is given a pointer to the mouse position on creation, which is updated every frame in the InputManager on MouseMotion
* The Player is given a pointer to the InputManager, which it can then use in the Update() function to access mouse coordinates.
* The InputManager class is made 'static', and the Player accesses the mouse position directly via InputManager.GetMousePos()

Ideally I want the Player's behaviour to be contained. I don't feel that it is neat to create new properties, functions or callbacks outside the player class just so that the player has access to two integers. The last solution (making the InputManager static) seems neat to me (especially since it only requires 1 new line of code in the Player class, and doesn't require the Player to hold onto new properties), but I've heard that using singletons is an 'anti-pattern' and should be avoided!

# Answer
It sounds to me like you want to look into the Components design pattern. This link does a much better job of explaining it than I could ever hope to do however in order to make sure this answer isn't useless in case the link ever dies I'll try to summarize it briefly.

Using a component pattern means that an entity (your player) can interact with another system in your engine(input manager) without ever having to really know each other. This gives you a neatly decoupled system where you could later swap the input component without having to change the player entity or if you wanted to have an enemy ship in your game as well you could use the class already created for the player, just switch the input controlling component from a keyboard/mouse to an AI.

There are of course multiple ways of doing this - my preferred one is to have each Entity have a list of Components that it iterates over each update and let those Components decide what happens to the Entity. This is excellently summarized in the above link as:

> A single entity spans multiple domains. To keep the domains isolated, the code for each is placed in its own component class. The entity is reduced to a simple container of components.

In your case I'd say the Pros would be that it looks neat and is extensible as well as works great if you do more components such as physics/sound/etc and the Cons would be it's a lot of new code if you don't plan to do more with it. If you just want a quick and dirty solution I would go with making the input manager a singleton and just call it a day.
> 1 votes

---
Tags: c++, software-engineering, sfml
---


# Question
Title: Rigid body physics resolution causing never ending bouncing and jittering
I'm trying to make a fairly simple, impulse based rigid body simulator as part of a Uni assignment. I'm using bullet physics to perform collision detection, and my own code to perform collision resolution.

My physics engine runs as follows:

Loop rigid bodies and do the following:

* Apply gravity to the body's velocity, and damping to the body's velocity and angular velocity.
* Integrate the position and orientation of the body from the previous frame to the next frame.
* If the object is moving fast, perform a convex cast with bullet from the previous position and orientation to the new position and orientation. If this cast hits something, move the object up to the contact point (with an allowed penetration of 0.04, because for some reason if I don't allow the penetration, bullet will sometimes not generate contacts correctly later).
* Loop over the current contacts for each object. Find the deepest contact for each body and move the body along the contact normal by this distance.

Perform collision resolution (done once):

* Perform discrete collision detection to generate contact points.
* Loop over each of the contact manifold points and generate an impulse for each point. Apply the impulse directly to the velocity and angular velocity of the associated rigid body(s).

This system works fine without gravity, but when I add gravity, one of my bodies never comes to a rest. The following short video should illustrate this pretty well:

https://www.youtube.com/watch?v=E4B8Lo7xnqc The first part shows the simulation without gravity (all good from what I can see) and the second part (around 0:42) shows what happens when I introduce gravity.

It appears as though the body is somehow gaining too much angular velocity when it collides with the ground, which forces it to continue bouncing around indefinitely. If I manually scale the angular velocity impulse back by a large amount (like 0.1) it reduces the bounding considerably, but doesn't eliminate. Plus, it seems hacky to just simply reduce the angular velocity like that.

The following is what I use to generate the impulse vector against static objects:

```
Vector CalculateLinearRotationalImpuleSingular(const PhysFrame& state,
const PhysConstants& constants,
const Vector& r,
const Vector& impactNormal)
{
    Vector impulse, rxn;
    const float restitution = 0.85f;
    const float restitutionTerm = -(1 + restitution);
    float lt, ut;

    // r x n
    VectorCrossProduct(r, impactNormal, rxn);

    // Bottom term
    Mat3::MatrixMulVector(state.m_WorldInverseInertiaTensor, rxn, impulse);
    lt = VectorDotProduct(rxn, impulse) + constants.m_InverseMass;

    // Top term
    ut = VectorDotProduct(impactNormal, state.m_Velocity) * restitutionTerm;

    VectorMultiply(impactNormal, ut / lt, impulse);

    return impulse;
}

```

This is my implementation of this equation:

And the following is how I'm applying the impulse of that equation to my rigid body:

```
void RigidBodyPhysics::ResolveContactWithStatic(RigidBody* rb, const Vector& contactPoint,
    const Vector& contactNormal)
{
    // Do calculation with one rb
    Vector worldCOG, r1, impulse, angMomentum;
    PhysFrame& state = rb->GetState();
    const PhysConstants& constants = rb->GetConstants();

    worldCOG = CalculateWorldCentreOfMass(rb->GetGameObject()->GetOrigin(),
        state,
        constants);

    // work out r
    VectorSubtract(contactPoint, worldCOG, r1);

    impulse = CalculateLinearRotationalImpuleSingular(state,
        constants, r1, contactNormal);

    // Apply linear velocity change
    state.m_Velocity += (impulse * constants.m_InverseMass);

    // Apply angular velocity change
    VectorCrossProduct(r1, impulse, angMomentum);
    angMomentum = state.m_WorldInverseInertiaTensor * angMomentum;
    state.m_AngularVelocity += angMomentum * 0.5f;
    // If I add this 0.5 it reduces the jitter, but seems mathematically wrong.

    return; // All done
}

```

Does anyone know why this super bouncy jittering might be occurring? If needed, I can post more source code snippets, just let me know what you need to see!

# Answer
I worked it out. The trick was for me to remove any velocity introduced by gravitational acceleration over the last frame. This stopped the contacts from producing a separating force when they should, in fact, be still on the ground.

This presentation helped me work it out: http://www.cs.qub.ac.uk/~P.Hanna/CSC3049/resources/3.6.%20Contact%20Resolution%20-%20Resting%20Contacts%20and%20Friction.pptx
> 0 votes

# Answer
It's on the right track but there are a couple of odd things happening. Firstly the body doesn't come to rest, it continues gliding and if you are applying damping that shouldn't happen.

Before anything, just have the object in the air, give it an impulse along of say 1m/s and don't process any collisions. You should see it damp down to nothing and then come to rest. Whereas in the video the block never stops it continues floating ad infinitum - unless the damping is so small as to not really effect anything.

The next thing to do, same test, is to test that with slow movement & angular that it comes to a rest. If it does not then before doing anything more complex I would fix that.

With that working the next thing I would do is rig up the scene such that the object is at 45 degrees, drops to the floor, and then rotates to land flat. From that you know exactly what is going into the system, and what you should see coming out.

You would expect to see nothing happening until contact with the floor then you would expect to see an angular velocity along X only which will then die away to nothing as it lands on the floor. If you see anything else then you can debug through to see what is causing that.

Also don't forget when dealing with the world that the angular is applied to the object only, given the world is presumed to have infinite mass for the purposes of the calculations.

Your equations look correct. I've not checked the code thoroughly but this looks like some sort of bug rather than anything fatally wrong.
> 0 votes

---
Tags: physics, bullet-physics, physics-engine, rigid-body-dynamics
---


# Question
Title: Draw a sprite when a key is pressed in LibGDX
I'm working with LibGDX. How can I draw a sprite when a key is pressed? I have tried with the following, but it doesn't seem to work.

```
if (Gdx.input.isKeyPressed(Input.Keys.X)) {
    batch.begin();
    sprite.draw(batch);
    batch.end();
}

```

# Answer
You could have a boolean that you set to true when the key is pressed in your update method:

```
 boolean drawSprite;
 if (Gdx.input.isKeyPressed(Input.Keys.X)) {
      drawSprite = true;
 }

```

And then in your render method:

```
batch.begin();
if(drawSprite == true) {
 sprite.draw(batch);
}
batch.end();

```
> 1 votes

# Answer
I assume you are using `Sprite` class from libgdx and the sprite you created is working fine? And the only problem is you cannot show the sprite when a key is pressed.

```
@Override
public void update() {

    // the input is pressed once even you are still holding the button.
    if(Gdx.input.isJustKeyPressed(Input.Keys.X)) {
        sprite.setVisible(true);
    }

    batch.begin();
    sprite.draw(batch);
    batch.end();

}

```
> 0 votes

---
Tags: libgdx
---


# Question
Title: Using large textures on limited hardware
I've run into a problem where some of the models that I'm loading can have very large textures (2000x2000 for example). While my desktop computer can load them just fine, my laptop gets a segfault at the `glTexImage` call. I've thought of a couple of things I can do in this situation:

1. Before giving the image to OpenGL, I could downscale it so it's below the max texture size, but I'm not sure how to then stretch the image to its original width and height
2. I could also outright refuse to load the texture, and replace it with a generic repeating texture, like Valve's black and purple grid, but this isn't at all reliable or desired

Are these two options viable? How is it done with game engines like Unity or Source? Are there any other options that are better than my ideas?

# Answer
> 1 votes
I had encountered the same issue when handling textures of size 2048x2048 in iOS. It would simply crash because of memory constraints.

As you stated, i had a threshold of 1024px for either width or height of the image. If it crossed the threshold, i simply downsized it to another image preserving the aspect ratio. There would be platform based image resize APIs which would take care of this. Or else you can definitely find some C code which does this.

One another option is to convert the textures to PVRT format offline & use them. They are very lightweight. There will be loss in quality & we'll have to make sure the target hardware supports PVR textures.

# Answer
> 0 votes
The best thing that you can do not use that large objects. Using them can cost some problems, and not just with texture sizes. This is a list of problems that it can bring:

* Collision detection. If you use too large objects the BSP Tress gonna need to chop bounding collisions or it can turn inneficient.
* Huge amount of time wasted drawing textures and vertex that wont be at screen. You can solve it with a Frustum culling special for this type of objects, like we usually use for terrains
* If you use frustum for this type of elements, the time that it needs to actually check all vertex.
* The ammount of memory picks for loading or deleting this textures can bring you another problems.

Large textures are good just for animating, but even with that if the resolution required is too large, is better chop them in smaller textures and use a index map.

You can also scale the objects, but be careful with the bounding for collisions for this object.

---
Tags: opengl, c++, textures
---


# Question
Title: Maze or puzzle algorithm for something similar to noodles
Not sure if anyone has played Noodles at all https://itunes.apple.com/gb/app/noodles!/id967624193?mt=8 but it is a simple puzzle game, that involves rotating tiles until they link up. The tiles are either 4-sided or 6-sided and each tile can have 1 of a set number of 'pipes' including end pipes. There's only one solution which you reach by joining all the pipes together to a special 'starter' pipe which can take the form of any of the other pipes. There's also no loops.

What type of algorithm would someone use for this? I thought it could perhaps be a maze algorithm, but I'm struggling to understand how you would go about this.I think it's because in essence there aren't any walls, just different styles of connectors. But is this in essence a perfect maze? Does anyone have an idea of a starting point for an algorithm to accomplish something similar?

I'm not specifically looking for code, but a help in the right direction to identify a relevant algorithm or how someone might go about this. Though I have tagged this 'ios' as that's what I would ultimately be targetting

# Answer
A standard maze-generation algorithm would work just fine in this case. There *are* walls. What you see are just the paths through those edges which are not walled. A wall is every edge which is not connected. I added the "invisible" walls to one of the screenshots of the example app you posted:

1. Generate a maze with your favorite maze generation algorithm. There are lots of algorithms to experiment with.
2. For each tile, check how many edges are not walled and generate the appropriate tile.
3. Rotate all tiles randomly
4. To check the win-condition, **do not** check if everything is rotated as it was before shuffling. There might be more than one valid solution (unless you are using a maze generation algorithm where you can mathematically prove that this is impossible). Do a flood-fill instead and check if all tiles are covered.
> 0 votes

---
Tags: ios, puzzle, maze
---


# Question
Title: How add a sprite to canvas using JavaScript?
I'm very new to sprites and I'm trying to figure out how to use them. I want to use a simple solution. Something like this:

var c = document.getElementById ('canvas) var ctx = c.getContext ('2d'); ctx.upload('image/testImage');

I'm very sorry if the solution is an obvious one, I'm not very good at JS. I am using pure JavaScript, I don't really like using engines.

# Answer
It is indeed really easy and you could find it easily by yourself...

```
image = new Image();
image.src = "path";
ctx.drawImage(image, ...);

```
> 1 votes

# Answer
A sprite in most setups is just a normal basic object (position, rotation, etc) that renders as a quad with some sort of texture. In a 2D canvas, if you have your own basic object class, you would want to render your sprite using CanvasRenderingContext2D.drawImage(...). To quote from MDN the parameters are:

> void ctx.drawImage(image, dx, dy);
> void ctx.drawImage(image, dx, dy, dWidth, dHeight);
> void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
> **image**
> An element to draw into the context. The specification permits any canvas image source (CanvasImageSource), such as an HTMLImageElement, an HTMLVideoElement, an HTMLCanvasElement or an ImageBitmap.
> ...

The image parameter has quite a few possible classes that you can use as your image source the most used of those being `HTMLImageElement`. Here's how it's used.

```
var img = new Image(); //Creates an HTMLImageElement
img.src = "localhost/myImg.png";
img.addEventListener("load", function() {
    ctx.drawImage(img, 0, 0);
});

```

Note: When loading external images you must deal with cross origin requests. To get it to work, you'll need to CORS enable your image or it will taint your canvas and you won't be able to render it.
> 1 votes

---
Tags: javascript, sprites, image
---


# Question
Title: Slow down in the same time over different distances
I'm trying to slow down a object over different distances in the same time, say 3 seconds.

My slow down code is.

```
function lerpSpeed (speed: float, lerpSpeedTime: float)
 {
     incomingFlightSpeed = flightPathScript.flightSpeed;

     i = 0;
     while(i < 1)
     {
         i += Time.deltaTime/lerpSpeedTime;
         i = Mathf.Clamp(i, 0, 1);

         flightPathScript.flightSpeed = Mathf.Lerp(incomingFlightSpeed, speed, i);

         yield;
     }
 }
```

So I call it with.

```
 waypointScript.lerpSpeed(1,(totaFlighpointsDistance/flightSpeed));
```

In the picture below I've draw a bezier curve and at the last 8 flight points (the red and yellow spheres) I want to start the slow down from the yellow sphere to the last red sphere.

I get the distance in between each of the last 8 flight points and total them up to give me the total distance, I understand to get the time it will take to travel that distance is time = total distance/speed, but as I'm slowing the speed in my function above this will not work.

And because every bezier curve I generate is different, some stretched out, with total distances sometimes ranging from 30 to 8.

So I'm a bit stuck here, thought I'd get this one, but unless I'm missing something simple I can't get my head around it, so any help would be greatly appreciated, thanks.

# Answer
> 0 votes
I've attached a few sample calculations below. The first two are linear burn downs, which isn't quite what you want, but it's good to see the math. Basically, each time you multiply the current speed by a reducing fraction that is a function of the number of stops you have. The last frame is always to `Lerp` to 0. All examples have two calculations, one from a starting speed of 30, one from a starting speed of 78.

```
Linear
Speed   30  26.25   22.5    18.75   15  11.25   7.5 3.75    0
Delta       -3.75   -3.75   -3.75   -3.75   -3.75   -3.75   -3.75   -3.75
Math        7/8 6/7 5/6 4/5 3/4 2/3 1/2 zero out

Speed   78  69.3    60.6    52  43.3    34.6    26  17.3    8.6 0
Delta       -8.7    -8.7    -8.6    -8.7    -8.7    -8.6    -8.7    -8.7    -8.6
Math        8/9 7/8 6/7 5/6 4/5 3/4 2/3 1/2 zero out

```

These sets are burn downs over time, each giving you the speed to `Lerp` to by the next point. The first is a four-second burn down, the second is a three-second burn down.

```
Multipled by 3/x (4 second burn down)
Speed   30  11.25   4.21    1.58    0
Delta       -18.75  -7.04   -2.63   -1.58
Math        3/8 3/8 3/8 zero out

Speed   78  26  8.6 2.8 0
Delta       -52 -17.4   -5.8    -2.8
Math        3/9 3/9 3/9 zero out

Multipled by 2/x (3 second burn down)
Speed   30  7.5 1.875   0
Delta       -22.5   -5.625  -1.875
Math        2/8 2/8 zero out

Speed   78  17.33   3.85    0
Delta       -60.67  -13.48  -3.85
Math        2/9 2/9 zero out

```

---
Tags: unity, ios, unityscript, lerp
---


# Question
Title: Conceptual question regarding Belief-Desire-Intent agent
I've been researching the Belief-Desire-Intent model and the way they used it in the original Black and White Game(which is the same, but they also defined decision trees as opinions).

I have a question about the distinction between opinion and belief.

From what I understand, beliefs are linked lists in the form of attribute: value.

So let's say a tree would be something like: Condition: Inanimate Type: Plant

So let's say I try to apply the command cut on it and the npc cuts down the tree in like 2 turns, by doing 50 damage each turn. So the newly formed belief is that the hp of a that tree is more than 50.

From what I understand, that this is now a newly formed belief, so the new belief about the tree would be: Condition: Inanimate Health: \>50 Type: Plant

What about the fact that the npc now knows it takes 2 turns to cut down the tree, is that now a newly formed belief or an opinion? If it's not, what kind of opinion could be formed out of that?

Help from anyone who's dealt with this would be appreciated as I'm finding it hard to find open source code examples of this.

# Answer
It would seem that you are missing some beliefs from the model.

There's two reconciliations I see:

## NPC Does 50 Damage is an Existing Belief

While one belief, that the tree has \>50 HP is true. It's based on an existing belief that the npc does 50 damage. So, you may be missing the npc's beliefs of its own abilities.

Then there is a second belief that is missed, and that's that the tree has \<=100 HP. If the npc believes it does 50 damage, and has to use two turns to destroy the tree, then the new belief is that the tree has to have less HP than or equal to 100.

## NPC Only knows how many turns to cut down a tree

The other possibility is that the npc will not know how much HP the tree has, but rather how long it takes for them to cut down the tree. Then their beliefs about many things will be relative to turns, and not relative to the underlying HP stats. It can only build beliefs based on what it observes.

In which case the belief would be described as taking 2 turns to cut down the tree.

---

I'm not very familiar with the actual system, but from a logic stand point that seems to be the issue. You can't believe the tree has any specific number of HP, unless you have some way of knowing how much damage you do.
> 2 votes

---
Tags: game-design, ai, software-engineering, game-mechanics
---


title: Isometric painter's algorithm problem

text:
# Question
Title: Isometric painter's algorithm problem
*Note: I dont use tiles, I use 3D Polygons :)*

I'm currently working on a real-time renderer for scanned real life objects. My main goal is to have an isometric viewer with the simple ability to rotate the object.

This alone is a simple problem. I basically had the full solution for it, but I wasn't happy with the performance at all.

As you might know, software rendering based on the CPU is slow (but I don't want to code a game engine, just a small viewer which should be okay with a low poly count like \< 10000) but for what i need it works surprisingly good.

The only part where my renderer is toooo slow is the z-buffer (multiple seconds for a 3000 poly obj). Mainly because it loops x*y*objects\*polygons.

Currently I'm using some sort of painters algorithm to draw polygons one after another, which brings me some problems: https://youtu.be/PDq4xtrgoi8

As you can see the distances per poly are calculated very poorly, just the center of the poly to world point 1000,1000,1000.

My question is not just about the pointers algorithm but I'd love to use a **minimal** failing method of drawing the polygons in a specific order rather than calculating every pixel by z-buffering.

If you have other simple methods which work fast on a CPU, I' d really appreciate hearing about them! :)

# Answer
In this book, Mathematics for 3D Game Programming and Computer Graphics - Eric Lengyel chapter 9, you can find information that can be usefull for you. Here it is a screenshot of the chapter.
> -5 votes

---
Tags: rendering, draw-order, software-rendering
---


# Question
Title: Could I implement MakeHuman into a UE4 game as a character creator?
Would it be possible to take MakeHuman and put it into a game made in Unreal Engine as a character creator?

Of course many unnecessary features would have to be removed, but would it work at all, and would it be easier than making such a system from scratch? MakeHuman is open source so there shouldn't be any legal issues.

# Answer
Practically speaking, no.

MakeHuman is a decently large, complex code base **written in Python** against particular specific UI APIs and conventions. Unreal is a very large, complex code base **written in C++** against completely different UI APIs and conventions. It would probably be extremely difficult to "integrate" MakeHuman into Unreal as a runtime character generator. Prohibitively so.

You'd almost certainly have an easier time building your own runtime character generator directly inside Unreal.

Further, just because MakeHuman is open-source doesn't mean there will be no legal issues. MakeHuman is released under a specific license (AGPL) which imposes certain requirements on its use. Your intended use may violate those requirements, and the license for MakeHuman may also conflict in various interesting and subtle ways with the license for Unreal. You'd want to double-check the licensing very carefully, possibly getting a lawyer to review it and your intended use.
> 1 votes

---
Tags: unreal-4
---


title: Indexed draw vs draw array

text:
# Question
Title: Indexed draw vs draw array
Lately I wondered, which draw command is faster, `drawArrays` or `drawElements`. I know difference between them, `drawArrays` just draws every vertex in the same order they were provided, and `drawElements` draws vertices based on the provided indices. But I'm still curious which command is faster, or when should I use `drawArrays` instead of `drawElements` and vice-versa.

# Answer
> 4 votes
**It depends**.

Using glDrawElements requires an index buffer which is an extra, but does allow for removal of duplicate vertices, concatenation of primitives and reuse of vertices via the hardware vertex cache.

Using glDrawArrays is simpler but doesn't have these advantages.

Desktop hardware has been optimized around glDrawElements with GL\_TRIANGLES for quite some time - Quake 3 pushed it as the preferred rendering path, so that's the timescale we're talking about.

Some mobile hardware may still have glDrawArrays and GL\_TRIANGLE\_STRIP as the optimal path.

As always, benchmark on your target platform(s).

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


# Question
Title: How can I create a world map like Mario 3's?
I want to create a world map similar to the type that Mario 3 on NES uses

where Mario can walk between levels (nodes?) by pressing up, down, left and right on the controller, and Mario can only pass through a level when it has been cleared.

What I have so far is a list of level nodes:

```
std::vector<SLevelNode*> NodeList;

struct SLevelNode
{
    CVector2D Position;
    CVector2D Size;
    CVector2D Origin;

    int ID;
    int Type;

    SLevelNode* pNeighbourNode[4];
};

```

The level node contains stuff like position, the type of level node (ground level, water level, castle level and so on). It also contain a neighbor node array, which in my case is 4, since I want the player to, eventually, be able to walk from a level node in all four directions. A level node might only have two ways of travel though, left and right for example.

Besides the level node, I also have a path piece, which is a piece of road between the level nodes:

```
struct SPathPiece
{
    CVector2D Position;
    CVector2D Size;
    CVector2D Origin;

    int Type;

    float Rotation;
};

```

The type variable is either a horizontal piece, a curve piece, a bridge piece and so on.

So far my character can walk between the level nodes by dragging a 2D vector between them, that the player traverse with. I want, however, the player to start walking from a level node, walk through the road pieces (between the nodes) and end up at the goal level node. I'm not sure how to make the level nodes "know about" the road pieces that is placed between the start node and the goal node. Have a list of path pieces in each level node?

I have though about using A\* and make a path finding map but it feels like it's over-complicates things.

I would like some help on how to achieve this.

# Answer
I would adjust SPathPiece so that it knows about the nodes it connects.

```
struct SPathPiece
{
    CVector2D Position;
    CVector2D Size;
    CVector2D Origin;

    int Type;

    float Rotation;
    SLevelNode * ConnectedNodes
};

```

I would then hook up the nodes that the road connects. For the pawn to walk I would put in a basic FSM

* stateLeaveCurrentNode
* stateWalkPath
* stateEnterDestinationNode

When you call WalkToNode(NodeToWalkTo) it would search the road path pieces for the road that connects both of the nodes (current node, next node) and cache it.

The state machine would then walk from the current node to the path piece start. It would then walk the path, then when it gets to the destination node it would walk to centre of the node.

Another alternative is to adjust SLevelNode so that it carries the list of road pieces it needs.

```
struct SLevelNode
{
    CVector2D Position;
    CVector2D Size;
    CVector2D Origin;

    int ID;
    int Type;

    SLevelNode* pNeighbourNode[4];
    SPathPiece* pConnectingRoad[4];
};

```

For the finding of route between nodes you could use a recursive search for the destination node. i.e.

```
IsDestimationNodeInThisPath(Destination,Path)
{
    if(Path.ConnectedNode[0]==Destination)
    {
           return true;
    }
    else
    if(Path.ConnectedNode[1]==Destination)
    {
        return true;
    }

    if(!IsDestimationNodeInThisPath(Destination,Path.ConnectedNode[0])
    {
        if(!IsDestinationNodeInThisPth(Destination,Path.ConnectedNode[1])
        {
             return false;
        }
    }
}

```

The other thing you could do is adjust the above so it increases a reference count and return the length of path, the actual connecting nodes is then returned. That way you'd walk the quickest method rather than the first one found.

You'd also need the current node list so that if you visit the same node twice you bail out and return false because you are in a circular list.

This will go horribly wrong though if you increase the size of the map to much because it'll chew through stack.
> 3 votes

---
Tags: 2d, maps, path
---


title: How to free the GPU from a long task?

text:
# Question
Title: How to free the GPU from a long task?
I'm developing an application that uses the GPU. Some tasks might be rather long (like a fragment shader with a loop). I have the impression that I can make the entire OS visually freeze by asking the GPU to perform a job that doesn't end. Of course, I'm not doing this on purpose, but when that accidentally happens, I have to force power off my machine and this is very difficult to debug.

Some questions:

1. Is this behaviour normal? Or could this be a bug in the hardware or driver?
2. Is there a technique to recover from this without force stopping my machine?
3. ~~Since the OS is still functioning (only not rendering), I could try to ssh into my machine and kill the process. Would that free the GPU from its job?~~ **Update:** I tried to ssh into my machine and `sudo kill -9 *pid*`, but didn't work.

I would like to know if there is an OS independent answer for this. If there isn't, my setup is macOS, with OpenGL (running on Intel HD Graphics 3000).

# Answer
> 3 votes
The short answer is: you can't right now. (possible work-around below)

Newer GPUs can do preemtion (context-switching) to prevent the entire machine from freezing when running long GPU programs, older GPUs don't support this.

Your OS also needs to support this as well as the specific drivers.

For example Windows 8 WDDM 1.2 requires this support in drivers ( https://msdn.microsoft.com/en-us/library/windows/hardware/jj553428(v=vs.85).aspx )

But even then you can't stop the GPU yourself. When this is supported your app can be killed externally but it does not allow your own application to directly abort the GPU operation.

---

**A possible work-around** would be to break down your shader loop into multiple shader passes and synchronize draw calls with the CPU (greatly reducing overall performance) so that the CPU can stop sending draw commands and also allowing the CPU to yield to other programs.

Note that it is possible the GPU driver will not yield, instead batching up all commands, until a frame buffer access is done or some kind of feedback information is requested from the driver.

Reading 1 pixel from the frame buffer between passes should be sufficient to cause a pipeline stall (GPU yield).

**Using OpenCL instead is another option.** OpenCL execution kernels are expected to take a fairly long time compared to pixel/fragment shaders so it is more likely that the drivers will support preemption and/or the driver will not use all available cores for OpenCL tasks, leaving some for the OpenGL tasks so the drawing can still crawl along.

**There is no guarantee any of these work-arounds will work on all GPUs and all drivers.** Some drivers are very performance-aggressive and will not yield for a long time to maximize the frame rate of the application with focus.

---
Tags: opengl, macos, hardware
---


# Question
Title: How closely can a game legally resemble another?
Most games build on other games' successes and many are downright clones. Where is the limit of imitation before legal issues come into play? Is it down to literary or graphic work like characters and storyline that cause legal problems, or can someone actually claim to own gameplay mechanics?

There are so many similar clone games out there that the rules are probably very slack or nonexistent, but I'd like to hear the views of more experienced developers / designers.

# Answer
I am not a lawyer and this is not legal advice. These are things I've heard many times over and have no reason to doubt.

Game mechanics cannot be copyrighted or protected in any fashion.

I could make a game called "Crystallized" that was Bejeweled, in every imaginable way, and as long as I didn't copy the art from Bejeweled (either directly, or by drawing new art that just happens to be nigh-identical) I'd be totally fine.

Game mechanics have been copied often enough that, if this weren't the case, I have no doubt we'd have heard about it by now. Game design is pretty much one giant incestuous ball of borrowing, and, honestly, is better for it.

Keep in mind that you can be sued for anything, even if you're not breaking any contracts or laws, and they might win. But I've never heard of that happening with regards to game design.
> 153 votes

# Answer
Other answers have covered trademarks and copyright pretty well, but do not forget patents. Many game mechanics developed in the early days of gaming are patented. The 2 that I know of are minigames while the main game loads (Ridge Racer), and jump-in multiplayer (Gauntlet). That is why you almost never see these features in any games, even though they are both great ideas. In theory if you want to use these mechanics then you have to pay a royalty to the patent holder, which could be expensive. In practice however, it is very unlikely to be enforced unless you are making a million-dollar type game.
> 25 votes

# Answer
Game mechanics are not subject to intellectual property controls. Names can be trademarked and any game code or assets are subject to copyright protection. There is some legal precedent for going after games that are "close" (http://en.wikipedia.org/wiki/Lexulous) but that was in an Indian court so I know much less about their IP laws (see also: the various FOSS StarCraft clone projects, most threatened with suits because they had "craft" in the name).

Trademark law generally draws a distinction based on if an "average consumer" could be mislead into thinking you were related to the other property. Copyright is much simpler since it only covers concrete works. If you redrew every sprite from your favorite game they would not be violating any copyrights (but might be violating a trademark if it is something high profile).

Recently some companies have tried to bring patent suits against some big-name game companies, claiming things as outlandish as they have a patent for the concept of text chat. Time will tell as to if these are a real threat, but until your revenue is in the millions I wouldn't worry about it.
> 15 votes

# Answer
Foreword: Anything related to laws will always be in a gray area, because the case outcome ultimately comes from a handful of people.

Others have accurately pointed out that game code and assets fall under copyright law and that product, company, etc. names fall under trademark law. However, although others have pointed out that you cannot copyright game mechanics, this isn't 100% true.

Let's look at the legal history of Tetris, a game often cloned by new game developers.

> In mid-2006, and in late 1997, TTC's legal counsel sent cease and desist letters to Web sites on the basis of Tetris-type games infringing the "Tetris" trademark, trade dress, and/or "look and feel" copyright. Around 2009, TTC and Tetris Holding LLC brought legal action against BioSocia, Inc., on the grounds that BioSocia's "Blockles" game infringed on proprietary rights that were held by TTC and Tetris Holding LLC. On September 10, 2009, the legal case against BioSocia was resolved, with BioSocia agreeing to discontinue making the "Blockles" game available to the public. In May 2010, TTC's legal counsel sent cease and desist letters to Google insisting that 35 Tetris clones be removed from the Android Market. A US District Court judge ruled in June 2012 that the Tetris clone "Mino" from Xio Interactive infringed on the Tetris Company's copyrights by replicating such elements as the playfield dimensions and the shapes of the blocks.

Source: http://en.wikipedia.org/wiki/Tetris#The\_Tetris\_Company

Tetris and Mino

So are game mechanics copyrighted? The answer, as with many legal issues, is *maybe*.

Read more about Mino vs Tetris here.
> 15 votes

# Answer
Great question, what better way to ask about copyright than through games, which encompass all forms of media and IP.

**First** off, be aware that **an idea cannot be patented**.
**Second** be aware that the copyright depends on the national law you are recommended to adhering as a natural citizen. There are for instance some **difference in interpretation of Fair Use in the US vs the EU**.

> Fair use is the most significant limitation on the copyright holder's exclusive rights (United States Copyright Office, 2010, para. 1)

The UMUC Library, has set up a well comprehensible site on the matter:

**What Can be Copyrighted?**

* Fixation: the work must be physically stored somewhere. You cannot patent your breath.
* Originality: to some degree. Modification may render a work to be considered original.
* Minimal Creativity: a new concept should be obvious

**Lastly**, shamelessly quoting, the *HM Chandler "The Game Production Handbook 2nd Ed", March 18, 2010 Jones & Bartlett Learning* under the banner of *fair-use*:

> Several basic types of IP are legally valid: copyrights, trademarks, trade secrets, and patents. The differences depend on how the idea is expressed. Producers should be familiar with the differences between these, especially independent producers working with a publisher. If the publisher is interested in your game and is ready to sign a deal, they will most likely demand that the copyright in the game be conveyed to them so they can create derivative products and re- produce the product free and clear.
> 8 votes

# Answer
I think this article puts it best, by presenting 5 copyright cases, including the Tetris and Yeti Town cases: http://www.gamasutra.com/view/feature/187385/clone\_wars\_the\_five\_most\_.php

In conclusion, if you're doing a total and complete rip off, you're in trouble these days, but you weren't 10 years ago.

In addition there are patents. Patents for concepts in games don't apply in many countries, but due to the way these courts work, if you do business in the respective country you're in trouble. https://www.google.ch/search?q=car+racing+game+patents It's likely that you could challenge and void many of these patents in court if you have half a million to spare, per patent - or you could just pay the patent holder a fraction of that and be fine.

Finally, there are trademarks. Universal did sue Nintendo because it's apparently easy to confuse Donkey Kong and King Kong. While Universal did lose badly, Nintendo first had to be willing to enter an expensive legal battle. If you don't have the funds, you can't defend against these kinds of legal attacks.
> 6 votes

# Answer
There is some fuzziness when it comes to the law concerning things like **spell names**. At that point, it really comes down to how closely tied the name is to the franchise. If the brand that is being pulled from has explicit claim upon a name like that, it would likely be under trademark rather than copyright so that is what you'd want to look for.

There is this great site that I found that has an entire article on legal issues for game developers with the different types of IP explained in detail.

Hopefully that helps with the more detailed parts of avoiding IP claims.
> 3 votes

# Answer
The answers above are all pretty much spot on, unless you're copying something closely, you should be okay.

But, and this is a big but, just because you are doing everything right, it doesn't mean you won't get C&D'd, or be sued. Unfortunately, a lot of business and individuals use the legal system as a bludgeon against competitors and will often issue cease and desist orders to try and get a competing product taken down, or head straight to a lawsuit.

Much of this behaviour depends on the cost of a lawsuit and the willingness of the competitor to spend the money and fight. Not many are. Even big companies often settle when faced with a bogus patent or IP lawsuit because it's easier and less costly.

So, the short answer is that you should be okay most of the time, but you can't be guaranteed not to be the target of a frivolous lawsuit.
> 0 votes

# Answer
Yes, but there are so many similar clone games out there that the rules are probably very slack or nonexistent
> -3 votes

# Answer
I have seen Modern Combat 5 use the "sapper" soldier class. It is almost identical to the "engineer" soldier class of Team Fortress 2. They are similar, as both can deploy turrets that can shoot automatically at any nearby enemy players. Both do the exact same thing, and even somewhat look alike, if that be considered copyright infringement. Team Fortress 2 had the engineer long before Modern Combat 5 had the sapper.
> -4 votes

# Answer
My personal belief is that if you have to ask the question, then you probably know in your heart that what you are doing is borderline wrong. It may or may not be legal, but to me its besides the point. If you cant be true to an art that you created then why bother.

Of course if you just want to knock down clones of popular games to make a quick buck, I doubt that anyone would bother with the hassle of legal action against you, since more often then not, if you just copied something and don't put your own spin on the issue, then it probably wont sell well enough to matter to the original.
> -9 votes

---
Tags: legal, copyright, intellectual-property
---


title: Variable Problem in GameMaker Studio

text:
# Question
Title: Variable Problem in GameMaker Studio
On obj\_player I have a Create and Step event

Create:

```
/// Intialize Variables
grav = 0.2;
hsp = 0;
vsp = 0;
jumpspeed = 7;
movepseed = 4;
move = key_left + key_right

```

Step:

```
//Get the player's input
key_right = keyboard_check(vk_right);
key_left = -keyboard_check(vk_left);
key_jump = keyboard_check_pressed(vk_space);

//React to inputs
move = key_left + key_right;
hsp = move * movespeed;
if (vsp < 10) vsp += grav;

if (place_meeting(x,y+1,obj_wall))
{
    vsp = key_jump * -jumpspeed
}

//Horizontal Collision
if (place_meeting(x+hsp,y,obj_wall))
{
    while(!place_meeting(x+sign(hsp),y,obj_wall))
    {
        x += sign(hsp);
    }
    hsp = 0;
}
x += hsp;

//Vertical Collision
if (place_meeting(x,y+vsp,obj_wall))
{
    while(!place_meeting(x,y+sign(vsp),obj_wall))
    {
        y += sign(vsp);
    }
    vsp = 0;
}
y += vsp;

```

Error Message:

```
FATAL ERROR in
action number 1
of Create Event
for object obj_player:

Variable obj_player.key_left(100007, -2147483648) not set before reading it.
 at gml_Object_obj_player_CreateEvent_1 (line 7) - move = key_left + key_right

```

Whats wrong with this code? Ive been stuck on it for a couple days now, just really confused as I have seen this code work in action and for other people in this video https://www.youtube.com/watch?v=IysShLIaosk

# Answer
> 1 votes
add

```
key_left = 0;
key_right = 0;

```

before

```
move = key_left + key_right;

```

in `Create:`

Both variables need to be initialized to some defined value before being read (`key_left + key_right` is a read of both) to set the move variable.

---
Tags: game-maker
---


title: Character movement in Unity

text:
# Question
Title: Character movement in Unity
For an endless runner game such as Subway Surfer, in order to move your character so smoothly in both z-axis and x-axis, which component of the followings is better:

`CharacterController` or `RigidBody`?

Can we use both of them together; if so, will it have any effect on the performance of our game?

# Answer
> 1 votes
You can only use one. Use the `Character Controller`, it will give you fine tune control with fixed speeds. Using a `Rigidbody` for player control is only useful in special cases.

---
Tags: unity
---


# Question
Title: Best algorithm for different shapes maze
Based off my previous question here Maze or puzzle algorithm for something similar to noodles are there specific algorithms that would be best suited to building a maze with only 1 solution for

1. A grid made of squares.
2. A grid made from hexagonal tiles

Thanks

# Answer
> 1 votes
For all maze algorithm problems, Think Labyrinth: Maze Algorithms usually has what you want.

Mazes with only one solution are known as **Perfect Mazes**. The page I linked lists more than a dozen algorithms for generating those, as well as a comparison table, under the heading *Perfect Maze Creation Algorithms*. Take your pick.

All these algorithms can be adapted for hexagonal mazes (or any topology and tessellation).

# Answer
> 1 votes
You would simply use `Union Find` and randomize the pair orders. When you are unifying, connect the two hexagons or squares (remove the border between them) and when you aren't unifying, leave the border as is. Randomize the order of unification.

`Union Find` is used to keep track of which rooms are accessible from which other rooms so you end with a maze where there is only one path between any pair of rooms (no cycles). Then you can add an entrance and an exit wherever you want.

---
Tags: algorithm, maze
---


# Question
Title: Unity change default settings for standard components
How can I change the default settings for the standard components or is this even possible? E.g. setting the default font-size for a text component so that each new text component I add will have the same font-size?

# Answer
> 1 votes
I prefer use `[ExecuteInEditMode]` instead of overriding defaults because you can edit it realtime in editor and you can grouping all texts , then set defaults to different groups of them.I know you want pervent repetitious work(changing defaults) by overriding defaults but you can't grouping them easily. for example:

---

**ExecuteInEditMode methode:**

group1(Menu fonts features) : font = 15;fontstyle = Normal,.....

group2(Score board fonts features) : font = 20;fontstyle = Bold ,.....

group3(Button fonts features) : font = 10;fontstyle = Italic,.....

**override methode:**

all text default fonts = 15;fontstyle = Normal,.....

---

but If you override them you have to change default again for some text,so you're limit in this way.this is mean you need many overriding classes foreach component.

this is basic using ExecuteInEditMode methode without grouping(for all text component in scene):

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

[ExecuteInEditMode]
public class ChangeFontSize : MonoBehaviour {
    public enum FontStyles{Normal,Bold,Italic,BoldAndItalic};
    public FontStyles ActiveState = FontStyles.Normal;
    public Color color;
    public Text[] AllText;
    public bool ChangeDefault;
    [Range(0,15)]
    public int size;

    void Update(){
        AllText = Object.FindObjectsOfType (typeof(Text)) as Text[];
        if(ChangeDefault == true){
            foreach (Text txt in AllText) {
            txt.fontSize = size;
                FStyle (txt);
            }
        }
    }
    //pass text components here
    void FStyle(Text mytext){
        switch(ActiveState)
        {
        // Check one case
        case FontStyles.Normal:
            //Set Normal Font style
            mytext.fontStyle = FontStyle.Normal;
            break;
        case FontStyles.Bold:
            //Set Bold Font style
            mytext.fontStyle = FontStyle.Bold;
            break;
        case FontStyles.Italic:
            //Set Italic Font style
            mytext.fontStyle = FontStyle.Italic;
            break;
        case FontStyles.BoldAndItalic:
            //Set BoldAndItalic Font style
            mytext.fontStyle = FontStyle.BoldAndItalic;
            break;
        }
    }
}

```

# Answer
> 0 votes
Perhaps you can achieve this by extending the component and overriding the right properties? Just spit balling here.

http://answers.unity3d.com/questions/12019/how-can-i-extend-a-component.html

---
Tags: unity
---


# Question
Title: What makes scaling pixel art different than other images?
Recently I was coaching a developer who's new to making pixel art games, and realized there's some "conventional wisdom" around scaling pixel art that's not obvious to a newcomer, and might not be well documented. So, here's an attempt to fix that....

---

1. I've heard I should only scale pixel art by 200%, 300% etc. not in-between sizes like 120%

* Why is that? Shouldn't scaling "just work" the way it does with other images?
    * What if I really need to make my character just a fraction larger or smaller to get the right gameplay or look? How do I fix this?
2. I'm told it's "bad" to use pixel art at different scales in one game - why?

* For example, if I scaled up my character so each sprite texel is 4x4 screen pixels, while my background art is scaled up so each sprite texel is 6x6 screen pixels. Isn't a pixel a pixel at the end of the day?

# Answer
> 42 votes
## Scaling by Whole Numbers

Scaling by 2x, 3x...**n**x is simple - each pixel just becomes an **n**x**n** square of pixels, and the look of the original sprite is perfectly preserved (including all the sharp lines, corners, and staircase zig-zags).

We run into trouble though when scaling pixel art by a fractional amounts (eg. 1.5x) because pixels are discrete by nature. We can't really have "half a pixel."

For other kinds of art we can often get away with blending adjacent source pixels where the pixel should be "half coloured," and at high resolutions the artifacts usually aren't noticeable. But on big chunky pixel art this quickly destroys the crisp look.

So instead we'll usually use "Nearest Neighbour" filtering (also called Point filtering) so that each pixel after scaling takes its colour from exactly one pixel in the original sprite.

This has another wrinkle: since the number of pixels after scaling isn't a whole-number multiple of the number of source pixels, some source pixels will get duplicated more than others (if scaling up) or skipped entirely (if scaling down).

Unfortunately, image editing software and GPU texture filtering aren't very choosy about where they duplicate or skip pixels - they just follow basic rounding rules - which can make the result look distorted and uneven.

Check out the example below. In the middle we've scaled up the mushroom sprite by 150% using Nearest Neighbour filtering, and the result looks wonky and haphazard. One eye is bigger than the other, some outlines are thick while others stay thin, and the rounded spots look blocky... it doesn't look like something a pixel artist would draw on purpose.

If we really need the sprite to be 150% bigger (say, to make the gameplay feel right, or to support alternate display resolutions), then we can repaint the problem areas like the example on the right. Now it looks more like something an artist would make, and stylistically consistent with other art in the game. (Though I'm not a great pixel artist myself, so it could still be better )

Unfortunately there aren't a lot of great shortcuts for this. For whole-number scales, you can use specially-designed pixel art upscaling algorithms - a wide variety are available in tools like ImageResizer \- to get a less blocky starting point than Nearest Neighbour, but it still takes an artist's eye and some elbow grease to get a high-quality result.

---

**Aside:** fractional scales can also crop up at runtime.

Imagine your game is in NES resolution (256 x 240), and you want to display it on a 1080p screen.

1080 ÷ 240 = 4.5, so some of the source pixels or "texels" in your scene get blown up to 5 screen pixels across, while others are only 4, creating distortions like we saw above. In motion they tend to make sprites ripple and shimmer distractingly, without an obvious cause:

You'll often see people suggest rounding camera or object positions to integer pixel coordinates, but that doesn't really fix the problem. Rounding already happens as part of the nearest neighbour filtering - the problem is that some screen pixels round to the same source texel (duplicating it), while others don't, leading to an uneven result.

The solution is to use a combination of padding/cropping or alternate asset sets to get back to a consistent, whole number ratio of screen pixels to texels for each display resolution you want to support. This is another case where there's no easy universal fix, and you'll have to apply some judgment and artistry to keep your game looking sharp.

## Keeping Pixel Scale Consistent

This "rule" comes down to stylistic consistency.

When you use pixel art at different scales, it can look like assets have been cobbled together from different games, instead having a unified aesthetic.

In the example on the left, I put together some sprites from Super Mario World, all at the same scale, and it looks great.

In the middle, I scaled up Mario and the level to twice the resolution of the background, and the mole to triple the resolution. Since I used whole-number scales, we don't get distortions or ripples anywhere, but it still looks a little funny.

For one, the background is so much more detailed than the foreground. It's able to represent smooth curves and sharp highlights, which makes the foreground look particularly "blocky" in contrast, rather than having a consistent pixel art feel. And the mole's outlines are noticeably thicker and more jagged than the rest of the foreground.

(I've just learned that graphics showing a mixture of pixel sizes like this are called "mixel art" or "mixels" in pixel artist circles)

At the right I show that again, by repainting the assets in a common pixel scale, we can bring back a more unified and intentional feel with the new asset sizes.

## But Do I Have To?

No, not really. It's your game, and you can make it the way you want.

Especially when prototyping and finding the fun in your game, being able to *try stuff fast* is more important than having it look perfect. You'll probably get the size of important things like your character wrong many times before you find what's best for your game, and it would *suck* to have to repaint every animation frame each time you want to try something different. So, early on, don't sweat it.

For the released game, it's a judgement call. No pixel art police will ban you from distributing your game if you don't follow the rules, and many players wouldn't be able to describe the difference. But attention to these pixel details is something many players (and reviewers) consider an important sign of quality - so get to know your audience, and decide what's best for the experience you want to offer them.

One last consideration is that a lot of pixel art games have very high-precision gameplay. Think of hopping between 1-block platforms in the early Mega Man games. In these situations, a consistent pixel grid (and tile grid) can be an important cue for the player in judging and executing their moves. Introducing irregularity in the art might actually make the game harder to learn, which can be frustrating.

---
Tags: scale, pixel-art
---


# Question
Title: What elements are indispensable to players of a tactical strategy game?
**Tactical strategy games** typically involve area capture/control, unit building, terrain effects, various specialized unit types. Some will include resource gathering / management, unit customization / advancement, experience benefits for units, tech / research trees, and commander powers.

Many are turn based to allow careful planning, while others are real time. Some have movement and targeting restricted by a grid, while others calculate rate of speed and distance - and in the case of 3d or pseudo-3d arcs of fire in vertical elevation. A few have side quests, a plot / story line - possibly branching, and an overall theme or genre of some type (sci-fi, fantasy, modern, etc). User interface elements are also critical to consider.

**Of these elements, and any additional elements not listed that can be thought of, which are the most indispensable?** *Which elements make or break a game, and keep you coming back or drive you away?* Please provide only the top three answers with supporting explanations and references, if available. Should platform impact the answer, please assume a game developed for both mobile devices and computers.

# Answer
## "Strategy" and "Tactical"

Starting with specifically strategy games. The core experience for the player could be described as **A game that emphasizes the cumulative result of a players choices**. In design this boils down to feedback loops. Build more units for resource gathering, you have more resources to build units for resource gathering.

In many strategy games, this is represented as economic choices. The best example of pure strategy games is probably Tower Defense games. You earn resources, and then spend them. But you don't typically actively make decisions about the individual fights that happen during waves of enemies.

So for strategy in general I'd say the choices available to the player and how those different choices compound to a final result is the key.

The focus of tactical games could be describe as **Maximizing fixed or limited resources to build the best outcome**.

My favorite example would be the Myth series of games. You never actually build new units (maybe you find some, but they are units already existing in the level).

## Tactical Strategy

Civilization series, Age of Empire series, and \*craft series all have economics at their core. You choose how many workers to build to increase your resource gathering vs. defensive or offensive units. You also decide to spend on your "technology tree" in all three, with some variation. That is strategy.

These game are also tactical. In Civ, you build up cities and train units and this leads to what resources you have available for battles when they occur. That is the strategy part. Tactical comes to play with your placement of units and their preparation. Battles may last only a few turns, and it's not likely that you'll be able to bring many more units to that battle. You have to make the best with the resources you have and the environment.

## Tactical Strategy Elements

So, strategy involves a series of choices that continually build upon each other. Tactical is focused on maximizing effectiveness of resources.

Most important elements then affect both:

* **Economic Decisions**. Some form of compounding decisions. Typically this is based on economics, with resources like gold or food or vespene gas. Then add different things that can be done with the same resource, forcing the player to choose one of many uses.
* **Utilization of Spent Resources**. Typically these are mobile units that can engage in fights with other unit. The player has chosen to build these units, this is the compounded outcome of their strategy effecting their ability to perform some action.
* **Tactical Advantages**. Constraints that the player can react to, in order to maximize the use of those units. High ground, visibility, etc. just so that it isn't a numbers game. Otherwise the strategy portion of the game will fall into gathering as many resources as quickly as possible. Starcraft does this very will with its highly varied races and units.

## Notes

* Tic Tac Toe is a tactical game. Limited spaces, trying to out position your opponent.
* Economics do not always mean strictly money. In Starcraft, there is a cap on the number of total units you can have. The units are part of the economy.
* A lot of the rest are aesthetics. Real Time Strategy games promote a more chaotic feel. Real Time Chess is absolutely crazy.
* Grid based games tend to promote more tactical gameplay as it is easier for players to judge distances or terrain effects. Civ tiles provide widely varying differences in effect. Without tiles it'd be hard to know which units are receiving which effects.
* Turn based games are meant to promote more planning. They can provide a much deeper set of strategic decisions to the player. Micro management in Civ means carefully planning what citizens are doing what. Micro management in Starcraft is a matter of how quickly you can give tactical orders to your units.

I've got to do some digging for specifics but "Game Mechanics: Advanced Game Design" by Ernest Adams and Joris Dorsman is a great book for understanding and modeling economics in games, they also discuss the Machinations tool which is awesome for designing and testing.

Also "Game Design Workshop: A Playcentric Approach to Creating Innovative Games" by Tracy Fullerton talks about how to break game down to the smallest parts and understand them.

Those are just two of the books that I've read that I can remember have some relevance. I'll try to find specifics in each to highlight when I cna.
> 1 votes

---
Tags: game-design, game-mechanics, strategy
---


# Question
Title: Why won't my model display fully in a mod made with an older version of GameMaker?
I have a model of a corkscrew that I am modding into a game made in what I *believe* was Game Maker 8.0. Unfortunately, there is little to indicate what version it was made in, other than that it was not GameMaker: Studio.

The problem with the model is that not all of it loads, and it just stops drawing. I made the model in GameMaker 8.0 Pro, through a simple 3D model-generating script that I wrote.

I loaded this content into Nintendo Nightmare. I did these tests in the "Hyrule Field" level (room 11, in the game), as it has the widest open area. I used a completely blank save file, going in to this, and made no other relevant cheat codes. The code I used is below. In the mod, code input is through one-line format, but I have formatted them for readability. Why won't my model completely display?

**This code adds drawing capabilities to the mod objects.**

```
object_event_add(obj_stringe, ev_draw, 0, "execute_string(text2);");
global.corkscrew = d3d_model_create();
d3d_model_load(global.corkscrew, "Corkscrew.d3d");
global.spr_pipeTexture = sprite_add("pipeTexture.png", 1, 0, 0, 0, 0);

```

**`text2` is a variable string executed every draw event of `obj_stringe`**

```
global.tube = instance_create(x, y, obj_stringe);
global.tube.text2 = "tex=sprite_get_texture(global.spr_pipeTexture, 0);
d3d_model_draw(corkscrew, x, y, z, tex);";

```

# Answer
The issue is that in older versions of game maker, models were stored in arrays which have a maximum storage of 32000 indexes, or roughly 10000 polygons. The newer versions (likely where the software you were viewing it in was made) don't have the same limit and don't store models in the same type of arrays. Therefore, models in older versions simply get "cut off" in memory and appear to stop drawing whereas newer versions of game maker lack such an issue.

Your only solution is to cut the model into smaller sub-models and draw each one individually (or just lower the polygon count).
> -4 votes

---
Tags: game-maker
---


title: Make HD trailer for Unity game

text:
# Question
Title: Make HD trailer for Unity game
I am making a HD trailer for my Unity game. How do I record awesome HD shots of my game inside the Unity editor?

# Answer
> 2 votes
You can easily capture 4K screenshots in Unity. All you have to do is capturing enough of these and assemble them into a video. Adobe Premiere is great for that (no doubt that After Effect can do the same).

The problem with this technique is that the frame rate will be awful if you don't have a powerful computer (taking screenshots costs a lot, but look at Time.captureFramerate to lock the deltaTime value it may smooth the framerate considerably).

Also what you can do is writing a script that will record your inputs and then replay them later on its own. Then you'll just have to play the section you want in your trailer, build your game, play it in HD and record the screen (using camtasia or sharex).

# Answer
> 0 votes
* If you want the screenshots for branding or publishing purpose, you could do some Photoshop on the screenshot.
* You already know the tool. There are other tools like Fraps (which is a professional game video capture tool, you can change the fps in it), PlayClaw, CamStudio, and VirtualDub.
* Try this link

You could always use a screen recorder tool to record your screen instantly. Hope this helps :)

---
Tags: unity, marketing, trailer
---


# Question
Title: Do I need the dev kit in order to release for Wii U?
In nintendo's developper website I found this quote.

> Q: How much does it cost to develop on Wii U?
>
> It’s free of charge to participate in the program and to submit games to Nintendo for technical certification. There is some cost involved for Wii U development hardware, but we run a program to help developers who are just getting started.

Now is it necessary to get those dev kits? I mean if I have my own personal console. Use Unity libraries (for example there is a ready .dll for using the WiiMote ), am I obliged to get the dev kit? I plan to develop my game using unity if that makes any changes.

# Answer
Yes, you do need a **Wii U Kit**. You cannot build, deploy and run your game on a regular **Wii U** console.

As Noctrine pointed out, there's no way Nintendo will let you publish a game that hasn't been tested on a console.

**Wii U dev kit specs**

The Wii U dev kit specs first and foremost support everything the regular retail Wii U console supports, and has the same hardware specs — the Wii U CPU and Wii U GPU are the same, as are the other features. However, dev kits usually have more storage and more memory to aid developers in compiling and creating games. The kit includes:

* Wii U console with added features such as extra ports, connectors, etc. The kit includes all the retail Wii U hardware.
* Nintendo-made software tools and libraries that can be freely used by developers.
* Royalty-free third party software and APIs licensed by Nintendo that is free for developers to use.
* Various tools to take in-game screenshots and in-game videos for trailers etc.
* Wii U games are usually written in C++. The Wii U dev kit includes a custom compiler.
* Tech support from Nintendo developers and experts on software, APIs, and the Wii U operating system.

Source: http://wiiudaily.com/wii-u-dev-kit/
> 7 votes

# Answer
Nintendo has now opened up for small firms, and even individuals to get access to not only the official SDK, but also developer kits.

You can check it out at developer.nintendo.com.
> 3 votes

---
Tags: unity, nintendo, wii
---


# Question
Title: Visualize quaternion euler angles without gimbal lock
I fusion ACC and GYRO data with Mahony algorithm, and then I want to show a line chart representing roll pitch and yaw to the user, so they can understand the degrees. As you can imagine, gimbal lock comes in at 90 degrees.

I also have an activity where the user can see a cube rotating correctly, having quaternions as input.

Is there a way to visualize the angles in degrees without gimbal lock? I can only manage to show an OpenGL shape rotating correctly, but my goal is to show the degrees.

# Answer
One way to visualize things would be to use an actual gimbal representation (topological circles that are hierarchically linked).

Refer to this Wikipedia depiction of how this might work.

Essential steps to implement a gimbal mechanism:

* check which Euler angle convention you're actually using. There are several (proper and Tayt-Brian)
* you must make sure that the outer-most gimbal circle affects **all** of its inner circular children, rotating them
* the gimbal lock effect is a natural side-effect when at least two of these circles are coplanar
* in the end, a gimbal is a composite robotic joint where all axes have the same physical origin, but different zero-pose orientation

*Regarding the gimbal lock issue*, simply convert the quaternions to your preferred Euler angle convention following the pointers presented here. As you may find, the issue stems from the fact that there are simply more ways of representing certain orientations using the gimbal mechanism that lies behind the Euler angle representation. This is a mathematical singularity and getting around it usually requires treating the case separately.
> 1 votes

---
Tags: opengl, quaternion, gimbal-lock
---