# Question
Title: Unity Method count exceed the limit of 64K
I just got an issue related to a 64k method in Unity so that's why I'm unable to build my project. It shows method limitation exceed the limit of 64k method count. So can anyone here help me out to resolve this issue?

# Answer
This answer relies heavily on Android's official documentation (the quoted parts, specifically).

---

**How to setup Multidex Support for Unity Project**

**What is Multidex:**

> Android application (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app. The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536, including Android framework methods, library methods, and methods in your own code. Getting past this limit requires that you configure your app build process to generate more than one DEX file, known as a multi dex configuration.

**When we use Multidex:**

When we exceed the total number of methods that can be referenced within a single DEX file to 65,536- including Android framework methods, library methods and methods in your own code.

> **Avoid the 64K limit**
>
> Before configuring your app to enable use of 64K or more method references, you should take steps to reduce the total number of references called by your app code, including methods defined by your app code or included libraries. The following strategies can help you avoid hitting the DEX reference limit:
>
> **Review your app's direct and transitive dependencies** \- Ensure any large library dependency you include in your app is used in a manner that outweighs the amount of code being added to the app. A common anti-pattern is to include a very large library because a few utility methods were useful. Reducing your app code dependencies can often help you avoid the DEX reference limit.
>
> **Remove unused code with ProGuard** \- Enable code shrinking to run ProGuard for your release builds. Enabling shrinking ensures you are not shipping unused code with your APKs.

Aside from these official tips, when building your Unity project, following these steps will help you further:

1. Build an Android Project from your Unity Editor.
2. Import your Android Project in Android Studio.
3. Setting up your app project to use a multi dex configuration requires that your make the following modification.

> If your minSdkVersion is set to 21 or higher, all you need to do is set `multiDexEnabled` to `true` in your module-level build.gradle file, as shown here:

```
android {
defaultConfig {
        ...
        minSdkVersion 21
        targetSdkVersion 26
        multiDexEnabled true
    }
    ...
}

```

> However, if your `minSdkVersion` is set to 20 or lower, then you must use the multidex support library as follows:
>
> 3.1. Modify the module-level build.gradle file to enable multidex and add the multidex library as a dependency, as shown here:

```
android {
    defaultConfig {
        ...
        minSdkVersion 15
        targetSdkVersion 26
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

```

> 3.2. Depending on whether you override the Application class, perform one of the following:
>
> * If you do not override the `Application` class, edit your manifest file to set `android:name` in the `<application>` tag as follows:

```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="android.support.multidex.MultiDexApplication" >
        ...
    </application>
</manifest>

```

> * If you do override the `Application` class, change it to extend MultiDexApplication (if possible) as follows:

```
public class MyApplication extends MultiDexApplication { ... }

```

> * Or if you do override the Application class but it's not possible to change the base class, then you can instead override the attachBaseContext() method and call MultiDex.install(this) to enable multidex:

```
public class MyApplication extends SomeOtherApplication {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }
}

```
4. Check error form other plugins manifest and clean the project.And sysc again.
5. If there is any dependency issue in your project, run this command in Android Terminal

```
% Gradle clean App."App name"

```
6. Copy these dependency in your Application Gradle , under dependencies:

```
compile fileTree(include: ['*.jar'], dir: 'bin')
compile fileTree(include: ['*.jar'], dir: 'libs')

```
7. Add the signingConfig in your main projects Gradle.

Or set the Signing mode to Debug mode by manually, Go to File -\> Project Structure -\> Under Modules Click on your project and under Build Types select Debug -\>choose Signing Config-\> debug
8. Now sync your Gradle and build the project.
> 22 votes

# Answer
I would recommend you to go through this link which will help you to create multidex enabled games directly through unity.

https://medium.com/@abhpatidar/solving-unity-dex-issue-538e134c8809

Note: This will only enable multidex in unity itself (and should fix multidex issues). It won't fix gradle related problems.
> 0 votes

---
Tags: unity, android, unityscript, android-studio
---


# Question
Title: Load uncontrolled 3D asset at runtime in Unity
I'm trying to load assets at runtime in Unity. I can load images this way: https://docs.unity3d.com/455/Documentation/ScriptReference/Texture2D.LoadImage.html

But how can I do the same with 3D assets? From what I read, loading .fbx/.obj and alike need importers. But importers are created by users, and support might be bad.

I read you can import using https://docs.unity3d.com/ScriptReference/WWW.html But that seems only to work with unity3D files

Or do I follow the wrong track? Is there another way to do this?

# Answer
You'll need to create a new instance of the `Mesh` class and populate it with the vertex data that you read from the model file loaded at runtime. (Including vertex positions, triangle indices, and optionally texture coordinates, normals, tangents vertex colours, skinning weights, etc.)

That means your game needs to include logic (either an existing library that you include, or hand-rolled) to parse that model file format and read out the relevant data into the array types accepted by the `Mesh` class.
> 0 votes

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


# Question
Title: Designing an efficient neighbour-networking system
I'm developing a game, which involves the use of *nodes* (buildings), and I need to implement *neighbour* networks that nodes can use to either *directly* or *indirectly* access other nodes. Nodes can be *created*, *destroyed*, or *bridged to* **at any point** in the game.

At the moment, I'm creating a list of all the nodes in a *neighbour* network, which is re-calculated whenever there is a *new* addition to the network. Each node in the network will hold a *reference* to this list. This system works, but I feel that there is a more *efficient* way to do this.

This is my current code for my node class

```
public class Node {
    public List<Node> directNeighbours;
    public List<Node> network;

    public void addNeighbour(Node n) {
        directNeighbours.add(n);
        recalculateNetwork();
    }

    public void removeNeighbour(Node n) {
        directNeighbours.remove(n);
        recalculateNetwork();
    }

    public void recalculateNetwork() {
        recalculateNetwork(new Network(), new HashSet<Node>());
    }

    void recalculateNetwork(List<Node> network, Set<Node> searched) {
        if (searched.contains(this)) return;

        network.add(this);
        this.network = network;

        for (Node neighbour : directNeighbours) {
            neighbour.recalculateNetwork(network, searched);
        }
    }
}

```

Is this the best way to keep track of direct and indirect neighbours? If not, could anyone please give me ideas on how to make this better?

# Answer
> 1 votes
Your basic approach is okay, but there's some issues with your implementation. Specifically:

* `recalculateNetwork()` creates a new network every time it gets called
* `recalculateNetwork(List<Node> network, Set<Node> searched)` is recursive. As of 2015, Java doesn't optimize for tail-recursion. Until that changes, it's generally good to avoid it if performance is an issue.

That being said, some problems in general graph structures are always going to be problematic. For instance, whenever you remove an edge (i.e. by removing a direct neighbor relationship between nodes A & B) there's a chance that you've partition the graph into two unconnected sub-graphs. Here's an example:

```
Y-Z
| |
X-A-B-D-E
```

Removing the edge A,B results in two sub graphs as shown:

```
Y-Z
| |
X-A B-D-E
```

The only way to determine that is to start at one node & see if the other is reachable or not. Some conditions allow you to speed this up (chunking, caching, restrictions on connections), but in the general case, you have to search all nodes before you can be certain that the graph needs to be split.

Here's some sample code & a tester. Personally, I would consider making the network field its own class instead of directly using the `HashMap`, but that's me. I opted for this instead as it more closely follows what you were already doing & isn't necessarily wrong per say. I've tried to strike a balance between understandability & performance. If this is still not fast enough, then we'll need to examine other parts of the problem & code to see if there's anything else to take advantage of.

Some comments about hash keys: It wasn't clear how many Nodes you might need, so went with integer IDs for hash keys. If each node has some other unique identifier (name, coordinate location, etc), use that instead. If you plan on generating many different nodes, but never exceed some maximum value, consider using keys from an object pool. Finally, there's universally unique identifiers (UUIDs); they seemed like overkill for this, but if you outgrow this code, you might need to consider them.

```
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

public class Node {
    private static int nextID = 0;
    private final int ID;
    private final HashMap<Integer, Node> neighbors;
    private HashMap<Integer, Node> network;

    /**
     * build a new node in its own network
     */
    public Node(){
        ID = nextID++;
        if(nextID == 0){
            throw new IllegalStateException("exhausted all node IDs");
        }
        neighbors = new HashMap<>();
        network = new HashMap<>();
        network.put(ID, this);
    }
    /**
     * build a new node & make it a direct neighbor of n
     * @param n the Node to make this node a direct neighbor of
     */
    public Node(Node n){
        ID = nextID++;
        neighbors = new HashMap<>();
        this.network = n.network;
        network.put(ID, this);
        addNeighbor(n);
    }
    public int getID(){
        return ID;
    }
    public boolean hasDirctNeighbor(Node n){
        return neighbors.containsKey(n.ID);
    }
    public boolean hasIndirctNeighbor(Node n){
        return network.containsKey(n.ID);
    }
    /**
     * get all of the direct neighbors of this node
     * @return collection of all direct neighbors
     */
    public Collection<Node> getDirectNeighbors(){
        return new ArrayList<>(neighbors.values());
    }
    /**
     * get all of the nodes in network of this node
     * @return collection of all nodes in the network
     */
    public Collection<Node> getAllNeighbors(){
        return new ArrayList<>(network.values());
    }
    private void mergeNetworks(HashMap<Integer, Node> other){
        HashMap<Integer, Node> larger = network;
        HashMap<Integer, Node> smaller = other;
        if(other.size() > network.size()){
            larger = other;
            smaller = network;
        }
        for(Node n : smaller.values()){
            n.network = larger;
            network.put(n.ID, n);
        }
        smaller.clear();
    }
    /**
     * add n to this node's direct neighbors - merges the networks if
     * necessary
     * @param n the node to add - note cannot be the same as this node
     */
    public final void addNeighbor(Node n){
        if(n == this){
            throw new IllegalStateException("cannot make node a neighbor with itself");
        }
        // if the node don't already share a network, then the two networks
        // must be merged
        if(!network.containsKey(n.ID)){
            mergeNetworks(n.network);
        }
        neighbors.put(n.ID, n);
        n.neighbors.put(this.ID, this);
    }
    /**
     * remove n from this node's direct neighbors (but not necessarily the network)
     * splits the network only if necessary
     * @param n the node to remove - note cannot be the same as this node
     */
    public void removeNeighbor(Node n){
        if(n == this){
            throw new IllegalStateException("cannot remove a node from itself");
        }
        neighbors.remove(n.ID);
        n.neighbors.remove(this.ID);
        // check if any other node we can reach from this node
        HashMap<Integer, Node> tempNetwork = new HashMap<>();
        ArrayList<Node> queue = new ArrayList<>();
        queue.add(this);
        tempNetwork.put(ID, this);
        while(!queue.isEmpty()){
            Node tempNode = queue.remove(0);
            for(Node neighborOfTempNode : tempNode.neighbors.values()){
                // found it, no need to split the network
                if(neighborOfTempNode == n){
                    return;
                }
                if(!tempNetwork.containsKey(neighborOfTempNode.ID)){
                    queue.add(neighborOfTempNode);
                    tempNetwork.put(neighborOfTempNode.ID, neighborOfTempNode);
                }
            }
        }
        // unable reach n from this node, therefore we must split
        for(Node local : tempNetwork.values()){
            local.network = tempNetwork;
            n.network.remove(local.ID);
        }
    }
    /**
     * removes this node from the network & from an direct neighbors it had
     */
    public void removeFromNetwork(){
        Collection<Node> oldNeighbors = this.getDirectNeighbors();
        for(Node n : oldNeighbors){
            n.removeNeighbor(this);
        }
    }
}

```

Tester/demo code:

```
public class Tester {
    public static void main(String[] args){
        Node[] nodes = new Node[7];
        for(int a=0; a<nodes.length; a++){
            nodes[a] = new Node();
        }
        for(Node n : nodes){
            System.out.println(info(n));
        }
        add(nodes[0], nodes[1]);
        add(nodes[2], nodes[3]);
        add(nodes[4], nodes[5]);
        add(nodes[4], nodes[6]);
        for(Node n : nodes){
            System.out.println(info(n));
        }
        add(nodes[0], nodes[6]);
        add(nodes[0], nodes[5]);
        for(Node n : nodes){
            System.out.println(info(n));
        }
        remove(nodes[0], nodes[1]);
        remove(nodes[4], nodes[6]);
        for(Node n : nodes){
            System.out.println(info(n));
        }
        isolate(nodes[5]);
        for(Node n : nodes){
            System.out.println(info(n));
        }
    }
    public static void add(Node n1, Node n2){
        System.out.println("adding " + n2.getID() + " to " + n1.getID());
        n1.addNeighbor(n2);
    }
    public static void remove(Node n1, Node n2){
        System.out.println("removing " + n2.getID() + " from " + n1.getID());
        n1.removeNeighbor(n2);
    }
    public static void isolate(Node n){
        System.out.println("removing " + n.getID() + " completely from its network");
        n.removeFromNetwork();
    }
    public static String info(Node n){
        String result = "ID: " + n.getID();
        result += "\tfull network: " + networkString(n);
        result += "\tdirect neighbors: " + neigborString(n);
        return result;
    }
    public static String neigborString(Node n){
        String result = "(";
        for(Node t : n.getDirectNeighbors()){
            result += " " + t.getID();
        }
        result += " )";
        return result;
    }
    public static String networkString(Node n){
        String result = "< ";
        for(Node t : n.getAllNeighbors()){
            result += t.getID() + " ";
        }
        result += ">";
        return result;
    }
}

```

---
Tags: java, architecture
---


# Question
Title: How do I respawn a prefab that matches the name of the game object I just destroyed?
In my game the player can interact with certain objects like coins, clouds and springs. After these interactions the game objects are destroyed. All of these game objects have their own properties, but their classes inherit from a master "WorldObjects" class that contains respawn information:

```
protected virtual void OnTriggerEnter2D(Collider2D other)
{
    if (other.CompareTag("Player"))
    {
        if (respawnObject)
        {
            Respawner.respawnPositions.Add(startPosition);
            Respawner.respawnTimes.Add(respawnTimer);
        }

        PlayerController = other.GetComponent<CharacterController2D>();
    }

    else return;
}

```

I have been able to respawn one type of object at a time by dragging a prefab to the first position in my objectsToRespawn array, but how do I send information to my Respawner class so that I can dynamically respawn the correct type of game object depending on the object I previously destroyed? Is it possible to compare my destroyed game object's name with its associated prefab, and then load the prefab into the array (or, if needed, a list)?

Here's my respawner class:

```
public class Respawner : MonoBehaviour
{
public GameObject[] objectsToRespawn;

public List<Vector3> respawnPositions = new List<Vector3>();
public List<float> respawnTimes = new List<float>();

private void Update ()
{
    if (respawnPositions.Count != 0)
    {
        RespawnObjects();
    }
}

private void RespawnObjects()
{
    for (int i = 0; i < respawnPositions.Count; i++)
    {
        respawnTimes[i] -= Time.deltaTime;

        if (respawnTimes[i] <= 0)
        {
            Instantiate(objectsToRespawn[i], respawnPositions[i], Quaternion.Euler(0, 0, 0));
            respawnPositions.RemoveAt(i);
            respawnTimes.RemoveAt(i);
        }
    }
}

```

Perhaps I should clarify, what I want to have happen is when I destroy a game object via OnTriggerEnter2D (like picking up a coin), that object sends its name or type or some sort of identification to the respawner class, which "queues" up the associated prefab, ultimately respawning it in its original location once the respawn timer for that object is 0.

This is my coin's OnTriggerEnter2D class (where the object is destroyed):

```
protected override void OnTriggerEnter2D(Collider2D other)
{
    base.OnTriggerEnter2D(other);

    Destroy(this.gameObject);
    Destroy(Instantiate(interactionEffect.gameObject, ObjectTransform.position, ObjectTransform.rotation) as GameObject,
        interactionEffect.main.duration * 2);
}

```

# Answer
> 2 votes
**Edit:** whoops! I had the idea that I wanted the prefab of the object itself to remember which prefab it's spawning from, but neglected a wrinkle of prefab spawning: when you spawn a copy of an object, all references that object has to itself and its own components/children get translated in the copy to point at the *copy* itself and the *copy's* components/children.

This is usually a good thing - it means that if I spawn a dozen instances of a gun, each one fires from its own barrel, rather than all of those instances still referencing *the original gun's* barrel.

But, it does slightly complicate a reference to "my own prefab" which, when the object *is* a prefab in the Assets folder is "me," but when the object is dropped/spawned in the scene, we no longer want it to be "me" but still point at the same asset in the Assets folder.

Here's how we can get this behaviour....

---

```
public class Respawnable : MonoBehaviour {

    public Respawnable prefab;

// When we're setting up the scene in the Unity editor:
// If I drag a reference of this prefab into the scene,
// the OnValidate() method runs and fixes up the reference
// to point to its prefab instead of to itself.
// This also initializes the reference when we first add
// the script to a new object that is or will become our prefab.
#if UNITY_EDITOR
    void OnValidate() {
        if(sourcePrefab == this || sourcePrefab == null) {
            var prefab = (Respawnable)UnityEditor.PrefabUtility.GetPrefabParent(this);
            sourcePrefab = prefab ?? this;
        }
    }
#endif

    // When spawning one of these via script, we need to fix up the
    // prefab link after spawning the copy. So call the Spawn()
    // method instead of Instantiate to make sure this happens.
    public GameObject Spawn() {
        var spawned = Instantiate(prefab);
        spawned.prefab = prefab;
        return spawned.gameObject;
    }

    // You can mirror all the overloads of Instantiate() you like.
    public GameObject Spawn(Vector3 position, Quaternion orientation) {
        var spawned = Spawn().transform;
        spawned.localPosition = position;
        spawned.localRotation = orientation;
        return spawned.gameObject;
    }
.
    Vector3 startPosition;
    void Start() {
        startPosition = transform.position;
    }

    void OnTriggerEnter(Collider2D other) {
        if (other.CompareTag("Player") == false)
            return;

        if (enabled) {
            // Find the respawner and tell it to respawn us after we're gone.
            var respawner = Respawner.GetInstance();
            respawner.Add(this, startPosition, respawnTimer);
        }
    }
}

```

Attach this to anything you want to respawn this way.

To simplify the lists, I'd make a little record type:

```
public struct RespawnRecord {
    public Respawnable prefab;
    public Vector3 spawnPoint;
    public float time;
}

```

And your respawn logic now knows exactly what to spawn (and doesn't need to juggle multiple lists)

```
List<RespawnRecord> respawnList = new List<RespawnRecord>();

public void Add(Respawnable prefab, Vector3 spawnPoint, float time) {
    respawnList.Add(
            new RespawnRecord(){
                 prefab = prefab,
                 spawnPoint = spawnPoint,
                 time = time
            });
}

private void RespawnObjects()
{
    for (int i = 0; i < respawnList.Count; i++)
    {
        var record = respawnList[i];
        record.time -= Time.deltaTime;

        if (record.time <= 0)
        {
            // Note we use the Spawn method instead of Instantiate directly.
            record.prefab.Spawn(record.spawnPoint, Quaternion.identity);

            // Don't forget to decrement i after RemoveAt!
            // Otherwise our next iteration checks slot [i+1]
            // which means we skip whichever object just moved
            // down to fill slot [i] when we emptied it.
            respawnList.RemoveAt(i--);
        } else {
            // Write back the changed record struct.
            respawnList[i] = record;
        }
    }
}

```

# Answer
> 2 votes
First, you should combine this information:

```
public GameObject[] objectsToRespawn;
public List<Vector3> respawnPositions = new List<Vector3>();
public List<float> respawnTimes = new List<float>();

```

Nothing about these lists says that the indexes for each refers to the same index in the other (not to mention that one of them is a static sized array and the other two are lists!). You should instead create a custom class object that holds these three pieces of information and have a *single* list of that class.

```
public class RespawnObjectInformation {
    public GameObject objectToRespawn;
    public Vector3 respawnPosition;
    public float respawnTime;
}

public class Respawner : MonoBehaviour {
    public List<RespawnObjectInformation> objectsToRespawn;
    // ...

```

This insures that any information you need is available and correct. You can't inadvertently `reverse()` one of the arrays and screw everything up.

You need the object name, too? Add that information to the class:

```
public class RespawnObjectInformation {
    public GameObject objectToRespawn;
    public Vector3 respawnPosition;
    public float respawnTime;
    public string objectName;
}

```

And your respawn code:

```
private void RespawnObjects()
{
    for (int i = 0; i < objectsToRespawn.Count(); i++)
    {
        objectsToRespawn[i].respawnTime -= Time.deltaTime;

        if (objectsToRespawn[i].respawnTime <= 0)
        {
            GameObject go = Instantiate(objectsToRespawn[i].objectToRespawn, objectsToRespawn[i].respawnPosition, Quaternion.Euler(0, 0, 0));
            go.name = objectsToRespawn[i].name;
        }
    }
    //remove objects from outside the loop to avoid a concurrent modification exception
    objectsToRespawn.RemoveAll(x => x.respawnTime <= 0);
}

```

Edit: SO MUCH LINQ

We can replace that entire function with this, instead, utilizing linq and lambda functions.

```
List<RespawnObjectInformation> respawns = objectsToRespawn.FindAll(x => {
    x.respawnTime -= Time.deltaTime;
    x.respawnTime <= 0
}); //yes, we can do this!
respawns.ForEach(x => {
    GameObject go = Instantiate(x.objectToRespawn, x.respawnPosition, Quaternion.Euler(0, 0, 0));
    go.name = x.name;
});
objectsToRespawn.RemoveAll(respawns);

```

---
Tags: unity, c#, assets, spawning
---


title: Rotation along normal vector

text:
# Question
Title: Rotation along normal vector
I have a triangle in the 3D world. I have the:

* positions for the three points
* the normal vectors for the three points (all the same, because vertices are not shared)

This triangle faces to a direction, so it has a XYZ rotation (but I dont know the rotation itself).

If I put a cube into the same scene, how I can achieve the same rotation for the cube? So if the triangle "looks" upwards, the cube should do the same. If it has a `10f` x rotation, how can I get what is the x?

# Answer
> 1 votes
The easiest way I can think to do this would be with a rotation matrix. It would be a 3x3 matrix with each row representing each of the basis vectors of the local space of the triangle in question.

Let's consider the normal of the triangle to be the `j` basis vector. You'd get the `i` basis vector with `cross(normalize(p1 - p0), triNorm)`. You'd get the `k` basis vector by taking the cross product of `i` and `j`.

You'd put those three resulting basis vectors in the matrix in the order of `i, j, k`. To produce the XYZ Euler angles for the triangle, you'd simply convert the rotation matrix to that form.

Here is some code that can help you do that. (inspired by code from the book: 3D math primer for graphics and game development):

```
float sx = -m32;

if(abs(sx) > 1e5f) {
    x = _PI * sx;
    y = atan2(-m23, m11);
    z = 0;
} else {
    y = atan2(m31, m33);
    x = asin(sx);
    z = atan2(m12, m22);
}

```

Something to keep in mind is that if you're trying to use a certain axis from the resulting Euler angle on it's own, you might get undesired results. You could fix this problem however, but it'll take a few more steps.

---
Tags: opengl, transformation
---


# Question
Title: How do I represent a MD5-mesh bone (quaternion orientation)
Going off this link about the MD5Mesh file format, I see a bone is represented as:

```
"[boneName]"   [parentIndex] ( [xPos] [yPos] [zPos] ) ( [xOrient] [yOrient] [zOrient] )

```

Since xOrient,yOrient,zOrient make up an orientation quaternion and not a vector, I don't know how to illustrate them. I'm still trying to get a grasp of bones and mesh manipulation.

How is the following represented in file?:

* Two bones of a simple stick figure (origin as "a" & left(or right) leg as "b")
* groin of model is at origin with the head in the positive y-axis direction
* arm wing span goes across x-axis
* leg is facing down and 2 unit out on the x-axis from the origin

# Answer
> 2 votes
The three imaginary components of the quaternion form the axis of rotation, and the real component

```
wOrient = sqrt(1f - xOrient*xOrient - yOrient*yOrient - zOrient*zOrient)

```

is the cosine of half the angle of rotation about that axis. So you can translate this into an angle-axis form if you find that easier to reason about:

```
axis = normalize(xOrient, yOrient, zOrient)
angle = acos(wOrient) * 2.0

```

Here are some particular Quaternion values you might see:

```
 x     y     z     w     Interpretation

 0     0     0     1     no rotation

0.26   0     0    0.97    30 degree rotation on x+ axis
0.50   0     0    0.87    60 degree rotation on x+ axis
0.71   0     0    0.71    90 degree rotation on x+ axis
0.87   0     0    0.50   120 degree rotation on x+ axis
0.97   0     0    0.26   150 degree rotation on x+ axis

 1     0     0     0     180 degree rotation on x+ axis
 0     1     0     0     180 degree rotation on y+ axis
 0     0     1     0     180 degree rotation on z+ axis

-1     0     0     0     180 degree rotation on x- axis (or -180 on x+ axis)

0.71  0.71   0     0     180 degree rotation about the line y = x

```

---
Tags: quaternion, bones, md5mesh
---


# Question
Title: Tiled - Possible to create a terrain from this specific tileset?
I'm really new to Tiled and I can't get the hang of creating terrains.

I have these really nice 2D assets I would like to use but I can't get the terrains to work. I'm trying to create a dirt path terrain brush from the below tileset.

I've checked countless tutorials but nothing works. I'm starting to think these just aren't compatible with Tiled.

Could someone tell me if it's meant to be possible?

I've added a watermark to the tile image below as these are commercial assets.

Thanks!

# Answer
It does not look like this tileset will be usable with the Tiled terrain tool without some modifications. For example there are three pieces at the top and bottom of the dirt and sand patches that need to be used together, whereas the terrain tool expects there to be one or more tiles that are interchangeable at the sides of such patches.

You could try to use automapping rules if you want to automate these transitions to their full potential.
> 1 votes

---
Tags: tiles, tilemap, tiled
---


title: More realistic AI chasing player

text:
# Question
Title: More realistic AI chasing player
I am developing a stealth game. In the game when enemy sees player he starts chasing it. But there are a lot of covers. If player just goes behind of a wall it will be out of sight for this enemy. But I want my enemies little bit more realistic.

So i did do some further implementations... For example if player goes out of sight enemy remembers last seen position and goes there anyway.

Than i save the move direction of player on the position where he was last seen. So when enemy goes there he looks this direction which he may probably catch a glimps of the player and start chasing again.

But if player is still no where to be seen I want my enemy to look around little bit, search for the player maybe. I couldnt come up with an algorithm to do that.

Also if on the last seen position and last move direction there is another wall, enemy goes this position and looks stupidly to the wall which also dont seem realistic at all...

Does anybody have any suggestions?

# Answer
A system similar to this is used in the Splinter Cell games.

Once the AI have validated that Sam is no longer at his last known position, they begin systematically scouring the available cover/corner locations, treating them like a checklist.

At the start of the search, they check off every cover position they already have line of sight to, then move to flank/scan remaining cover points. Once an AI has scanned a cover location, it checks it off. Once they've exhausted their search possibilities, they fall back on more general patrol behaviours.

This could help with your "turn into the wall" case. If the wall has an alcove that could serve as cover, then it's a sensible site to check and they'll turn to scan it. If it's a completely blank wall, it won't be tagged as a cover location and they'll ignore it and look at the next closest cover in that general direction.
> 4 votes

# Answer
Given how your question is presented, I'd say the real answer is to take a step back and think how you want your AI to behave, since how your AI behaves must fit the kind of game you are making:

* A tactic/puzzle-like game like the first Commandos game, your current behavior would be enough if you add a little "look around" animation
* A purely stealth game would use an AI like the described by @DMGregory in Splinter Cell
* An stealth/action game would work with the guard going into a "search and destroy" mode, where he will move randomly around the area until you are seen again, or even make him know your current position for X seconds, so you have to stay away from his line of sight for an amount of time.
* A more systemic game with emergent gameplay, you should not only think about the guard's AI, but the AI of all agents and how they interact with each other.

There is no way to improve an AI in the vacuum (besides performance), since you first need to have a clear picture of what you want to achieve with your AI in order to be able to measure the quality of it's behavior.

Of course, once you have a clear idea, you will be presented with a lot of questions about how to achieve that goal.
> 0 votes

---
Tags: ai
---


title: Box2d punch detection

text:
# Question
Title: Box2d punch detection
So working on a 2d fighting game and wondering whats a good method for detecting punch collision. Ive got a few questions on how to implement the attack stuff. Im using box2d (and Libgdx) for the movement and collision detection.

1. Best way to do punch and detection? Currently thinking of creating a fixture on the body and destroying it after a little time with a Timer
2. How to do a multipunch combo, basically if they hit the button 3 times in a row it does a combo attack? Think creating a variable that gets added +1 when they hit the button and a timer resets it back to 0 after a certain amount of time
3. Prevent attacks during the attack animation to prevent button jamming? Currently using state status so need to figure out the best way to change the state to/from attacking

# Answer
I assume this is a street fighter like game so I'm not sure why you would need to destroy a fixture after a set period unless you have parts of the fighter that get destroyed during the fight but this is what I would do:

1. I would have a sensor fixture/s on each player's body to register hits and sensors for each hand. This would allow you to register attacks without affecting moving/animations.
2. Have a super class called something like **Attack** which has value for length of attack (*attackLength*),a value for next attack (comboAttack), and a list of valid combo Attacks(*attackList*). The attack length could then be used to determine when the attack has finished and to determine if the next attack was triggered in time to be considered a combo. Then if the combo is in the valid list add it to the comboAttack. When the attack is finished check if the comboAttack variable has a combo if so do that combo move.
3. As stated in point 2 using a variable like attackLength would allow you to determine whether an attack was ongoing or completed.
> 1 votes

---
Tags: collision-detection, libgdx, box2d, fighting-game
---


# Question
Title: Share Image on Android Application from Unity Game
I've captured screenshot in my game when player dies. I've following code to capture screen shot.

```
RenderTexture rt = new RenderTexture (800, 600, 24);
        MainCamera.targetTexture = rt;
        Texture2D texture = new Texture2D (800, 600, TextureFormat.RGB24, false);
        MainCamera.Render ();
        RenderTexture.active = rt;
        texture.ReadPixels (new Rect (0, 0, 800, 600), 0, 0);
        MainCamera.targetTexture = null;
        RenderTexture.active = null;
        Destroy (rt);
        byte[] bytes = texture.EncodeToPNG ();
        Directory.CreateDirectory (Application.persistentDataPath + "/GameOverScreenShot");
        File.WriteAllBytes (Application.persistentDataPath + "/GameOverScreenShot" + "/DiedScreenShot.png", bytes);

```

I am getting saved screenshot using following code.

```
byte[] bytes = File.ReadAllBytes (Application.persistentDataPath +"/GameOverScreenShot" + "/BirdDiedScreenShot.png");

    Texture2D texture = new Texture2D (800, 600, TextureFormat.RGB24, false);
    RectOffset tempOffset = new RectOffset (5, 5, 5, 5);
    texture.filterMode = FilterMode.Trilinear;
    texture.LoadImage (bytes);
    Sprite sprite = Sprite.Create (texture, new Rect (0, 0, 800, 400), new Vector2 (0.5f, 0.0f), 2.0f);
    ScreenShot_Image.GetComponent<Image> ().sprite = sprite;

```

Now, I want to share this screenshot on android application. As per my research i have got following code for that, but it is returning blank image.

```
//instantiate the class Intent
    AndroidJavaClass intentClass = new AndroidJavaClass("android.content.Intent");

    //instantiate the object Intent
    AndroidJavaObject intentObject = new AndroidJavaObject("android.content.Intent");

    //call setAction setting ACTION_SEND as parameter
    intentObject.Call<AndroidJavaObject>("setAction", intentClass.GetStatic<string>("ACTION_SEND"));

    //instantiate the class Uri
    AndroidJavaClass uriClass = new AndroidJavaClass("android.net.Uri");

    //instantiate the object Uri with the parse of the url's file
    string destination = Application.persistentDataPath + "/GameOverScreenShot" + "/DiedScreenShot.png";
    AndroidJavaObject uriObject = uriClass.CallStatic<AndroidJavaObject>("parse","file://"+destination);

    //call putExtra with the uri object of the file
    intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_STREAM"), uriObject);

    //set the type of file
    intentObject.Call<AndroidJavaObject>("setType", "image/*");

    //instantiate the class UnityPlayer
    AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer");

    //instantiate the object currentActivity
    AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");

    //call the activity with our Intent
    currentActivity.Call("startActivity", intentObject);

```

What should I change in this?? Please help, Advance Thanks

# Answer
Application.Persistant datapath stores your image inside of the apk, this is not what you want as your gallery will not see it. Before you call WriteAllBytes, use this code:

```
string myFolderLocation = "/storage/emulated/0/DCIM/Screenshots/";

            if (!System.IO.Directory.Exists(myFolderLocation))
            {
                System.IO.Directory.CreateDirectory(myFolderLocation);
            }
string myScreenshotLocation = myFolderLocation + "myFilename";

File.WriteAllBytes(myScreenshotLocation, bytes);

```

Then you refresh the android phone photo gallery, give it a minute before is actually is visible in the gallery, but you can see it inside that folder location as soon as you save the picture.

Note: mine works like a charm and its saving it on internal storage also.
> 1 votes

# Answer
```
MainCamera.targetTexture = rt;
Texture2D texture = new Texture2D (800, 600, TextureFormat.RGB24, false);

//maybe you add this??

texture.apply();

MainCamera.Render ();

```
> -1 votes

---
Tags: unity, android, screenshot
---


# Question
Title: Unity 2D: Position Child Object to center of Parent Object
What I'm trying to achieve is snapping a child object to the center of its parent object after dragging and dropping it.

The moving object successfully follows the mouse, and drops. It also successfully selects a dynamic parent when it moves over a new node.

What it does NOT do is then snap to the center of its parent. It instead jumps all over the screen and snaps to nothing.

Here is all of my code:

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

public class Object_Moveable: MonoBehaviour {

 private Vector2 mousePos;
 public float moveSpeed;
 public float offset = 0f;
 private bool following;
 private GameObject SelectedNode;

 // Use this for initialization
 void Start() {
  following = false;
  offset += 10;
 }

 void Update() {

  if (Input.GetMouseButtonDown(0) && ((Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position).magnitude <= offset)) {
   following = true;
  }

  if (following) {
   transform.position = Vector2.Lerp(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition), moveSpeed);
  }

  if (Input.GetMouseButtonUp(0)) {
   following = false;
   //Attach (Node, 0, 0);
   transform.localPosition = SelectedNode.transform.position;
  }
 }

 void OnTriggerEnter2D(Collider2D trigger) {
  if (trigger.tag == "pipenode") {
   transform.SetParent(trigger.transform);
   SelectedNode = trigger.gameObject;
  }
 }
}

```

# Answer
Your local position is the position **relative to the parent**.

This means that to put an object exactly on the parent, it's local position must be (0, 0, 0) (meaning no change compared to the parent).

In your case, do

```
transform.localPosition = Vector3.zero;

```
> 2 votes

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


title: Queueing with Unity's NavMeshAgent

text:
# Question
Title: Queueing with Unity's NavMeshAgent
I have created a strategy game where the units use Unity's NavAgent pathfinding and flocking algorithms. This works well. However, I need to add queueing so that units will queue sensibly. This works most of the time, but it isn't perfect and I want to know if there's a better way of doing it.

My first draft was to simply check which unit is closest to the destination, but this caused issues because a group might be navigating around an obstacle and the unit closest is at the back of the queue... so the whole group stops.

Second draft checked the distance to destination based upon the length of the path each unit had to take. This works far more often, but sometimes still has issues. Sometimes the same problem happens, but much less often. The one who is supposed to be moving stops, and so the entire group stops.

There's also a problem I've noticed, where the waiting units could sometimes benefit from rotating, even if they shouldn't be moving. Unfortunately they sometimes get stuck and will wait before they can move, to rotate. If they could rotate when forbidden from moving it'd help considerably too.

What I need to know...

1. **How can I make Unity NavAgent's queue, so that they will wait for the other agents closest to the destination to move first?**
2. **How can I ensure that this does not stop agents from rotating while in a queue (rotating may move them into a better position in the queue).**

Code:

**Unit Movement Function**

```
private void Movement()
{
    // Unit is moving.
    if (moveVectors.Count > 0)
    {
        navAgent.isStopped = false;

        // Check for whether to wait in queue.
        Vector3 nextVector = transform.position;
                nextVector += transform.forward * speed * Time.deltaTime;

        foreach (Unit unit in list)
        {
            if (unit != this &&
                unit.moveVectors.Count > 0 &&
                Vector3.Distance(unit.transform.position, nextVector) <= (unit.footprint + footprint) &&
                PathDistance(unit) < PathDistance(this))
            {
                navAgent.isStopped = true;
                return;
            }
        }
    }
}

```

There's a bit more to Movement, but it's not relevant so we'll ignore it for now.

**PathDistance Function**

```
private float PathDistance(Unit unit)
{
    Vector3 startPosition = unit.transform.position;
    Vector3 endPosition = unit.moveVector;
    Vector3 lastPosition = startPosition;
    Vector3[] path = unit.navAgent.path.corners;
    float distance = 0;

    for (int i = 0; i < path.Length; i++)
    {
        distance += Vector3.Distance(lastPosition, path[i]);
        lastPosition = path[i];
    }

    distance += Vector3.Distance(lastPosition, endPosition);
    return distance;
}

```

Is there a better way of achieving the result I want?

# Answer
**Nearest-first movement priority**

> Second draft checked the distance to destination based upon the length of the path each unit had to take. This works far more often, but sometimes still has issues.

You don't say which issues, but I think we can assumed "ending up blocked". This is important, because this approach you mention is the only sane way to begin tackling the problem. Blocking probably happens because the shortest path is taking into account other units that are moving. You have to get the shortest path as if the map were otherwise empty. You can then prioritise who gets to move first in order of decreasing shortest-path proximity, i.e. closest first.

Inspiration for this idea is road traffic. Especially at stop streets, people don't constantly stop/start to wait for one another. They know when they have right of way, and they go confidently, otherwise they know they'll hold up traffic in the long run. I think the same applies in your case. If you get the shortest path in an otherwise clear map, you should not have this problem as no-one is trying to avoid anyone else, they are just moving to the goal - but in this case, they must do so in order of nearest to furthest proximity to the goal. We do the same when traffic merges into a single lane - we tend to let the guys who *are already* in front, go *first*. This assures a smooth flow, no accidents.

**EDIT**: At worst, a hybrid approach will be required where, perhaps if a unit does get locked up by the usual method, you occasionally attempt a straight move, or even a random movement to an available neighbouring cell, in order to let things settle into a nice queue - a bit like shaking up a tin to compact it and let the small stones go to the bottom. Knowing whether an agent is "locked up" is a matter of identifying patterns in its most recent moves.

**General dev tips**

If you're able to make your code run in *interactive mode*, that is, rather than the simulation running on freely, instead you press e.g. spacebar, then another entity moves, and the simulation waits for another press to move the next entity, so you are manually stepping through what would ordinarily be each frame of processing. If you aren't already doing so, you can then see / think through exactly what is happening with the logic (even more so if you hook up to VS debugger, which will allow you to step through the logic one instruction at a time, although Unity native assembly code may be inaccessible).

You also want to ideally be able to see the map (possibly per entity) showing A\* pathing values..
> 0 votes

---
Tags: unity, c#, path-finding
---


# Question
Title: Get intersecting point of Arc, X distance from centre (Unity)
I'm no mathmetician so forgive my wording when I ask this, there is no doubt an answer somewhere but I dont even know what to search for.

I want to find the intersection point (B) as a Vector2 on a perfect circle.

If I know X, Y, A and C I assume I can use the radius and distance to calulate the position of B based on the distance between X and C somehow? (using C# if there are any methods which will accomplish this)

TIA.

# Answer
> 2 votes
I used Pythagoras to solve it

here is the code I used:

```
    // X placement can be anywhere along the x axis of the object
    float xPlacement = Random.Range(0, obstacleWidth);
    // Get the distance from the middle of the arc as a positive number and the max height of the arc(obstacle height)
    // Use Pythagoras to equate b
    float b = Mathf.Sqrt(Mathf.Pow(obstacleHeight, 2) - Mathf.Pow(Mathf.Abs((xPlacement - (obstacleWidth / 2))), 2));
    Vector2 intersect = new Vector2(xPlacement, b);

```

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


# Question
Title: Are all games made by drawing each frame?
I am a beginner learning about computer animation(for games). So far, the only method that I have come across is drawing each frame, every frame update. So at the start of every frame, the entire frame is erased, and then the things for that are needed that frame are redrawn.

My question is whether or not this method is the only one that is used for making animations and games. It seems like it is a bit inefficient. I also don't quite understand how this method would work for ***3d*** games. Could someone please explain this in more detail?

# Answer
> 73 votes
Very old games used a technique where only those parts of a frame are redrawn that changed on that frame. What I can remember, the game "Little Big Adventure" uses this technique (1994). But you can see that the game has for most of the time a static camera. only when you move out of the visible area the scene is redrawn. If you play the game you would also notice a tiny lag on that frame. On modern GPUs with modern game engines, things have changed. Everything is redrawn on each frame. Depending on the rendering technique, things might even be rendered several times. The computing power of a GPU is just incredibly high when you use it correctly. But reuse is happening. For example an engine could decide to update the shadow map only every 5th frame. Or the lighting is not updated as long as there is no change in the light sources.

# Answer
> 16 votes
# No.

At least if you include old games from the 70s which used vector displays.

For example, the widely known game Asteroids, which was originally developed for vector displays which are a fundamentally different way of rendering graphics to a screen.

> Vector monitors were also used by some late-1970s to mid-1980s arcade games such as Asteroids, Tempest, and Star Wars. Atariused the term Quadrascan to describe the technology when used in their video game arcades.

https://en.wikipedia.org/wiki/Vector\_monitor

Modern day graphics are pretty much 100% made for rasterizaton, which by definition writes the contents of a graphics buffer to the display every frame.

# Answer
> 11 votes
On the lowest level, the graphics processor on your machine will indeed compute each frame from the ground up and send it to your screen. You will only be exposed to this, however, if you manage this low-level stuff yourself \[1\] Any graphics (and with that, game-) engine however, will handle these things for you, and you are free to express the scene in terms of many entities that you could modify between frames, but will be persistent.

> ... how this method would work for 3d games ...

The elements in 3D space are persistant, the graphics engine would, again, recompute the image on your screen for any changes that happened (camera movement etc.)

\[1\] ... for example if you write your own engine \[2\] with something like OpenGL. Even in that case you would likely store persistent things between frames.

\[2\] Which is *not* an option at your current skill level.

# Answer
> 2 votes
Short answer: No.

Long story:

When I learned some game programming in school, we were taught to do the following:

Decide what fps rate we wanted in the game (30 for example).

Write some code that adds 1 to a counter for each interval (33 msec for 30 fps). This code runs concurrently with the game loop.

Then the game loop that does the calculations for the game (game state update) will reduce the same counter by 1 for each frame. But the graphics calculations and drawing to screen will only be done if the counter is at zero.

The outcome is that the graphical frame rate will adjust depending on how well the cpu handles the calculations in game. When not too much is happening in the game, calculations are easy and the graphics frame rate will be higher than the actual game state update (basically wasting cycles since we draw the same game state more than once on screen).

But then a lot is happening in game, the cpu will have more work to do and game state updates will be prioritised over drawing to screen.

Most of the time, the game will keep updating at the intended rate, but will appear "laggy" since you won't see each update on screen. This may be preferrable to the whole game slowing down because you force it do draw each update on the screen.

This was all done with C++ and no game engine, nor graphics card. Everything ran on a single core cpu. We used some libraries for 2d graphics.

# Answer
> 0 votes
Before one can say whether video games "draw" the display every frame, it's first necessary to define what is meant by "draw". There are certainly many video games certainly do not all draw every frame by assembling a bitmap from scratch; indeed, many gaming platforms never assemble full bitmaps *at all*.

There are a few approaches video games can take to generating a display. A very small number have the CPU turn the electron beam on and off or for every pixel or, for vector-scan games, set the XY coordinate of every dot to be plotted. Most games that do this do so largely for the purpose of demonstrating that the CPU is fast enough. More commonly games will have hardware which, in the absence of CPU involvement, would output some pattern of pixels or vectors to the display repeatedly. This pattern may be produced by reading data sequentially from a region of memory and interpreting each bit or group of bits as a pixel color (this is called a bit-map display). In some cases, hardware may read a byte of memory for each 8x8, 16x16, or other size region of the display and then use that byte to select a range of memory to read for pixel data (this is often called a character-map display). Some hardware platforms can overlay multiple bitmap displays with configurable positions. These are referred to as sprites.

Some platforms do not allow the display pattern to be changed while it is being sent to the screen, but instead require that all updates occur after the beam has finished drawing one frame but before it has started drawing the next. On such platforms, everything that is going to appear on a frame needs to be loaded into the display hardware before the start of that frame, and the display will be limited to showing a pattern that can be set up all at once. If the CPU were to stop running while the frame is being shown, that same frame would keep being shown indefinitely. Other platforms do allow the pattern to be changed or reconfigured while it is being drawn to the screen. This makes it possible to show a screen which is much more complicated than the video circuitry could handle by itself. This may make it possible for a hardware platform which has eight sprites to show a larger number of movable objects by setting the positions of the top eight objects on the screen, waiting for the beam has reached a point somewhere between the bottom of the first object and the top of the ninth, setting the position of the ninth object, waiting for the beam to get between the bottom of the second object and top of the tenth (if it isn't already there), setting the position of the tenth object, etc. Note that this approach would require CPU involvement during every generated frame of video, even if none of the objects visibly move, but the CPU would not be involved with "drawing" each object.

Most personal computer games use hardware configured to draw a single bitmap screen, and then draw onto that screen anything that needs to be different from what's already there. Sometimes it may be easier to draw things without regard for whether it is actually necessary in a particular case, but if code can easily tell that there's no reason for part of the screen to change, performance may be improved by skipping that part. Today's platforms are often fast enough that they could draw the entire screen many times over during the course of a frame, but historically that was not the case. The fastest possible code to write all the pixels on the Apple II computer's high resolution screen, for example, would take more than two frames, and the fastest possible code to copy all of the pixels on the Apple II computer's high resolution screen from another buffer would take twice that. Getting good performance required that games only update things that were actually changing, and that is what good games generally did.

# Answer
> -10 votes
To put it briefly, I would say not all frames are drawn but just the ones required to present your story or theme of game or game-play are. Plus the timing of the things you would want to happen at certain instances would matter.

---
Tags: 2d, 3d
---


title: Position of the prefabs not randomizing

text:
# Question
Title: Position of the prefabs not randomizing
So, I'm currently working on a game.

The objects are treated as prefabs, so every time it is instantiated, the position of the object must randomize.

```
public ObjectDisplay SpawnObject()
{
    Vector3 randomPosition = new Vector3(Random.Range(-2.5f, 2.5f), 7f);

    GameObject obj = Instantiate(objPrefab, randomPosition, Quaternion.identity, objCanvas);
    ObjectDisplay objDisplay = obj.GetComponent<ObjectDisplay>();

    return objDisplay;
}

```

The `randomPosition` is what is supposed to be changing the positions, but what happens is that the prefabs would continue to spawn from the middle of the screen. I've tried changing the position values but that didn't do much.

The code is seemingly fine, but it doesn't function the way it is supposed to. Any ideas?

# Answer
> 2 votes
Just use this form, it always works for me:

```
Vector3 randomPosition = new Vector3(Random.Range(-2.5f, 2.5f), 7f, 0f);
GameObject wordObj = GameObject.Instantiate(wordPrefab); //as GameObject;
wordObject.SetParent(parent);
wordObj.transform.position = randomPosition;

//etc.

```

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


# Question
Title: What is a good rule for blocking projectiles on a square grid?
Suppose we have a square grid, and each tile may or may not be occupied by an object. Some of those objects can be a unit that can launch a projectile at another unit. However, that projectile should be blocked if a third unit is "in the way" of the projectile path.

What I want is a rule for whether a projectile path is "blocked" from one tile to another, based on possible intermediate tiles blocked by an object. The blocking rule should satisfy the following criteria:

1) It should be based *only* on the information about the relative position on the grid of the two tiles, and the occupation of tiles by objects. Details such as *which* object is occupying a tile should not matter. Imagine the same rules would apply with placing stones on a Go board

2) It should be as obvious to the player as possible what the projectile blocking rules are. Imagine they could move a ranged unit to a tile to get a shot, and that movement is irreversible. If they later find out that the shot they wanted to make is blocked, they essentially got screwed over by a game mechanic. I don't want people to lose a game because of opaque mechanics. It should be as obvious as possible to the player that the shot they want to make form a tile is blocked *before* moving to that tile.

3) The rule should be generally applicable, not just a heuristic for a non-general set of possible scenarios. Given any two integer coordinates, {X1, Y1} and {X2, Y2} we should automatically be able to name the coordinates of *all* tiles that block those two coordinates.

4) The rule should be invariant to 4-way rotation, translation, and reflection along either axis.

Some rules would be obvious. For example, if your shot is completely horizontal/vertical (rook movement) or completely diagonal (bishop movement) and something is directly in that path, it should be blocked.

But there are cases that are not completely obvious to me, and different rules have been followed in different games. For example, what if the projectile launcher and target are separated by a knight's path? Is an object blocking the projectile if it lies on one of the two tiles that sit between the launcher and target along the long axis of separation? I have seen that being a valid block in the game Hero Academy, though it's not obvious to me that it should be.

EDIT: I realize that point #2 can be addressed with a nice UI that can inform the player of whether a path is blocked before they commit to their move. However, even *if* the UI does that, I still want it to be obvious to the player, independent of the UI. (If the player has to play a few games to learn how it works, that's fine, as long as it's easy to learn.) This aligns with my general philosophy that one should maximize the proportion of cognitive effort that goes towards strategic decision making, and minimize the proportion of cognitive effort that goes towards figuring out game mechanics on the spot.

# Answer
First, let's look at a few examples.

White tiles represent the tiles that must be empty for line of sight. The grey tiles are allowed to be full. The black line is your attempted projectile path. Notice the red edges. These are all the edges the projectile must cross to get to its target. If the projectile hits the very corner, we act as if it must cross all edges that meet at that corner. So, we simply need to test a collision between the path and all these edges.

To do this, we can use the slope. Starting and ending at the centers of the start and target tiles, a slope greater than 1 would mean we first cross to the tile above, so we determine if that tile is clear. If the slope is less than one, we first check the tile to the right. If we are firing down or left, we do the same thing, but check if the slope is negative.

It is a litter tricky for the next tile, though. So instead let's look at our line. If we say the start point is the origin, then our line is `y = mx` where m is the slope. When `x = 0.5`, it should cross over to the tile to the right. If we solve for y by multiplying by the slope, we can see how many tiles up or down we've traveled before crossing the right. In the first example, when `x = 0.5`, `y = 0.5 * 2 = 1`. Since it is in the 0.5-1.5 range, we can conclude that it must have crossed the top edge first. If it was even higher, like between 1.5 and 2.5, then we would need to count *two* tiles above instead of one. If it is exactly .5, 1.5, etc., then it is at a corner, and we include all the tiles like in the second example. We can repeat the process, testing x = 1.5 next, and so forth, until we reach the destination.
> 2 votes

# Answer
Just viewing the problem from a mathematical standpoint:

If \\$(x\_0,y\_0)\\$ and \\$(x\_1,y\_1)\\$ are your two points, let's define \\$\Delta x=x\_1-x\_0\\$ and \\$\Delta y = y\_1-y\_0\\$.

As you've pointed out, some special cases are trivial:

1. If \\$\Delta x=0\\$, it's a vertical column of tiles
2. If \\$\Delta y=0\\$, it's a horizontal row of tiles
3. If \\$\Delta x=\Delta y\\$, it's a diagonal (and possibly adjacent tiles)

Leaving these aside, you can assume w.l.o.g. that \\$x\_0\<x\_1\\$ and that \\$\Delta x \> \Delta y\\$, otherwise just switch the roles of \\$x\\$ and \\$y\\$ and reverse the \\$(x,y)\\$-coordinates of the output tuples when you're done.

Your question is answered by looking at where the line \\$f(x)=\frac{\Delta y}{\Delta x}(x-x\_0) + y\_0\\$ which connects the original two points intersects the vertical grid lines between your tiles.

The set of "blocking" tiles should contain all pairs of integer tuples \\$(i,j), (i+1,j)\\$ for \\$x\_0 \leq i \< x\_1\\$ where \\$ j-\frac{1}{2}\leq f(i+\frac{1}{2})\leq j+\frac{1}{2}\\$, as illustrated in the lazy drawing below.

Whether you choose strict inequalities in the last expression or not determines what happens when the line exactly passes through a point where two grid lines cross. I'd recommend against using strict inequalities since it would allow a projectile to slip through the "gap" between two diagonally aligned blocks, such as shooting from (0,0) to (1,1) when there are walls on (0,1) and (1,0).

Needless to say, if you were to implement it exactly this way you'd end up counting a lot of tiles twice, so there's still a bit of work to be done in translating this idea into an efficient algorithm.
> 1 votes

---
Tags: game-design, path-finding
---


title: Multiple mains in vertex shader, GLSL

text:
# Question
Title: Multiple mains in vertex shader, GLSL
I have a renderer where you can define passes where you pick the shader, and a signal, each object can register a listener to that signal in order to draw himself, the problem comes when some objects are normal meshes, others are sprites, some have skeletal animations, some don't. I was wondering if I could pack within the same vertex shader many different optional main functions, and pick the correct one for each object.

If there is no way, I would have to compile a different shader for each of the types and bind it from zero for all objects, even though all fragment shaders are the same.

# Answer
> 0 votes
No, I don't believe there's any way to have different `main()` functions in one shader. But you do have a few options. You could pass in a `uniform` that the `main()` function uses to decide which other function to call. Something like this:

```
uniform int shaderType;
const int kShaderType_X = 1;
const int kShaderType_Y = 2;
const int kShaderType_Z = 3;

vec4 doShaderTypeX()
{
    // ... do whatever you need for the first shader type
}

vec4 doShaderTypeY()
{
    // ... do whatever you need for the second shader type
}

vec4 do ShaderTypeZ()
{
    // ... etc.
}

void main()
{
    vec4 result;
    if (shaderType == kShaderType_X)
    {
        result = doShaderTypeX();
    }
    else if (shaderType == kShaderType_Y)
    {
        result = doShaderTypeY();
    }
    else if (shaderType == kShaderType_Z)
    {
        result = doShaderTypeZ();
    }
}

```

Your other solution of making several different programs that share a fragment shader but have different vertex shaders will also work. If you make them all at start up, you only need to make them once. Or you could do it lazily and make each one the first time it's required, and keep it around for later use.

---
Tags: opengl, glsl, vertex-shader
---


# Question
Title: How can I make object to follow first person character and the camera without making the object child?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectFollowCamera : MonoBehaviour
{
    public Transform cameraToFollow;
    public Transform objectToFollow;
    public float distanceFromCamera;

    private void Update()
    {
        objectToFollow.position = new Vector3(cameraToFollow.position.x,cameraToFollow.position.y,cameraToFollow.position.z - distanceFromCamera);
    }
}

```

This script is attached to a empty GameObject. The objectToFollow will move once i'm moving the Player with the keys. But when i'm rotating the camera of the player around the objectToFollow is not moving.

The Player have attached to it: Character Controller , First Person Controller , Rigidbody

And the Camera is child of the Player.

# Answer
> 0 votes
You don't want to immediately just snap the follower's position to the target's position. It won't look as good, and won't function like following in the sense that the follower moves towards the target. You need to use interpolation and rotation to achieve this. These are the steps that I can think of that worked for me:

1) Interpolate the follower's position to some position near the target's position.

2) Take into account any grounds or floors or walls around the follower. You can actually put a second Character Controller on the follower and move that. If you can't use that, then you can always use some different collider to detect collisions. Should work just as fine.

3) Rotate to look at, or look in any direction you would like, while doing number one.

Do this, and you should be good to go!

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


# Question
Title: How to keep clicks from menu from interfering with game state?
I ran into a problem coding my game in which when I click the play button on the newly implemented menu, it also creates a bullet from my player. The player and the menu both rely on the mouse input. How would I make it so that this doesn't occur? Perhaps how would I delay input from the mouse for a second until after the game starts?

Thank you.

```
public static boolean pressed = false;

public void mousePressed(MouseEvent e)
{
    int mx = (int) e.getX();
    int my = (int) e.getY();

    if(Game.state == STATE.MENU) {
        if(Menu.playButton.contains(mx, my))
        {
            // Pressed Play Button
            pressed = true;
            Game.setState(Game.STATE.GAME);
        }

        for (int i = 0; i < handler.object.size(); i++)
        {
            GameObject tempObject = handler.object.get(i);

            if(tempObject.getId() == ID.Player && pressed == true)
            {
                handler.addObject(new Bullet(tempObject.getX()+16,
                        tempObject.getY()+24, ID.Bullet, handler, mx, my, game));
                bullets_shot += 1;

            }
        }
    }
}

```

# Answer
> 0 votes
Just setting up a flag that indicates if the menu is open should be enough.

The player should check the flag state, and in case it's true, don't shoot.

EDIT:

I updated your function adding an else condition to the check on the game state:

```
public void mousePressed(MouseEvent e)
{
    int mx = (int) e.getX();
    int my = (int) e.getY();
    pressed = true;

    if(Game.state == STATE.MENU) {
        if(Menu.playButton.contains(mx, my))
        {
            // Pressed Play Button
            Game.setState(Game.STATE.GAME);
        }
        if(Menu.helpButton.contains(mx, my))
        {
            JOptionPane.showMessageDialog(null, "W: up, "
                + "S: down, D: right, A: left, "
                + "ESC: Pause ");
        }
        else if(Menu.quitButton.contains(mx,my))
        {
            // Pressed Quit Button
            System.exit(1);
        }
    }
    else{ //<--- Added this else
        for (int i = 0; i < handler.object.size(); i++)
        {
            GameObject tempObject = handler.object.get(i);

            if(tempObject.getId() == ID.Player)
            {
                handler.addObject(new Bullet(tempObject.getX()+16,
                        tempObject.getY()+24, ID.Bullet, handler, mx, my, game));
                bullets_shot += 1;
            }
        }
    }
}

```

# Answer
> 0 votes
At this point in your code:

```
for (int i = 0; i < handler.object.size(); i++)
    {
        GameObject tempObject = handler.object.get(i);

        if(tempObject.getId() == ID.Player)
        {
            handler.addObject(new Bullet(tempObject.getX()+16,
                    tempObject.getY()+24, ID.Bullet, handler, mx, my, game));
            bullets_shot += 1;

        }
    }

```

You do the bullet stuff while in the `Game.state == State.MENU` state. You need some other state like `State.PLAY` And only be able to create bullets while actually in the game. Not the menus. Hope this hopes! :)

---
Tags: mouse
---


# Question
Title: Why doesn't anything run after the yield return new line
I am trying to make a fade to another scene in unity when I came across a problem. For some reason when the coroutine begins the Ienumerator it only runs half of the Ienumerator Method which is only the anim.SetForBlue line. Heres my code.

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

public class Loseforcube1 : MonoBehaviour
{

    public GameObject blueWinPanel;
    public Animator animForBlue;
    // Use this for initialization
    void Start()
    {
        blueWinPanel = GameObject.Find("Blue win panel");
        animForBlue = blueWinPanel.GetComponent<Animator>();
    }

    public IEnumerator WaitTillNextScene()
    {
        animForBlue.SetTrigger("FadeBlueWin");

        yield return new WaitForSeconds(3.9f);
        SceneManager.LoadScene(2);
    }

    void OnTriggerExit()
    {
        if (GameObject.Find("Cube Player 2"))
        {
            StartCoroutine(WaitTillNextScene());

        }
    }
}

```

# Answer
How have you determined that it "only runs half" of the method? You've asked it to wait 3.9 seconds, if you put a breakpoint and tried to debug, then of course the method will hit the yield statement and continue as if it never executes the rest of the function.

The problem is that execution will continue *3.9 seconds later.*

For example, I have this script:

```
public class TestCoroutine : MonoBehaviour {
    void Start() {
        StartCoroutine(WaitTillNextScene());
    }

    public IEnumerator WaitTillNextScene() {
        Debug.Log("Time before yield: "+ Time.time);
        yield return new WaitForSeconds(3.9f);
        Debug.Log("Time after yield:  " + Time.time);
    }
}

```

And this is the output I get:

But there's *almost four seconds* between those two debug lines.

If the second scene isn't loading, your problem is likely elsewhere, for example, do you have three scenes in your build settings? Are you accounting for the delay it takes for a non-asynchronous `LoadScene` to load the scene? Depending on the size of the new scene, this could take much longer than 4 seconds!
> 2 votes

# Answer
Well, if you think about what the `return` keyword does, it returns, or in other words, exists the function at that specific point in execution. So that code that is below the `yield return` is never called, because it simply can't be reached.

If you are wanting to execute that piece of code, then putting it above the `yield return` is what you need to do. Hope that clarified your issue. Again, nothing can be run after the `return` keyword. That's most likely why it's not working for you. :)
> -2 votes

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


# Question
Title: Steamworks Networking with LibGDX / Java
I have recently found out about Steamworks SDK and after reading through some of the documentation and information from other sources I was left with a few questions.

I found Steamworks because I was interested in how Steam handles multiplayer in games, like co-op games with the lobby creation and all.

This is because of a game I'm developing which is planned to be a 2-player co-op puzzle game. When it comes to networking, how would I program the game to use Steamworks lobby creation? Would I just program it normally with a client server? Because normally that would require atleast one of the users to forward their ports but would the Steamworks work around that? Or do I implement the Steamworks right away?

This would be cruicial to know since adding networking late in to the development is very difficult. Thank you in advance, any links or help is much appreciated! Also, I'm progamming in Java(LibGDX).

# Answer
> 1 votes
To avoid port forwarding and play a 2-player game, it is best to choose the Steam P2P Network API. It uses libjingle to punch through a NAT, so port forwaring is no longer necessary. It's a bit slower than, say, a UDP socket connection, but it's still faster than you need for your case.

You can use Steamworks4j to use the Steamworks API in Java. There are also some examples of how to use Steam P2P and Lobbies. For more information, see Steam API Doc

---
Tags: java, libgdx, networking, multiplayer, steam
---


# Question
Title: My game crashed... Access Violation (0xc0000005)
I guess this is the first official crash I've had in Unity (that is not just an infinite loop.) The game works just fine in the editor but when build and run it, the game won't even start.

I just keep getting this error message:

So I check the folder specified but I have no idea what I'm looking at if I'm completely honest with my self. I see a bunch of directories and stuff but that's about it. I don't know how to read an error log but I'd like to. This whole game is a learning experience so I would to learn how but Idk what to do.

this is the error log : Here

If need be I'll put it in the question but I'd like to avoid making this too long. If you have any questions about my code you need to know let me know.

# Answer
> 0 votes
Well this is embarrassing... I had some compiler errors showing up in the editor from me converting some game Objects to transforms. I changed them back to gameObjects and everything works fine. I was just trying to save a little memory. but thank you guys for your advise down in the comments.

# Answer
> 11 votes
I see you solved your own problem. However, I would like to explain what are you looking at, and what to look for in an error log like the one you received, in case you get a similar error in the future.

There are many type of error logs, and this one is quite low level. It is difficult to understand what the problem is with a large game with such an error log, but there are some clues you may use to help yourself.

The first line is the Unity Player version. This is relatively important, as an error may be linked to a precise version of the player that you're using. In general, always try to make sure you're using the last version of Unity to make your games.

Then you get the error type and location. In this case, the error is:

```
test 8.exe caused an Access Violation (0xc0000005)
  in module test 8.exe at 0023:01275744.

```

In here, you can see that the error is an access violation, which corresponds to code `0xc0000005`. Regardless of the error code, it might be useful to search online for it, and that way you can at least know whether or not the error is related to your program or not.

In this case, in Windows, error `0xc0000005` may be related to closing handles that are currently in use, that is, you're using a handle in one thread and you're closing it in another at the same time. If you're not doing anything like this, then it is likely that this is an error in the player itself.

Then you see the module that caused the error, and the program location. In this case, the module is `8.exe`, which is the same executable file. It is perfectly possible that the error was not caused in the executable file, but in a DLL that you loaded.

The next section is some general information regarding to the state of the machine when the error happened:

```
Error occurred at 2015-11-01_000136.
D:\..........\8.exe, run by Foo.
32% memory in use.
0 MB physical memory [0 MB free].
0 MB paging file [0 MB free].
0 MB user address space [3746 MB free].
Read from location 7220799c caused an access violation.

```

If you see something like "100% memory in use", you may want to think that the problem was caused by filling up the memory.

Also, you can see that the actual error happened when trying to read from memory location `7220799c`. This seems to be a normal memory location, but if the conflicting address was `00000000` or something like that, then the problem is a null pointer access.

Then you see the runtime context. This contains the CPU registers, the bytes at CS:EIP and the stack. These are snapshots of several parts of the computer at the exact moment the program crashed.

First you get the CPU registers. Unless you have a disassembly of the program, it's very difficult to diagnose something like this, but if you see EIP (Instruction Pointer) set to 0, then it probably means you're calling a null pointer. Also, if EBP (Base Pointer) and ESP (Stack Pointer) are vastly different, then it probably means you had a stack overflow.

Then, you get the bytes at `CS:EIP`. This is what the instruction pointer is pointing to. This is the actual program code that was meant to be executed. Not much to see here, but you may want to decode the actual bytes and see what the actual instruction is about. In this case, `f3 0f` is a "Shift Packed Data Left Logical" MMX or SSE2 instruction. If you see something like pure zeroes or pure `f`s in here, then it probably means you're executing invalid code. Check the value of `EIP` in the context above.

Then you get the stack. The currently active stack frame is what you have from `EBP` to `ESP`. In this case, there is not much to see here, but if for example, you see a truncated large text in there, then it is possible that you are experiencing a stack overrun.

Finally, you get a list of the modules that are loaded into memory with your program. Look at this list to find DLLs that you are not expecting (like viruses, or antiviruses), or old versions of DLLs that you are expecting.

# Answer
> -1 votes
I have had something like that for 2 months. I solved it myself.

Try do download new graphic card drivers from nvidia or ati, then use software called Display Driver uninstaller, uninstall all your graphic card drivers then restart PC, install new ones and restart again.

It is possible that you had more than 1 card drivers installed because u recently changed hardware or something.

My rust is fine now :) I hope it helps

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


# Question
Title: Scale a sprite as it moves down a triangle
I have a sprite that is inside a triangular like shape. How to make the sprite decrease in size as it moves down the shape?

https://ibb.co/gjc6oS

# Answer
> 1 votes
If I remember sprites in Unity have a variable local scale. You just have to apply the intercept theorem on the scale.
Basically: `(oldScale.y/oldDistanceToPivotpoint) = (newScale.y/newDistanceToPivotpoint)`
Same works for scale.x.
You can do this every frame.
Your distanceToPivotpoint is simply the distance from the center of your sprite to the lower corner of your triangle.

# Answer
> 0 votes
One technique that you could try is the following: When you move the sprite downwards within the triangle, you could decrement the sprites lower width, then it's upper width, gradually; ultimately creating that sucking in effect of the sprite moving through that shape.

---
Tags: unity
---


title: Creating paralax background in Unity3D

text:
# Question
Title: Creating paralax background in Unity3D
I am trying to create some parallax background in Unity in 2D mode by tweaking offset of the background material and using tiling. I used this tutorial https://www.youtube.com/watch?v=nGw\_UBJQPDY as a reference, but my material doesn't tile like one in the tutorial. Any tips for creating infinite background with tiling and tweaking offset? What am I doing wrong?

# Answer
> 4 votes
When importing a texture, you can set two different 'wrap modes'. These tell the renderer what to do when the UV map goes past the edges of the texture.

Yours is set to 'clamp', which will just stretch the pixels on the edge. This is useful for preventing artifacts when rendering sprites, but in this case you will want to set it to repeat.

Note that in 2D projects, it defaults to clamp, whereas in 3D projects it will default to repeat.

More info about wrap modes in Unity.

---
Tags: unity, 2d, textures, materials
---


# Question
Title: Libgdx can't read .ttf file when running Android configuration
Firstly, I am aware that a similar question was asked some time ago that went unanswered. Currently, it has multiple upvotes but no answer.

The error

```
com.badlogic.gdx.utils.GdxRuntimeException: Error reading file: data/font/font1.ttf (Internal)
...
Caused by: java.io.FileNotFoundException: font/font1.ttf

```

occurs when I use the class `FreeTypeFontGenerator` provided by Libgdx as a extension to use freetype fonts(link). This is the line in my project that caused error:

```
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("font/font1.ttf"));

```

I can be fairly certain that my path to the .ttf is correct, as the desktop configuration runs perfectly, showing the font as desired.

My guess: I didn't include the `freetype` extension when creating this libgdx project. When following the tutorial to include it (that is, adding the `freetype` dependencies in build.gradle), something somehow went wrong. But even this is not convincing enough.

`build.gradle`:

```
project(":desktop") {
    apply plugin: "java"

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
        compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"
        compile "com.badlogicgames.gdx:gdx-tools:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-desktop"

    }
}

project(":android") {
    apply plugin: "android"

    configurations { natives }

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-arm64-v8a"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86_64"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-arm64-v8a"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86_64"
        compile "com.badlogicgames.gdx:gdx-freetype:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-arm64-v8a"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86_64"

    }
}

```

# Answer
This solved it for me, even though not the same as the similar question.

My actually font filename in the `font` folder is `font1.ttf`. After changing it to `font.ttf`, the problem resolved itself. I don't understand why it worked, as I think it is okay to include numbers and uppercase in a file name.
> 0 votes

---
Tags: java, libgdx, android
---


title: Special moves using mouse movement?

text:
# Question
Title: Special moves using mouse movement?
Recently, I accidently broke my PC controller and I was *forced* to play Skullgirls using the keyboard. Needless to say, it sucked. Fighting games are the kind of games where a controller is (almost objectively) better to use than a keyboard, just like how keyboard + mouse is better to use for FPS games than a controller. Keyboards just don't allow the same freedom a controller offers for fighting games, especially because of the analog stick.

So while I was getting my \*** kicked and (of course) blaming only my keyboard instead of myself, I had an idea: why don't fighting games use the mouse, too? Couldn't the mouse movements be used as the directional input for the special moves instead of the arrow keys? Examples:

* Hadouken - quick flick with the mouse into the direction you're facing
* Shoryuken - a steep upward curve towards the direction you're facing
* Roundhouse kick - a quick circle motion

What are the advantages and limitations using the mouse in such a way? Are there any examples out there? Maybe there are some limitations I'm not seeing right now? To me, this looks like a way to give players the same freedom in fighting games with keyboard + mouse as a controller would provide, so I'm surprised I don't see more fighting games with that control option.

# Answer
> 1 votes
When you use the controller's analog stick, you use your fingers. Your fingers are very fast and they don't have to move that much. Combine that with the fact, that there's a maximum angle the joysticks can bend, which allows for fast stops and you get something with a high precision, speed and the ability to change direction very fast.

Since you use your wrists or arms when you move a mouse, you can't get the same combination.

Most fighting games also use the left joystick and the right (non-directional) buttons. Most PC users on the other hand use their right hand for 2D movement (mouse) and their left for buttons (WASD). Ask any professional fighting game player about what getting the second player feels like (most arcade machines put the joystick and the buttons on different sides for the second player and it's disorienting).

---
Tags: control
---


# Question
Title: Can somebody explain this behavior in pygame?
I have an image that I'm rotating and moving

And when the rotation angle is negative the image moves as expected.

But when the angle is positive it moves it's origing point to the left

Can anybody explain this behavior, and how to solve it?

Here is the code

```
import pygame, sys
import math

screen = pygame.display.set_mode((700, 400))
wrench = pygame.image.load('prueba.bmp')
white = (255,255,255)

ox = 20
oy = 32
running = True
posX = 100 - ox
posY = 100 - oy

pygame.init()
while running:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        running=0
        screen.blit(wrench, (posX, posY))
    if(pygame.time.get_ticks() <= 20000):
        screen.fill(white)
        t = pygame.time.get_ticks() / 1000
        ang = math.degrees(math.pi / 2 * math.cos(math.pi * t))
        #ang = math.pi / 2 * math.cos(math.pi * t)
        print(ang)
        posX = 100 + (50 * math.cos(math.pi * t)) - ox
        posY = 100 + (20 * math.sin(math.pi * t)) - oy
        rotated_wrench = pygame.transform.rotate(wrench, ang)
        screen.blit(rotated_wrench, (posX, posY))
    pygame.display.flip()

```

# Answer
> 1 votes
This line is setting the X coordinate of the bliting:

```
posX = 100 + (50 * math.cos(math.pi * t)) - ox

```

The cosine is positive from 0 to 90 degrees and 270 to 0, which is the right side of a circle; and negative otherwise.

This is making the value to oscillate between `100 + 50 - ox` and `100 - 50 - ox`

If you want to keep the horizontal position to not oscillate in both directions, you should use the absolute value:

```
posX = 100 + (50 * math.fabs(math.cos(math.pi * t))) - ox

```

---
Tags: python, pygame
---


# Question
Title: Changing texture offset in unity by script
I am trying to change texture offset in a material by a script to create a parallax effect, but it doesn't move a bit no matter what I am trying. Any tips for this case? Or am I missing something?

# Answer
> 1 votes
Figured it out. Should have used SetTextureOffset method. https://docs.unity3d.com/ScriptReference/Material.SetTextureOffset.html

---
Tags: unity, textures, vector, scripting, parallax-scrolling
---


# Question
Title: How to implement a restart button after game over?
How would one go about implementing a method in which it calls the game to restart by pressing a button after game over?

I have my game class which puts the player in and starts the enemy sequence shown below. I already have my restart button as shown in the code snippet from the mouseinput class below and the problem is I don't know what to put in the area where the question marks are to get the thread to restart, if I'm using the appropriate language or not I'm not sure. I'm new please bare with me.

Thank you. What I'm doing now isn't working because it's glitching and the fps is shaky.

```
public Game()
{
    new Window(1000, 635, "Galaxy Monkeys", this);
    start();

    handler = new Handler();
    camera = new Camera(0, 0);
    this.addKeyListener(new KeyInput(handler));
    menu = new Menu(this);

    BufferedImageLoader loader = new BufferedImageLoader();
    sprite_sheet = loader.loadImage("/spritesheet.png");

    Enemy enemy = new Enemy(-20, r.nextInt(563), ID.Enemy, handler, this);
    Monkey p = new Monkey(500, 250, ID.Player, handler, this);

    handler.addObject(p);

    for(int i = 0; i < enemy_count; i++)
    {
        handler.addObject(enemy);
    }

    this.addMouseListener(new MouseInput(handler, camera, this));
    background = loader.loadImage(("/background.jpg"));

    INSTANCE = this;
}

```

Restart event on MouseInput.java:

```
public void mousePressed(MouseEvent e)
{
    int mx = (int) e.getX();
    int my = (int) e.getY();

    if(Game.state == STATE.GAMEOVER)
    {
        if(GameOver.restartButton.contains(mx, my))
        {
            // Pressed Restart Button
           Game.setState(Game.STATE.GAME);
            Game.INSTANCE = new Game();
        }
    }
}

```

# Answer
> 1 votes
I'm not that familiar with developing on java, but I'd say you shouldn't create a new instance of `Game` since it is the class that is handling the game window and the rest of the instances (camera, menu..)

Right now, all the game info is initialized withing the `Game` class constructor, which is not convenient, since if you want to start all over again, your only alternative is to instantiate a new Game instance.

I would separate the logic of the scene from the logic of the engine, at least by creating new functions.

Seeing your project, I'd approach it like this:

* `SetupScene()` \- I'd create this new function to initialize the player and the enemies
* `ClearScene()` \- In this function you'd dispose of all the entities created in your current game state. This would include the enemies created in the `SetupScene()`, the player, and any new enemy created after the scene setup.
* `Game()` \- Keep the constructor to initialize the components that are the foundations of your engine. Once all components are initialized, call SetupScene()
* `Restart()` \- You would call this function when you wish to restart the game. In it you will call `ClearScene()` to remove all entities, and then call `SetupScene()` again. You could even add a loading screen here, in case the operation takes too much time.

When building big systems, it's important to keep things modular and clear. Even if it's your own system and you know perfectly understand and know how to work with it, yourself in 2 years or even 2 months could be extremely confused.

Not really game development, but I'd recommend this book to anyone who wants to step up their programming expertise: Clean Code

---
Tags: java
---


# Question
Title: What design pattern should be used when there are a lot of different possible jobs?
Some background information on what I am trying to accomplish. I am creating the game in Unity using C#. Basically, I am trying to create an RPG type of game where it really harps on the idea of a lot of different possible classes/jobs(I will call them jobs so not to confuse anyone). Basically, every job will have its own unique set of skills and can only do certain tasks, not dissimilar to a lot of games out there. However, the way I see most of the advice given down this path is simple inheritance, mostly because the user is only trying to implement 2 or 3 unique jobs. I feel as though this is just the easy answer that ends up causing a lot more headaches in the long run when you have lots of different jobs to implement.

So my main question is, what design patterns would someone use when there are a lot of different jobs that the programmer needs to implement?

# Answer
This question is hard to answer without knowing exactly what your game system does and does not allows your "jobs" to do.

But usually I would use composition instead of inheritance. There would be just one class `Job`. Each instance of `Job` has a `List<Skill> skills` (or other appropriate data-structure). You are not saying much about what "do certain tasks" actually means in your game. Does each skill represent exactly one task which the player can perform with some input action? Then `Skill` would have an abstract method `perform()` or `performOn(GameObject target)`. Or can a skill actually provide more than one task? Maybe even depending on some other factors? Then `Skill` might need a method which returns a `IEnumerable<Task>`.

But either way, I would try to use as few classes inheriting from `Skill` as possible. Skills with similar functionality should use the same class with different values.

For example, let's say you have skills like `Woodcutting`, `Mining`, `Foraging` and `Fishing`. Having one of those skills allows the player to perform the "extract resource from resource node" task and this task is mechanically identical for each skill. They just differ by the kind of node they work on. I that case I would just have one class `ResourceGatheringSkill` inheriting from `Skill`. The different instances of this class would differ by a property which says which resource nodes it works on.

You could even go a step further and move the logic to decide what can and can not be gathered to the resource nodes. In that case the resource gathering skills become even simpler. The script on the resource nodes would just check if the job of the player-character has a skill with a specific name. In that case `Skill` would just need a property `name`, nothing more.
> 3 votes

---
Tags: unity, design-patterns
---