# Question
Title: How to assign GameObject to a instantiated prefab?
GameObject A (Panel - CraftSystem) is in the scene already as seen on the screenshot (Screenshot). I then instantiate the GameObject B (WorkingStation) which has a public GameObject craftSystem. So I need to assign A to B after B is instantiated.

this is the instantiated object code:

```
 using UnityEngine;
 using System.Collections;

 public class WorkingStation : MonoBehaviour
 {

     public KeyCode openInventory;
     public GameObject craftSystem;    //Game Object that needs to be assigned from hierarchy
     public int distanceToOpenWorkingStation = 3;
     bool showCraftSystem;
     Inventory craftInventory;
     CraftSystem cS;

     // Use this for initialization
     void Start()
     {
         if (craftSystem != null)
         {
             craftInventory = craftSystem.GetComponent<Inventory>();
             cS = craftSystem.GetComponent<CraftSystem>();
         }
     }

     // Update is called once per frame
     void Update()
     {
         float distance = Vector3.Distance(this.gameObject.transform.position, GameObject.FindGameObjectWithTag("Player").transform.position);

         if (Input.GetKeyDown(openInventory) && distance <= distanceToOpenWorkingStation)
         {
             showCraftSystem = !showCraftSystem;
             if (showCraftSystem)
             {
                 craftInventory.openInventory();
             }
             else
             {
                 cS.backToInventory();
                 craftInventory.closeInventory();
             }
         }
         if (showCraftSystem && distance > distanceToOpenWorkingStation)
         {
             cS.backToInventory();
             craftInventory.closeInventory();
         }
     }
 }

```

this is the code used to instantiate it:

```
 public void SetItem(GameObject b)
 {
     hasPlaced = false;
     currentBuilding = Instantiate(b).transform;
     placeableBuilding = currentBuilding.GetComponent<PlaceableBuilding>();
 }

```

Ive tried to do `craftSystem = GameObject.FindGameObjectWithTag("CraftSystem");` but it does not work as after i instantiate the object B the public GameObject stays empty and i get null reference error to this line "craftInventory.openInventory();"

Ive also tried `craftSystem = GameObject.Find("Panel - CraftSystem(Clone)");` and get the same result. public GameObject craftSystem still stays empty and i get null reference error.

# Answer
> 0 votes
If i understand correctly, you want to assign a GameObject (a prefab, let's call it **A** ) to another prefab, which you just instantiated (let's call it **B**).

There are 2 ways to do that :

1. IF, the Prefab **A** is present in your game's hierarchy, then you can get it's reference using GameObject.Find or GameObject.FindGameObjectWithTag, and then assign it to your GameObject variable (*craftSystem*, in your case).

After Looking at the screenshot, I see that the Prefab **A** is instantiated at run-time and is not present in hierarchy at compile time (hence suffix *clone*).

Add the following line inside Start function, before anything else

craftSystem = GameObject.Find("Panel - CraftSystem(Clone)");

2. IF, the Prefab **A** isn't present in the hierarchy, then you need to put that Prefab inside a folder called **Resources**, then call Resources.Load, on the saved Prefab (**A**), with this you'll get a reference to that prefab, which you can then assign to your *craftSystem* variable.

P.S. If this is not what you're looking for, then you need to make your question more clear, and i'll update my answer according to that.

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


# Question
Title: Three points to normal notation (interpret the math)
From: Euclidian Space: Planes, I see the formula:

> **Convert Three points to normal notation**
>
> N = (p1-p0) × (p2 - p0)
>
> d = -N • p0^2
>
> where:
>
> N = normal to plane (not necessarily unit length) d = perpendicular distance of plane from origin. p0,p1 and p2 = vertex points x = cross product

When calculating the distance to the origin from the plane (d)... A) how is the p0 squared? B) how do I resolve the dot product of the vector (-N dot p0^2) to scalar distance?

# Answer
> 2 votes
Thanks to @DMGregory, I think I have it.

```
n = (p1 - p0).cross(p2 - p0);
n = normalize(n);
d = n.dot(p0);

```

Where p0, p1 and p2 are points. n is the (unit) normal vector and d is the distance to the origin from the plane.

---
Tags: 3d, mathematics, vector
---


# Question
Title: Client/Server networking for mobile games
I am currently considering the pros and cons of two different approaches for networking an Android game.

First, I will specify some details about the game and its requirements, and then I will explain the considered approaches.

The game is a mobile game currently being developed for Android (but may be a port to iPhone in the future). The game is being built on the Unity3D engine using the Android Basic license, which does not allow direct access to .NET sockets.

The core functionality of the game consists of basic matchmaking, and the gameplay during a match. Matches are turn based. When another player finalizes his/her turn, each other player will receive the update and will see it rendered. The client will collect the turn from the player and send it off to the server. Nothing too special here.

The first approach I am considering is a mixture of a REST service and Google's Cloud2Device Messaging. With this, the general flow would be:

* Collect the turn from the user.
* Send the turn to the server via an HTTP POST to a REST service.
* The server processes the turn and saves the match state, assigning it an "event id."
* The server uses Cloud2Device messaging to send a notification down to each client. The notification consists of an "event id."
* Upon receiving the notification from the Google servers, the client will perform a GET to the game server's REST service asking for details for the respective event id.

Given this approach, the pros I see are:

* REST services are easy to write (much of my experience is in REST services).
* No custom socket work, as Google's service is used to notify clients.
* Easy to implement within Unity's Android Basic license.
* Cloud2Device Messaging allows an app to be "woken up" if it is not currently running (could be helpful in certain cases, I suppose).

The cons I see are:

* Networking code is at the mercy of Google's service.
* If Google delivers the "turn start" notification too late, a player may miss his/her turn.
* Porting to the iPhone would require a heavy rework of network management.
* Google likely will begin charging for Cloud2Device Messaging.

The alternative approach is to use a workaround to the lack of .NET socket support within Unity Android Basic. This would basically use Android's built-in socket support mixed with some custom-made Unity plugins to allow sending/receiving of network messages.

The general flow of this approach would be a straight-forward client/server socket approach, where each user playing the game has a connected socket.

The pros I see for this are:

* All networking is handled by my services (not Google's).
* Easier porting to other platforms (iPhone, iPad, etc.)
* Potential to show more real-time player actions, rather than receiving all turn data after the turn has been committed.

The cons I see are:

* Very little personal experience writing socket servers for games (this point scares me the most right now).
* Debating whether this is necessary or not, as a turn-based game does not exactly need constant socket communication. A REST service may be all I need.
* Constant socket communication may require an unnecessary amount of CPU or network data for a mobile device (or does having a socket open not require many resources expect when transmitting data?).

My observations and speculations aside, can anybody weigh in on this issue? I do not have much experience when it comes to game networking (especially for mobile) and would much appreciate advice on this issue. Let me know if more details are needed.

Thanks!

# Answer
> 1 votes
I've used (.NET) sockets in Unity3d on iPhone and it was pretty simple. Nothing to be scared about. Open connection should not (noticeably) consume resources when no transmission takes place, so that's not an issue. In fact, it might be that opening new connection for every request consumes *more* power and bandwidth.

That said, for a turn-based game using a web-service is probably simpler. As I understand, the only problem with this approach is notifying the client that opponent's turn ended. Maybe you can get away with simple polling from the phone?

# Answer
> 0 votes
I would not recommend "reinventing wheels" here. Backend functionality is very similar regardless what is your app genre. you need to manage XP, Players, Levels , coins, virtual economy, watch retention reports, etc'.

I would recommend checking existing platforms that can save significant R&D time and money. My recommendation to game entrepreneurs is to focus on what suppose to bring them money - THE GAME.... and to use existing solutions for everything else.

---
Tags: iphone, android, networking, server, mobile
---


# Question
Title: Why doesn't x fully reach y in while(x < y)
I have the following code in a coroutine

```
float percent = 0;

while(percent < 1) {
    Debug.Log(percent);

    percent += Time.deltaTime;
    yield return null;
}

```

However, percent never reaches or passes 1 (stops around ~0.98). How can I make sure that the while loop doesn't end until percent reaches 1?

# Answer
*This answer was initially a simple comment. I poster an answer as **OP said it fixed his problem**.*

When using floats you should append a `f` at the end of the numerical value, in your case :

```
float percent = 0f;

while(percent < 1f) {
    percent += Time.deltaTime;
    yield return null;
}

```

It is possible that your problem **has nothing to do with that, but it is just good practice!**
> 1 votes

# Answer
Your log function is **before** the increase of the value of `percent`. So the final value of percent is never logged.

The final time round the loop would look like this

```
while(percent < 1) {
    Debug.Log(percent); //percent is 0.98, 0.98 is logged

    percent += Time.deltaTime; //deltaTime is say 0.03, so percent is now 1.01
    yield return null;

    //percent is 1.01, loop will exit and 1.01 is never logged
    //(despite being the value of percent at the end of the loop

}

```

`percent` is now larger than 1, but its not logged after the loop, just at the **beginning** of each loop
> 11 votes

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


# Question
Title: How do games programmatically manipulate 3d models?
The title says it all. An artist makes a 3d model of a character. How does a programmer use the model to make the character run around?

# Answer
There are multiple ways to do this:

The first and the most popular way is to create a skeleton for the model, then use this skeleton to move around the vertices of it. This is also usually done by the artist, because it needs to contain what areas are affected by which bone.

When the animation is done the artist saves it in a file (for example the COLLADA file format is very popular between beginner game programmers, because it is readable by humans, but because it's based on XML, it's big, so bigger game companies use files like .fbx).

The skeleton is made out if bones. The artist can define which vertices need to be moved by giving them a weight. The higher the weight, the higher the amount of movement it produces when the specific bone is moved. There's a separate weight table for each bone, so the same vertex can be affected by multiple bones

The second way is called morphing. It's more ancient but is still used today, because it doesn't require the use of a skeleton, thus it's better for things like the face of a model, or when you need to move the separate vertices around. Instead of creating a skeleton, the artist creates the states the model can be in, then the program loads in each frame and interpolates between them in the vertex shader.

Literally any model format is able to store an animation this way in the form of multiple separate files (like in .obj files), but some are able to handle them natively inside 1 file (one of the most famous one between beginners is id Software's .md2 format).

The third method of animating something is called procedural animation. It's not widely used, because it doesn't result in humane movements. It can be used when animating water or grass or any other natural objects, that has a pattern in it's motion.

The fourth and arguably the most complex is muscle-based animations. For example GTA IV used this engine, which calculates motion using a defensive AI and a skeleton structure. It's based on the first technique but it doesn't require the artist to animate the body. It's kind of like ragdoll but with better motions.

The fifth way is ragdoll. You probably know this, there are even games which almost purely rely on this, like the infamous Goat Simulator, but most games use it for dead characters. This also requires the artist to create a skeleton, but moving the joints is done with algorithms. These algorithms take max angles and drag into consideration.
> 12 votes

# Answer
Animatable 3D models come with a skeleton (either the modeller or animator does this step of modelling, since it's in a bit of no man's land).
The skeleton is made of bones, relatively positioned between eachother, and every bone is mapped to a set of vertices of the 3D model, with influence values ranging from 0 to 1 (0.2, 0.5, etc.).
When this is done, the animator makes an animation, which can be a separate file or be stored within the model's file itself depending on format.
Animations are basically a set of instructions to each bone, telling them when to move or rotate, and how much.
By moving the bones around, you indirectly move the model's vertices around.

this is a very dumbed down explanation, and there are many different ways to do basic and more advanced animation, some being completely programmatic, however nowadays you won't find many animated models in a game without a skeleton (N64 models didn't have skeletons i believe, instead the model pieces worked as the skeleton)
> 7 votes

---
Tags: rigging, 3d-modeling
---


# Question
Title: How can I reduce the data sent to the GPU for a voxel?
I'm making a minecraft style game where each chunk each chunk has buffers holding the position of all visible blocks and texture atlas coordinates of the 36 vertices that are needed to draw the triangles.

I have 8 vertices and an EBO that I use for the triangles so it takes up sizeof(GLfloat)\*3\*8 + sizeof(GLuint)\*36 + sizeof(Glfloat)\*2\*36 so 528 bytes. that seems like a lot per block meaning that if I am rendering around 16\*16 chunks(I use an stl::map not an array) 16\*16\*256 chunks that have around 300 visible blocks that means I am sending about 40 mb of data to the GPU each frame.

It runs smoothly now but could this end up being a problem? or is there a way to reduce this?

one other thing, I tried to change my program from using gldraw arrays and having 720 bytes for each block to using an EBO for just the position. how can you control what vbo the ebo operates on?

for example the EBO would have indices to the points of the cube and texture coordinates but still have an instance array for the position

# Answer
> 3 votes
Since data is only sent to the GPU when you *change it* on the CPU, you can identify which data does not change every frame and split that out. Positions, for example, are likely fixed at creation time and never really need to change again, so your position data can go into one vertex attribute stream and your texture coordinates (which do change, potentially) into a separate stream.

Then you only update the second stream every frame. Any other varying data goes into that second stream, and any other fixed data goes into the first.

If you have access to them, geometry shaders are another option you can use (possibly in addition to the two streams). Instead of all eight cube positions, you can just store a single position and expand that into the necessary eight (or whatever) vertices in a geometry shader. Likewise for texture coordinates, in fact; you could just store a "texture index" and do some math to adjust the texture coordinates for your generated vertices.

---
Tags: opengl, voxels
---


# Question
Title: Any way to combine instantiated sprite renderers into one texture so I can apply into a plane at runtime?
So I am procedurally generating a tile set in Unity by instantiating different tiles that only have a transform and sprite renderer components. I managed to pack the sprites using unity sprite packer assigning them a packing tag so that I reduce the draw calls drastically.

But Im still having to deal with a great amount of game objects in the scene when the camera zooms out, increasing the batching and giving me problems when I try to apply light to them for example.

So I am trying to find a way to combine all these sprite renderers into a texture.So I can then apply this to a plane and Ill only have to deal with one plane gameObject for the map. But I cant figure out how to do this. I cant really use the combine meshes way as they are sprites only, not meshes. I tried taking a screenshot at run-time but It comes up a bit blurry. Any idea how can accomplish this? Thank you for your help.

# Answer
> 6 votes
Here's one way to handle it:

* Make a texture that records which tile to draw at each cell of the grid, 1 pixel = 1 tile (so if you make a 4096 square texture, you can have over 16 million tiles in your map)
    + Ensure it's stored uncompressed, with point filtering and no mipmaps
* Write a custom shader that reads this texture for each tile, then looks up the appropriate tile from your tileset texture.
* Render your map as a single quad.

For this example I used a free RPG tileset by Kenney and a 16x16 map for simplicity.

Here's the shader I used, built on Unity's standard surface shader so I could apply lighting to it:

```
Shader "Custom/TilemapShader" {
    Properties {
        _MainTex ("Map", 2D) = "white" {}
        _Tileset("Tileset", 2D) = "white" {}
        _Size("Map & Tileset Size", Vector) = (16, 16, 20, 13)
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _MainTex;
        sampler2D _Tileset;

        struct Input {
            float2 uv_MainTex;
        };

        float4 _Size;
        // _Size.xy is the size of the map in tiles.
        // _Size.zw is the size of the tileset in tiles.

        void surf (Input IN, inout SurfaceOutputStandard o) {

            // Scale up the uvs into tile space.
            float2 mapLocation = IN.uv_MainTex * _Size.xy;

            // Get this pixel's position within the tile we're drawing.
            float2 inTileUV = frac(mapLocation);

            // Clamp the texel we read from.
            // ("Point" filtering does this too, but its math is slightly
            // different, which can show up as a shimmer between tiles)
            mapLocation = (mapLocation - inTileUV) / _Size.xy;

            // Slightly inset tiles so they don't bleed at the edges.
            inTileUV = inTileUV * 126.0f / 128.0f + 1.0f / 128.0f;

            // Calculate texture sampling gradients using original UV.
            // Otherwise jumps at tile borders make the hardware apply filtering
            // that lets adjactent tiles bleed in at the edges.
            float4 grad = float4(ddx(IN.uv_MainTex), ddy(IN.uv_MainTex));

            // Read our map texture to determine what tiles go here.
            float4 tileIndex = tex2D(_MainTex, mapLocation);

            // Generate UV offsets into our tileset texture.
            tileIndex = (tileIndex * 255.0f + inTileUV.xyxy )/_Size.zwzw ;

            // Sample two tiles from our tileset: one base tile and one overlay.
            // (Hey, we have room for two indices, might as well use it!)
            fixed4 base = tex2Dgrad(_Tileset, tileIndex.xy, grad.xy, grad.zw);
            fixed4 over = tex2Dgrad(_Tileset, tileIndex.zw, grad.xy, grad.zw);

            // Combine overlaid tile with base using standard alpha blending.
            fixed4 c = lerp(base, over, over.a);

            // Put all this into terms the Unity lighting model understands.
            o.Albedo = c.rgb;
            o.Metallic = 0.0f;
            o.Smoothness = 0.0f;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

Note that a bunch of the fixups I do there are so that texture filtering works correctly in tileset space. If you're using pixel art tiles with nearest filtering and no mipmaps, you can gut a bunch of that math.

Also, those divisions will be more efficient if you replace them with constants for your map & tileset sizes - I've exposed them as variables here to be more flexible during development & iteration.

If you need to scroll the map over a wider area than you can/want to store in a texture all at once, you can try one of two approaches:

* use one quad & index map for each "chunk" of the map, and recycle/reposition chunks of the map as they scroll off-screen. This requires multiple draw calls, but you can clamp the worst case.
* use one quad for everything shown on-screen, and incrementally update the tile index map as the camera moves around. You can use texture wrapping to pan the map across the quad, so you only have to update a row/column at a time instead of regenerating the whole map.

If you go this route, you'll probably want to also write a script that will generate the tile index map from a source file (like something you created in Tiled), or a custom editor script that helps you modify the tile map visually. Picking precise colour values pixel by pixel to populate the index map was by far the slowest part of putting this example together. ;)

---
Tags: unity, sprites, procedural-generation, tilesets
---


# Question
Title: How to maximum height and body to move in projectile motion( on Canvas)
\**Really.anybody Know't this question's Answer? \**

I asked this question before, but I think I worded it badly and thus did not get any response. I am trying to use an projectile motion in my game. It works. But Canvas coordinate system to Left Top corner to calculate. So projectile point is inverted. I don't know how to maximum height and body to move in point. please help me. Thank you!

Here is my code:

```
public class strak extends View {

public float x;
public float y;
private Controller controller;
private ProjectileEquation projectileEquation;
public int trajectoryPointCount = 20;
public float timeSeparation = 1/3f;

float x1, x2, y1, y2;
private Bitmap bmp;

public static class ProjectileEquation {

    public float gravity;
    public Vector2 startVelocity = new Vector2();
    public Vector2 startPoint = new Vector2();

    public float getX(float t) {
        return startPoint.x + t * startVelocity.x;
    }

    public float getY(float t) {

        return 0.5f * gravity * t * t + startVelocity.y * t + startPoint.y;
    }
}

public static class Controller {
    public float power = 10f;
    public float angle = 0f;
}

public strak(Context context) {
    super(context);
    this.controller = new Controller();
    this.projectileEquation = new ProjectileEquation();
    this.projectileEquation.gravity = 10f;
    Log.i("BitmapFactory", "Create!");
    bmp = BitmapFactory.decodeResource(getResources(),R.drawable.boll);
    yyyyyy();
}

private void yyyyyy() {
    projectileEquation.startVelocity.set( controller.power,0f);
    projectileEquation.startVelocity.rotate(controller.angle);
}

@Override
public boolean onTouchEvent(MotionEvent ev) {

        x2 = ev.getX();
        y2 = ev.getY();

        invalidate();

     long startTime = System.nanoTime();
        float deltaTime = (System.nanoTime() - startTime) / 1000.000f;
        startTime = System.nanoTime();

        if((y1 < y2 )&& (x1 < x2)){

            controller.angle-= .2* deltaTime;
            controller.power-= .2* deltaTime;
            Log.i("LOG_TAG,", "Right to Down Cros");
        }
        if((y1 > y2 )&& (x1 > x2)){
            controller.angle+= .2* deltaTime;
            controller.power+= .2* deltaTime;
            Log.i("LOG_TAG,", "Down to Right Cros");
        }
        if((y1 > y2 )&& (x1 < x2)){
            controller.angle+= .2* deltaTime;
            controller.power+= .2* deltaTime;
            Log.i("LOG_TAG,", "Down to Left Cros");
        }
        if((y1 < y2 )&& (x1 > x2)){
            controller.angle-= .2* deltaTime;
            controller.power-= .2* deltaTime;
            Log.i("LOG_TAG,", "Left to  Down Cros");
        }
                switch (ev.getAction()) {

    case MotionEvent.ACTION_DOWN:

    case MotionEvent.ACTION_MOVE:
        Log.i("LOG_TAG,", "ACTION_MOVE:");
        x1 = ev.getX();
        y1 = ev.getY();
                }
    return true;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    yyyyyy();
    float t = 0f;
    x = getWidth() / 2;
    y = getHeight()/2;
    float timeSeparation = this.timeSeparation;

    for (int i = 0; i < trajectoryPointCount; i++) {
        float x = this.x + projectileEquation.getX(t);
        float y = this.y + projectileEquation.getY(t);

        canvas.drawBitmap(bmp, x, y, null);
        t += timeSeparation;
    }
}
}

```

# Answer
> -2 votes
You could try to do a symmetry with respect to x axis, like this:

```
float y = -(this.y + projectileEquation.getY(t));

```

---
Tags: java, android
---


title: Why does the increment only run once?

text:
# Question
Title: Why does the increment only run once?
I've made an `Event Trigger` when I have written a script that makes something disappear when it's hit. In addition to that I've an increment in that method that should increment each time something is hit, but it only increment the first time. Can somebody tell me why this is happening and what I should do in order to solve it?

```
 public void Hit()
{
    Destroy(gameObject);
    Hits++;
    text.text = Hits.ToString();
}

```

So every time something is hit this method runs, but it only increments the first time.

# Answer
Just taking a guess since we'd really need to see where the 'Hits' value is coming from, but I'm guessing that is a field of this gameObject, so when you Destroy this gameObject the value 'Hits' is going away. What you want is for 'Hits' to be shared across multiple objects, like with a static or something.
> 1 votes

# Answer
This event it's called when the gameobject is hit, but the first thing you are doing is destroy the object. `Destroy` lasts a couple miliseconds before detroy the object itselfs, so the whole method is executed, but there will be no object the next hit so neither the method.

I can't help you anymore because I don't know what are you trying to do. If you put your code, where is attached this code (and the gameObject) and what you want to do maybe I can help you more.
> 0 votes

# Answer
When you make this run, there are 2 scenarios,

1: The object gets destroyed, moves on and does ++Hits;.

2: No object is hit and it is stuck destroying a blank tile.

(I\`m a noobie)
> 0 votes

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


# Question
Title: texture cordinate VBO not being updated OpenGL
I'm making a minecraft style game and I decided to add a VBO with the texture atkas coordinates of the vertices but it is appearing all white. However I'm following the same process as another VBO for the block positions which works

the one that works

```
glBindBuffer(GL_ARRAY_BUFFER,chunk->posOffsetVBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(glm::vec3)*65536,NULL,GL_DYNAMIC_DRAW);

glVertexAttribPointer(2,3,GL_FLOAT,GL_FALSE,3*sizeof(GLfloat),(GLvoid*)0);
glEnableVertexAttribArray(2);
glVertexAttribDivisor(2,1);

```

then I fill it with glm::vec3s like this

```
glBindBuffer(GL_ARRAY_BUFFER,adjacentChunks[1][1]->posOffsetVBO);

glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(posOffsets),&posOffsets[0]);

```

this is the one with the texture coordinates that doesn't work

```
glBindBuffer(GL_ARRAY_BUFFER,chunk->texCoordVBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(glm::vec2)*36*1000,NULL,GL_DYNAMIC_DRAW);

glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,2*sizeof(GLfloat),(GLvoid*)0);
glEnableVertexAttribArray(1);

```

then fill It with 36 glm::vec2s for each block so one per vertex

```
glBindBuffer(GL_ARRAY_BUFFER,adjacentChunks[1][1]->texCoordVBO);

glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(texCoords),&texCoords[0]);

```

Is there a reason why the texture one doesn't work?

# Answer
> 0 votes
I feel stupid, after hours of trying to solve this problem I looked in the vertex shader for the umpteenth time and noticed that I was setting the output texture coordinate to itself. Now it works.

---
Tags: opengl, textures, vbo
---


# Question
Title: SDL Player do something for 3 seconds then stop
I'll make my player respawn after 1 of his lives is taken, but I want him to be invincible for 2 or 3 seconds and not instadie again because he will be in the way of enemy bullets.

```
for (int i = 0; i < MAX_BULLETS; i++) if (enemyB[i]) {
    if(globalTime % 2 == 0)
        enemyB[i]->y -= enemyB[i]->dx;
    if (player->alive && (enemyB[i]->x > player->x && enemyB[i]->x < player->x + 97 && enemyB[i]->y == player->y-15))
    {
        if (player->invincible == false) {
            player->life -= 25;
            player->hbSprite++;
        }
        if (player->life <= 0) {
            player->invincible = true;
            player->lives--;
            player->life = 100;
            player->lifeSprite++;
            player->hbSprite = 0;
            if (player->lives <= 0) {
                player->alive = 0;
                player->hbSprite = 4;
                player->lifeSprite = 3;
            }
        }
        removenemyB(i);
    }
}

```

When I set player-\>invicible = true he's not taking dmg , but I need him to do that only for 2 or 3 seconds , help pls.

# Answer
> 2 votes
Given that you are working with SDL2, `SDL_GetTicks()` is the most straightforward solution. `SDL_AddTimer` is also an option, but you would have to deal with a bit of multi-threading, unnecessary repeated executions, and callback functions.

I see that you have a `globalTime` variable, which I am inclined to incorporate as part of my answer, but I don't have enough context with the code you've provided to be sure how that variable is updated.

That being said, replace setting invincibility with *the game time that the player will no longer be invincible*:

```
// ...
if (player->life <= 0) {
    player->endInvincibleTime = SDL_GetTicks() + 3000; // 3 seconds
// ...

// endInvincibleTime is Uint32 type

```

This amounts to setting a marker at some fixed point in the future. Game time will eventually pass it, permanently.

Then, instead of checking for invincibility, just check if game time has passed `endInvincibleTime`:

```
// ...
if (player->endInvincibleTime < SDL_GetTicks()) {
    player->life -= 25;
    player->hbSprite++;
}
// ...

```

`SDL_GetTicks` returns an unsigned 32 bit integer, meaning that from the moment `SDL_Init` is called its timer starts counting milliseconds and it is able to count up to 49 *days* worth of milliseconds.

---

Note that I am suggesting here that you use `SDL_GetTicks` as your game duration/timing system directly, but that is only for the sake of example. There are other ways of tracking time. For example using different timing libraries , or in STL. They more-or-less amount to better precision and/or more reliable response time. Here's some more reading on C timers *Always be wary of integer overflow/wrap-around.* Especially when using unsigned integers.

---
Tags: sdl, c, sdl2
---


# Question
Title: Best way to interpolate player movements in a very fast paced Unity game?
In my Unity online multiplayer game players move very fast and I currently use `Lerp` to interpolate between their last position and current position:

```
transform.position = Vector3.Lerp(transform.position, this.correctPlayerPos, Time.deltaTime * smoothingFactor);

```

`smoothingFactor` is currently around 35f but I don't like the result. If I lower `smoothingFactor`, movements will be smoother but players will lag as well. If I increase it to like 40, it will be more precise but laggy.

How can I solve this?

# Answer
There are two common patterns for use of Lerp. The one you're using is:

```
current = Lerp(current, target, sharpness)
(where sharpness is a constant between 0 and 1)

```

Note that there's a feedback loop here. The value of `current` is both an input and an output, so the value of `current` we use as input in the next frame is the output from the last frame.

This is good for when you want an easing effect: when the `target` is updated to something far from `current`, you get a fast initial movement, which slows down as the `current` value approaches the `target`. This looks nice in UI transitions and simple camera follow scripts.

In the context of interpolation for multiplayer though, it's probably not an ideal choice. Imagine another player running at a constant velocity across my screen. Their speed will spike each time I get a new update from the server (when `target` jumps ahead) and then slow to a crawl as they get close to the last update position. Even if I'm getting frequent updates, the constant increases & decreases in speed make it look jerky and low-performance.

Instead you probably want the other common Lerp pattern:

```
current = Lerp(previous, next, progress)
(where progress varies linearly from 0 to 1 over the expected duration of the move)

```

Here you store the position of the player in the most recent update from the server (`next`), and the position they were in when it was received (`previous`), and interpolate between them over one server update interval.

Note that neither of the inputs `previous` or `next` are modified by the Lerp, which prevents any feedback loop changing the behaviour of the formula over time.

Instead, the character moves with a constant velocity throughout the Lerp. In fact, if you let `progress` go past 1 in the event of a late or missing update packet from the server, then this also seamlessly handles a simple linear prediction, so the character won't stop and hesitate waiting for new server input (but at a risk of slight overshoot). This will generally look much smoother for this type of use.
> 13 votes

# Answer
Thank you. This has been a very good explanation, regarding the *progress*, and the **different** ways of interpolation.

As I understood the issue: Having a **constant interpolation factor** between 0 and 1; Where lower values produce smoother but much delayed results, and higher values produce more accurate but choppy results.

What the *progress* calculation below does is treat interpolation as a variable, that increases and decreases when it needs to, handled by how far one is away from the **Previous Position Received** to the **Next Position Received**

This is the way I handled it. - Since my issue was, in a 'constant' interpolation factor where movement was smooth, the jump for example was extremely delayed, making the player seem like he's strafe-jumping in mid-air. This is where the 'progress' method comes in handy. Upon approaching the 'Next Position' say when the player lands, previously he was too 'laggy' to land accurately on the ground but rather drop half way from the jump before jumping again. So as the player drops down closer to the 'next position', the progress calculation gets closer to 100%, resulting in the interpolation toward the end of the jump get accelerated, smoothing the movement.

See below, I'm using Photon Unity Networking:

```
void Update () {
    clientPredictionValue = nManager.clientPredVal;
    velocityPredictionValue = nManager.velocityPredVal;

    if (photonView.isMine) {
    }
    else {

        //Progress Calculation for Interpolation value
        if (prevPosition == Vector3.zero) {
            prevPosition = realPosition;
        }
        currentDistance = Vector3.Distance (tr.position, realPosition);
        fullDistance = Vector3.Distance (prevPosition, realPosition);
        if (fullDistance != 0) {
            progress = currentDistance / fullDistance;
        }
        prevPosition = realPosition;

        if (clientPredictionValue != 0) {
            progress *= clientPredictionValue;
        }

        syncTime += Time.deltaTime;
        tr.rotation = Quaternion.Lerp(tr.rotation, realRotation, syncTime/syncDelay);
        tr.position = Vector3.Lerp (tr.position, realPosition, progress);
    }
}

public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info){

    if (stream.isWriting) {
        //This is OUR player. We need to send our actual position to the network.

        stream.SendNext (tr.position);
        stream.SendNext (tr.rotation);
        stream.SendNext (pMovement.playerVelocity);
        stream.SendNext (anim.GetFloat ("AimAngle"));
        stream.SendNext (anim.GetFloat ("HorizontalMovement"));
        stream.SendNext (anim.GetFloat ("VerticalMovement"));
        stream.SendNext (anim.GetBool ("Jump"));
    }
    else{
        //This is someone else's player. We need to receive their position (as of a few
        //milliseconds ago, and update our version of THAT player.

        // Right now, "RealPosition" holds the other's position at the LAST frame.
        // Instead of simply updating "realPosition" and continuing to lerp,
        // we MAY want to set our transform.position immediately to this old "realPosition"
        // and then update realPosition

        realPosition = (Vector3)stream.ReceiveNext ();
        realRotation = (Quaternion)stream.ReceiveNext ();
        playerVelocity = (Vector3)stream.ReceiveNext ();
        anim.SetFloat ("AimAngle", (float)stream.ReceiveNext ());
        anim.SetFloat ("HorizontalMovement", (float)stream.ReceiveNext ());
        anim.SetFloat ("VerticalMovement", (float)stream.ReceiveNext ());
        anim.SetBool ("Jump", (bool)stream.ReceiveNext ());

        syncTime = 0f;
        syncDelay = Time.time - lastSynchronizationTime;
        lastSynchronizationTime = Time.time;

        //Velocity Prediction
        realPosition = realPosition + playerVelocity * velocityPredictionValue * syncDelay;
    }
}

```
> 0 votes

---
Tags: unity, movement, multiplayer
---


title: Collision Detection works 2 sides

text:
# Question
Title: Collision Detection works 2 sides
This might be really simple but it is giving me a lot grief and I wondered if you guys would be able to shed some light on it. Basically I have a tile map which draws tiles at 64 * 64 and that works very well and they are drawn in a 2D array like this in the game1 class.

```
TileMap tileMap = new TileMap(new int[,]
    {
        { 2,2,2,2,2,2,2,2,2,2 },
        { 2,2,2,2,2,2,2,2,2,2 },
        { 0,0,0,0,0,0,4,4,4,4 },
        { 0,0,0,0,0,0,1,1,4,4 },
        { 1,1,1,1,1,1,1,1,1,1,},
        { 1,1,1,1,1,1,1,1,1,1,}
    });

```

Now comes the problem. Basically I want to determine which side the player has hit the tile from. However, with the algorithm below the collision only works correctly for the bottom and left side. if the player hits the tile from the top it will state it was hit from the bottom. if the player hits from the right it will specify the left side was hit. if the player hits from the left or bottom it will show that collision has happened but state it happened on the right or top of it. it will output that the top of the has been hit but only when the player is completely in the tile like this

.

Pretty much the same thing happens when it displays the right side is hit (player moves more to the left)

**TileMap**

```
int left = (int)Math.Floor((float)player.playerBounds.Left / TILE_WIDTH);
        int top = (int)Math.Floor((float)player.playerBounds.Top / TILE_HEIGHT);
        int right = (int)Math.Ceiling((float)player.playerBounds.Right / TILE_WIDTH) - 1;
        int bottom = (int)Math.Ceiling((float)player.playerBounds.Bottom / TILE_HEIGHT) - 1;

        Rectangle tileBounds = new Rectangle((int)tilePosX, (int)tilePosY, TILE_WIDTH, TILE_HEIGHT);
        Rectangle playerBounds = player.playerBounds;

        float WidthOfRects = 0.5f * playerBounds.Width + tileBounds.Width;
        float heightOfRects = 0.5f * playerBounds.Height + tileBounds.Height;

        int centerX = (playerBounds.Left + playerBounds.Width / 2) - (tileBounds.Left + tileBounds.Width / 2);
        int centerY = (playerBounds.Top + playerBounds.Height / 2) - (tileBounds.Top + tileBounds.Height / 2);

        for (int y = top; y <= bottom; ++y)
        {
            for (int x = left; x <= right; ++x)
            {

                if (mapCell[y, x].TileID == 1)
                {
                    //minkowski sum
                    if (Math.Abs(centerX) <= WidthOfRects && Math.Abs(centerY) <= heightOfRects)
                    {
                        double wy = WidthOfRects * centerY;
                        double hx = heightOfRects * centerX;
                        if (wy > hx)
                        {
                            if (wy > -hx)
                            {
                                Console.WriteLine("bottom");
                                //newPos.Y = tileCollision.Bottom;
                            }
                            else
                            {
                                Console.WriteLine("right");
                                //newPos.X = tileCollision.Right;

                            }
                        }
                        if (wy > -hx)
                        {
                            Console.WriteLine("left ");
                            //newPos.X = tileCollision.Left - playerBounds.Width;
                        }
                        else
                        {
                            Console.WriteLine("top");
                            //newPos.Y = tileCollision.Top - playerBounds.Height;
                        }
                    }
                    // player.Position = newPos;
                }
            }
        }

```

**Map Cell**

```
public class MapCell
{

    public int TileID { get; set; }

    public MapCell(int tileID)
    {
        TileID = tileID;
    }

```

Any help would be greatly appreciated.

Thank you.

# Answer
**Solution #1:** Try to check for collisions before they happen:
**if** player's position + his horizontal velocity collides with the tile
**and**
the velocity is negative (i.e he's moving up),
**then** the collision will happen from above.

The same logic can be applied to the other sides.

**Solution #2:** You can create additional collision boxes on every side of the "main" box,
so-called 'sensors', and check for collisions with them:

The red box is the main one and the yellow boxes are those additional sensors. My drawing is far from ideal, but hopefully you got the idea.
> 1 votes

# Answer
Check out my answer: Platformer collision problems (C++)

Maybe it doesn't seem so simple to implement with your codes but that collision system would be the best choice for you (I think).
> -1 votes

# Answer
Get this:

```
float WidthOfRects = 0.5f * (playerBounds.Width + tileBounds.Width);
float heightOfRects = 0.5f * (playerBounds.Height + tileBounds.Height);

```
> -3 votes

---
Tags: c#, xna, collision-detection, mathematics, geometry
---


# Question
Title: Why is RK4 better than Euler integration?
At the end of these great slides, the author compares all the different integrators presented. One way or another, they all fall short except for *Improved Euler Integration* and *Runge Kutta 4 Integration*, which both pass all tests.

I suppose I should mention that I am working on a 2D game that *isn't* very physics intensive. I'm just curious as to where Improved Euler Integration would fall short and RK4 would have to be used instead.

My game consists mostly of simple gravity (jumping and falling), movement along the X and Y axes, and bounding box collision. Is it worthwhile to implement RK4 or would Improved Euler be sufficient? I see many discussions where Euler Integration's users are chastised, but from what I can see, Improved Euler is quivalent in simple 2D matters. I imagine it'd also be faster.

# Answer
> 15 votes
I personally prefer Velocity Verlet for most simulations. In my experience with this method, it is quite suitable for pretty stiff equations. It seems like this "improved Euler" method is pretty similar to the Velocity Verlet one and relies on a class of integration methods known as predictor-corrector. You can read a lot of things on these methods nowadays, starting with David Baraff's "Large steps in cloth simulation" where the power of implicit methods really shines. Their downfall is that you:

1. have to approximate Jacobians or Hessians and then have to,
2. compute a fair amount of matrix inverses per frame.

So if you're not a math guru, you could get your fingers stuck. Just experiment with whichever method you want and then settle for the one that seems to perform best for you. Simple is not always better, but for interactive framerates I only know one word: compromise.

Some additional resources you might want to look at:

Jakobsen is a sort of genius for coming up with such a simple idea for pretentious problem (his specialty is Cryptography if not mistaking, but he succeeded in proving the mathematical equivalence of his method to a class of Gauss-Seidel iterative algorithm, which is convergent). For simplicity, go for this first before delving deep into implicit methods.

**LATER EDIT**: I recently got a paper on this issue of using explicit integrators for soft or semi-rigid body simulation and what their performance and quality impact is. This paper should serve as a guide for choosing a certain integrator, depending on the scenario.

# Answer
> 10 votes
Q: Why use the advanced Runge Kutta?
A: Because it's very exact.

Q: Why not?
A: Because you are making a game and a very exact physics engine doesn't matter, it just has to be good enough to fool the player.

By the way, if you have got heavy dampening on collision, like most platformers would, a simple Euler is just fine.

I strongly recommend that you unlike the code in the presentation use fixed step physics, which saves you some potential glitches, and lets you solve the problem of the ball gaining or losing energy in a very simple fashion. Just go for the middle ground between explicit and implicit integration:

```
velocity += 0.5 * acceleration;
position += velocity;
velocity += 0.5 * acceleration;

```

What the presentation doesn't show is how to handle collisions so that objects don't appear to go beyond the boundaries. The simple solution to that problem is to use a high update frequency. A more complex but potentially better performing solution is to move objects back at the time of collision, exact implementation depends on desired physics behaviour.

# Answer
> 1 votes
The presentation has error. The method referred to by presenter as "Improved Euler" is actually Velocity Verlet method!

See here for more authoritative source: http://www.physics.udel.edu/~bnikolic/teaching/phys660/numerical\_ode/node5.html

Also same equations are in Wikipedia.

A common immediate improvement over Euler's method is Midpoint method which what presenter probably had in mind but ended up mistaking Velocity Verlet as improved Euler. The only different between Midpoint method and Velocity Verlet is that velocity is average of last and next acceleration instead of just dependent on last acceleration.

---
Tags: physics, rk4, integration
---


# Question
Title: How to create a new GameObject, without adding it to the scene?
I'm creating what is essentially my own prefab system. Game objects are defined by a human readable data file. I'd like to create an empty GameObject, load it with the components defined in the data file and have it ready and waiting for an `Instantiate()` call. However, whenever I use `GameObject go = new GameObject()` a new game object is added to the scene.

Using Unity built in prefabs, I can load a prefab as a GameObject, and it's not added to the scene. (See example below)

The rationale behind this is I'd like to have one list that contains GameObjects, some generated by loading Unity prefabs and others created by my custom prefab system. This needs to happen at run time, and can't involve the Unity Editor (since ideally end users would be able to define their own data files).

How can I create a new GameObject, without Unity automatically instantiating it for me?

---

For example, I can make a call like this:

```
Resources.LoadAll("PrefabsDirectory", typeof(GameObject))

```

And I'll get a list of GameObjects, none of which are added to the scene when the call is made. Essentially, I'm creating a `LoadAll` method for my own prefabs, and likewise, I don't want to instantiate the GameObjects when the call is made.

# Answer
You could change the GameObject's hideFlags?

I just tried running this:

```
GameObject myGameObject = new GameObject ();
myGameObject.name = "Obvious Name";

myGameObject.hideFlags = HideFlags.HideInHierarchy;

```

...and it's there, but it's not in the hierarchy. Technically, it's in the scene, but you don't see it until you change it's flags back to HideFlags.None. It's not the answer you're looking for, but at least as far as releasing this to developers goes, it's cleaner than grouping your objects.
> 7 votes

# Answer
There is no way to do `go = new GameObject();` without adding it to the scene.

I'm working on an RTS where the player base needs to be persistent, and essentially, we serialize everything they've done and load it back in at run time using modified assets from the store.

Most output to XML or JSON so it's pretty straight forward to load the file and manipulate it as you wish.
> 0 votes

# Answer
You can't do that exact thing, unfortunately. However, you can accomplish the same design pattern (ie. abstract away the building of your objects, and then simply call them with a single command later) through a Factory pattern.

When you want an object, call something like `Factory.CreateGameEntity()`, and that method will handle everything behind the scenes.
> 0 votes

# Answer
The right way is to make a prefab , you allocate that prefab as an Object , then whenever you want to instantiate just use the reference of this Object and cast it as a GameObject.

ex :

```
private Object prefab;

public static GameObject Create(void)
{
   return (Instantiate(prefab , position , rotation) as GameObject);
}

```
> -1 votes

# Answer
To load a prefab into a variable so you can instantiate it later you would use the following code:

```
 GameObject ball = (GameObject)(Resources.Load ("myPrefab"));

```

I've done this in a project with Unity 5.5. It will be available to instantiate but not in the scene or part of the hierarchy until instantiated as normal.
> -1 votes

---
Tags: unity, resource-management
---


title: 2D HUD over 3D scene

text:
# Question
Title: 2D HUD over 3D scene
I'm trying to create a 2D Heads up Display for my players in a 3D OpenTK environment. How I'm doing it is by drawing my 3D elements and then running this code.

```
GL.MatrixMode(MatrixMode.Projection);
GL.Ortho(-0.5, 0.5, -0.5, 0.5, 1, 100);
GL.LoadIdentity();
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
//Disable all depth stuff
GL.DepthMask(false);
GL.Disable(EnableCap.DepthTest);
GL.Disable(EnableCap.CullFace);
//Pass texture to shaders
GL.ActiveTexture(TextureUnit.Texture0);
GL.BindTexture(TextureTarget.Texture2D, TextureImg.Handle);
GL.Uniform1(GL.GetUniformLocation(Game.pgmID, "texUnit"), 0.0);
GL.Uniform1(GL.GetUniformLocation(Game.pgmID, "texture"), 1.0);
//Enable vertex attributes
GL.EnableVertexAttribArray(Game.attribute_vpos);
GL.EnableVertexAttribArray(GL.GetAttribLocation(Game.pgmID, "texcoord"));
GL.EnableClientState(ArrayCap.VertexArray);
GL.EnableClientState(ArrayCap.TextureCoordArray);
//MVP matrix is only translation of HUD position
Matrix4 c = Matrix4.CreateTranslation(new Vector3(Position.X, Position.Y, 0)) * Matrix4.CreateScale(0.1f);
GL.UniformMatrix4(Game.uniform_mview, false, ref c);
//Send vertices and uvs to shader
GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(verts.Length * Vector2.SizeInBytes), verts, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(Game.attribute_vpos, 2, VertexAttribPointerType.Float, false, 0, 0);

Vector2[] uvs = new Vector2[]
{
    new Vector2(0,0),
    new Vector2(1,0),
    new Vector2(1,1),
    new Vector2(0,1)
};

GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(uvs.Length * Vector2.SizeInBytes), uvs, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(GL.GetAttribLocation(Game.pgmID, "texcoord"), 2, VertexAttribPointerType.Float, false, 0, 0);
//Draw
GL.DrawArrays(PrimitiveType.Quads, 0, 4);
GL.UseProgram(Game.pgmID);
//Make sure I can render 3D again
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
GL.DepthMask(true);
GL.Enable(EnableCap.DepthTest);

```

It works exactly how it's supposed to, except the quad that I draw to the screen is slightly stretched out. It's annoying the absolute heck out of me, and I have no idea what I'm doing wrong.

**Edit: Picture**

# Answer
GL.Ortho creates a screen that is as wide and tall as you specified it. In your case both the width and height is 1 unit.

Because your screen is wider than taller, a width unit is bigger than a height unit, and thus the square becomes stretched.

You need to get the screen's sizes, calculate it's aspect ratio (width / height), then you need to set the left clipping plane to `-aspectRatio / 2` and the right to simply `aspectRatio / 2`. You also need to load the ortographic matrix after the identity matrix.

You should store `aspectRatio` somewhere in case you wnt to put something at the edge of the screen, because that's not 1 anymore.
> 2 votes

# Answer
After a lot of searching about, the answer was amazingly stupid. All I needed to do was send the translation of my HUD element multiplied by an orthographic matrix to the shader. The code looks like this for other people with my problem.

`Matrix4 c = Matrix4.CreateTranslation(new Vector3(Position.X, Position.Y, 0)) * Matrix4.CreateScale(100) * ortho * Matrix4.Identity;
GL.UniformMatrix4(Game.uniform_mview, false, ref c);`
> 0 votes

---
Tags: 2d, 3d, opentk, hud
---


# Question
Title: How to synchronize a parent and child position?
When watching this video of Unity development, I was following along trying to learn Unity and for the most part understood everything conceptually.

Where I got lost was when I tried using some of the same code and setup in Unity. I got the code working fine, but I got in trouble when I tried to implement the parent-child behavior seen in the video at around 7 minutes regarding the **Enemy** objects.

The solution described is set up as follows (someone correct me if I didn't understand it properly from the video).

**Parent Object**

* Contains the script which drives behavior and movement
* Is located at the origin of the scene (reset the transform in other words)

**Child Object**

* Contains the graphics renderer which draws the actual sprite or 3D object
* Is located at the enemy spawn point

For me to get this setup working, I had to run the Translate function explicitly against the child object:

```
transform.GetChild(0).Translate(dir.normalized * distThisTurn)

```

However, in the video, it appears to work just fine with only:

```
transform.Translate(dir.normalized * distThisTurn)

```

Once he fixes the rotation issue, at about 7 minutes in, this works beautifully, and the enemy travels the path exactly as expected. When I tried this exact same approach, my enemy sprite jumps all over the place. It took me several hours to figure out that I needed to add the `.GetChild(0)` part. The behavior I saw with the setup from the video is that the invisible parent object moved correctly along the path, and the child went crazy and followed some alternate version of the same path, as if the origin was different or offset, or the path was reflected across some axis.

My question is: **what did I do wrong?** Can anyone spot how my setup is different than the one used in the video? Did I miss some detail of how he set up his parent-child objects, particularly for the enemies? Or could this be some different behavior due to the version of Unity he is using (I believe mine is newer as I installed it just this week). I think it could also be some small gizmo or feature he neglects to mention that allows you to synchronize the movement of a parent object with its children.

The reason for this setup (at least as given in the video) is it allows you to easily swap out the graphics. The scripting is tied to the parent, so all you have to do is exchange the child for one with different graphics and you're done. That part makes sense, I just don't understand why the exact same code he uses did not work for me. I'm talking only about the Enemy object here - the creeps that move along the path (it's a tower defense game).

I just want to know because I may have to use this extra GetChild call quite a bit, and I feel like it shouldn't be necessary, especially after seeing it work so well in the video. Doing this would also make my scene design a little easier.

I have already read the comments on that video for additional info, as well as looked through Unity forum posts, other posts here on Game Dev.SE, and Google results. It would seem as if this is either old behavior, or there is some small detail neglected to explain in the video of how to synchronize movement of parent and child objects.

# Answer
I figured out what I did wrong. The key I was missing is this: **the child object treats the parent's location as the origin**. If I'd understood that, I would have had no trouble setting it up right the first time.

You could think of the parent as the butt of a pool cue, and the child as the tip. When you move the tail end of the stick, the other end moves with it. When you move the tip, you are adjusting the length of the stick (by altering the position values in the child's transform component).

The fix was to place the parent object where the spawn point should be, and then reset the child transform to place it at the same location as the parent. In the pool cue analogy, this is like placing the pool cue vertically so that when you look directly down at the table from the top, the tip and the butt appear to be in the same position.

Thanks to DMGregory for pointing me in the right direction (no pun intended).
> 4 votes

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


# Question
Title: Stopping player from spamming movement keys which causes glitches Unity C#
I wrote a script for the player movement in c#. Whenever the player presses A or D, it moves him/her to the left or right by 12 units and when the player presses W or S, it moves him/her up or down by 12 units. My script works fine, but if a person starts to spam all of the keys at once, it glitches out and the player object is not in line with the level anymore. I want to have the script check if there a movement is currently happening before executing the movement on the keypress. Here is my script:

```
void Update () {

    transform.Translate(Vector3.forward * ForwardSpeed * Time.deltaTime);

    if (Input.GetKeyDown (KeyCode.A) && side > maxSideLeft) {
        MoveObjectTo(this.transform, new Vector3(this.transform.position.x - 12, this.transform.position.y, this.transform.position.z + 10), movementSpeed);
        side -= 1;
    } else if (Input.GetKeyDown (KeyCode.D) && side < maxSideRight) {
        MoveObjectTo(this.transform, new Vector3(this.transform.position.x + 12, this.transform.position.y, this.transform.position.z + 10), movementSpeed);
        side += 1;
    }

    if (Input.GetKeyDown (KeyCode.W) && level < maxLevelHeight) {
        MoveObjectTo(this.transform, new Vector3(this.transform.position.x, this.transform.position.y + 12, this.transform.position.z + 10), movementSpeed);
        level += 1;
    } else if (Input.GetKeyDown (KeyCode.S) && level > minLevelHeight) {
        MoveObjectTo(this.transform, new Vector3(this.transform.position.x, this.transform.position.y - 12, this.transform.position.z + 10), movementSpeed);
        level -= 1;
    }

    if (Input.GetKeyDown (KeyCode.R) || Input.GetKeyDown(KeyCode.Space)) {
        SceneManager.LoadScene ("Scene1");
        Time.timeScale = 1;
    }
}

private void MoveObjectTo(Transform objectToMove, Vector3 targetPosition, float moveSpeed)
{
    StopCoroutine(MoveObject(objectToMove, targetPosition, moveSpeed));
    StartCoroutine(MoveObject(objectToMove, targetPosition, moveSpeed));
}

public static IEnumerator MoveObject(Transform objectToMove, Vector3 targetPosition, float moveSpeed)
{
    float currentProgress = 0;
    Vector3 cashedObjectPosition = objectToMove.transform.position;

    while (currentProgress <= 1)
    {
        currentProgress += moveSpeed * Time.deltaTime;

        objectToMove.position = Vector3.Lerp(cashedObjectPosition, targetPosition, currentProgress);

        yield return null;
    }
}

```

# Answer
The first thing I'd have a look at with your code is implementing the command pattern on your inputs. This will abstract the actual movement keys pressed from the act of moving itself. Allows for easy rebinds and using your key response methods for more than just the player character. Always try to avoid "magic numbers/keys" since they tend to scale poorly.

The next thing I'd recommend is handling input **before** you move the character. If the player enters valid input then apply the transform only if the current velocity of the player character is 0.

This will end up making your Update method look like this:

```
void Update()
{
  PlayerInputHandler.HandleInput();
  transform.Translate(Vector3.forward * ForwardSpeed * Time.deltaTime);
}

private InputHandler PlayerInputHandler;

```

Notice all the code is on one layer of abstraction, and the update method isn't actually worried about the details of how Inputs are handled. Much easier to follow!

This is a rough sketch up of what an InputHandler might look like, though keep in mind I'm not a regular to C# or Unity so a few errors might creep in:

```
public class InputHandler : MonoBehaviour
{
  public void OnAwake()
  {
    // Set default keys for inputs
    UpCommand = new InputCommandUp(KeyCode.W.ToString());
    DownCommand = new InputCommandDown(KeyCode.S.ToString());
    RightCommand = new InputCommandRight(KeyCode.D.ToString());
    LeftCommand = new InputCommandLeft(KeyCode.D.ToString());
  }

  public void HandleInput()
  {
    CheckInput(UpCommand);
    CheckInput(DownCommand);
    CheckInput(RightCommand);
    CheckInput(LeftCommand);
  }

  private void CheckInput(InputCommand CurrentInputCommand)
  {
    // Only handle new input if player character has come to a complete stop
    if (Event.current.Equals(Event.KeyboardEvent(CurrentInputCommand.GetKeyAsString()))
        && CurrentCharacter.ForwardSpeed == 0)
    {
      CurrentInputCommand.Execute(CurrentCharacter);
    }
  }

  private InputCommand UpCommand;
  private InputCommand DownCommand;
  private InputCommand RightCommand;
  private InputCommand LeftCommand;

  private PlayerCharacter CurrentCharacter
}

```

There'd obviously be a few getters and setters up there for testing and flexibility but they seemed a distraction so I ignored them for this.

The interface itself only needs two methods, one to do the thing when the key is pressed to the player, and one to provide easy access to a string representation of the key.

```
interface InputCommand
{
  public void Execute(PlayerCharacter CharacterToManipulate);
  public string GetKeyAsString();
}

```

Then an Implementation of the InputCommand might look something like this

```
public class InputCommandUp : InputCommand
{
  public void InputCommandUp(string InInputKey)
  {
    InputKey = InInputKey;
  }

  public void Execute(PlayerCharacter CharacterToManipulate)
  {
    if (CharacterToManipulate.ExceedsMaxLevelHeight())
    {
      CharacterToManipulate.MoveObjectTo(CharacterToManipulate.transform,
        new Vector3(CharacterToManipulate.transform.position.x,
                    CharacterToManipulate.transform.position.y + 12,
                    CharacterToManipulate.transform.position.z + 10),
        CharacterToManipulate.movementSpeed);

      CharacterToManipulate.level += 1;
    }

    }
  }

  public string GetKeyAsString()
  {
    return InputKey;
  }

  private string InputKey;
}

```

Hopefully that'll be of some help to you! (Also I recommend reading the other programming patterns in that book as well, they can be pretty handy in a pinch).

Any questions/complete misunderstandings of the problem give me a shout.
> 1 votes

# Answer
What about using a timespan? I'm not sure if u can access it in unity but maybe.

```
Private previousFireTime As TimeSpan
Private fireTime As TimeSpan = TimeSpan.FromSeconds(0.18F)

If GameTime.TotalGameTime - previousFireTime > fireTime Then
DoStuff() //do your stuff
previousFireTime = GameTime.TotalGameTime
End If

```

GameTime.TotalGameTime is just the total running time of your game.
> 0 votes

# Answer
I wrote this script with simple booleans in the right place to do what I wanted it to do:

```
public bool isMoving = false;

void Update () {

    zPosition = (int)this.transform.position.z;
    if (zPosition >= 0) {
        ScoreText.GetComponent<Text>().text = "Score: " + zPosition;
    }

    transform.Translate(Vector3.forward * ForwardSpeed * Time.deltaTime);

    if (Input.GetKeyDown (KeyCode.A) && !isDead && transform.position.x != -36) {
        MoveObjectTo(this.transform, new Vector3(this.transform.position.x - 12, this.transform.position.y, this.transform.position.z + 10), movementSpeed);
        //side -= 1;
    } else if (Input.GetKeyDown (KeyCode.D) && !isDead && transform.position.x != 36) {
        MoveObjectTo(this.transform, new Vector3(this.transform.position.x + 12, this.transform.position.y, this.transform.position.z + 10), movementSpeed);
        //side += 1;
    }

    if (Input.GetKeyDown (KeyCode.W) && !isDead && transform.position.y != 12) {
        MoveObjectTo(this.transform, new Vector3(this.transform.position.x, this.transform.position.y + 12, this.transform.position.z + 10), movementSpeed);
        //level += 1;
    } else if (Input.GetKeyDown (KeyCode.S) && !isDead && transform.position.y != 0) {
        MoveObjectTo(this.transform, new Vector3(this.transform.position.x, this.transform.position.y - 12, this.transform.position.z + 10), movementSpeed);
        //level -= 1;
    }

    if (Input.GetKeyDown (KeyCode.R) || Input.GetKeyDown(KeyCode.Space)) {
        SceneManager.LoadScene ("Scene1");
        Time.timeScale = 1;
    }
}

private void MoveObjectTo(Transform objectToMove, Vector3 targetPosition, float moveSpeed)
{
    //Don't do anything Object is already moving
    if (isMoving)
    {
        return;
    }
    //If not moving set isMoving to true
    isMoving = true;
    StartCoroutine(MoveObject(objectToMove, targetPosition, moveSpeed));
    StopCoroutine(MoveObject(objectToMove, targetPosition, moveSpeed));
}

public IEnumerator MoveObject(Transform objectToMove, Vector3 targetPosition, float moveSpeed)
{
    float currentProgress = 0;
    Vector3 cashedObjectPosition = objectToMove.transform.position;

    while (currentProgress <= 1)
    {
        currentProgress += moveSpeed * Time.deltaTime;

        objectToMove.position = Vector3.Lerp(cashedObjectPosition, targetPosition, currentProgress);

        yield return null;
    }
    //Done moving. Set isMoving to false
    isMoving = false;
}

```
> 0 votes

# Answer
In my sinple games I have two integer variables: `forward` and `right`. Every loop these variables are reset to 0. If `W` is pressed 1 is added to forward. If `S` is pressed 1 is subtracted from `forward`. Then in your case I would add `12 times forward` as the vector in `moveObject`. I would do similarly with the right variable. Keep in mind that using this method of movement means going forward and sideways at the same time moves faster than going forward, because you are going forward 12 and sideways 12. (12 squared plus 12 squared = a number more than 12)
> 0 votes

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


# Question
Title: Can I develop on the Oculus Rift with below the minimum required hardware?
I have tried to see if my GTX 960m supports VR and sadly it seems I need minimum GTX 970m, still I have seen videos that if you overclock your 960m you can get a decent 115 frames. My question is, can I still develop games for the Oculus Rift in my 960? I can't afford now to buy assets, oculus and a new laptop.

# Answer
Not easily, if your system can't support the hardware, you will encounter problems when trying to develop a game.

The Rift is a display and input device (orientation and head tracking), it's not doing most of the work when it comes to VR, you computer is. The video card is a critical part of that. The requirements for developing with the Rift are likely higher than they are for playing games with the Rift. Development code is often more resource intensive than fully optimized production code.
> 0 votes

# Answer
I expect that using a laptop with a 960m would be an unpleasant experience with the Rift. You might want to consider developing for GearVR instead because then the PC performance only impacts your development experience and not the app performance on the phone. Both the GearVR and a suitable phone can usually be found used for under $300usd total if you look around. While the Rift is obviously higher fidelity, I've seen some great stuff on the GearVR and have had fun working with it too.
> 0 votes

---
Tags: graphics, hardware, oculus
---


# Question
Title: glViewport() Win10 doesn't draw new parts
I've been steadily working through building a basic 2D tile framework in python.

I'm trying to use modern openGL so I have a simple shader and some vertex buffers and it's mostly doing what I want so far. I have a Scene with a method for centering the viewport on a Sprite:

```
def centre_viewport(self, x, y):
    x = -x+self.viewport_width//2
    y = y-self.viewport_height//2
    if x > 0:
        x = 0
    if y < 0:
        y = 0
    if x - self.viewport_width < -self.width:
        x = -self.width + self.viewport_width
    if y + self.viewport_height > self.height:
        y = self.height - self.viewport_height
    self.viewport_x = x
    self.viewport_y = y
    glViewport(x, y, self.viewport_width, self.viewport_height)

```

`self.viewport_width` and `_height` are set when a scene is added to the window, so they have the same dimensions as whatever window is created.

In my test game, the scene width and height are twice the window dimensions of `704x512`. Everything works fine on my main mac development machine. On my work windows machine though, when the sprite moves and causes the scene to scroll, the previously hidden parts of the scene are not drawn:

My draw loop is very simple:

```
def _draw(self):
    glBindBuffer(GL_ARRAY_BUFFER, self.sprite_vertex_buffer)
    glVertexAttribPointer(self.vertices, 3, GL_FLOAT, GL_FALSE, 0, None)

    glBindBuffer(GL_ARRAY_BUFFER, self.sprite_texture_buffer)
    glVertexAttribPointer(self.tex_coords, 2, GL_FLOAT, GL_TRUE, 0, None)

    glDrawArrays(GL_TRIANGLES, 0, self.sprite_vertex_count)

    glBindBuffer(GL_ARRAY_BUFFER, self.tile_vertex_buffer)
    glVertexAttribPointer(self.vertices, 3, GL_FLOAT, GL_FALSE, 0, None)

    glBindBuffer(GL_ARRAY_BUFFER, self.tile_texture_buffer)
    glVertexAttribPointer(self.tex_coords, 2, GL_FLOAT, GL_TRUE, 0, None)

    glDrawArrays(GL_TRIANGLES, 0, self.tile_vertex_count)

```

and as mentioned, it works fine on my mac.

Is `glViewport()` the appropriate way to be doing this, and why isn't it working properly on windows?

# Answer
So I solved my problem by doing things differently. I don't really want this to be the accepted answer because it doesn't answer why `glViewport()` isn't working properly on my Windows machine. However, I have a working viewport now, using a translation matrix:

first I modified my shader to accept a matrix and apply it to each vertex:

```
        attribute vec3 a_position;
        attribute vec2 a_texCoords;

        uniform mat4 t_matrix;

        varying vec2 v_texCoords;

        void main()
        {
            gl_Position = t_matrix * vec4(a_position, 1);

            v_texCoords = a_texCoords;
        }

```

in my Scene class, I hook into the matrix as part of my initialisation method:

```
self.transform_matrix = glGetUniformLocation(self.shader_program, "t_matrix")

```

and then whenever the viewport is moved, I update the matrix:

```
def centre_viewport(self, x, y):
    x = -x+self.viewport_width//2
    y = y-self.viewport_height//2
    if x > 0:
        x = 0
    if y < 0:
        y = 0
    if x - self.viewport_width < -self.width:
        x = -self.width + self.viewport_width
    if y + self.viewport_height > self.height:
        y = self.height - self.viewport_height
    self.viewport_x = x
    self.viewport_y = y
    #glViewport(x, y, self.viewport_width, self.viewport_height)

    self.viewport_matrix = [
                                1, 0, 0, self.viewport_x * 2.0 / self.viewport_width,
                                0, 1, 0, self.viewport_y * 2.0 / self.viewport_height,
                                0, 0, 1, 0,
                                0, 0, 0, 1,
                           ]

```

The matrix then gets uploaded to the GPU each time around the `_draw()` loop:

```
def _draw(self):

    glUniformMatrix4fv(self.transform_matrix, 1, True, self.viewport_matrix)

    ...

```

Notice that the matrix is transposed (3rd parameter set `True`), I could have constructed the matrix the right way around I suppose, but I think it looks tidier this way!

Ultimately this is a better way to do what I want anyway, because it gives me the option of translating the `z` axis too, if I want to do things with very tall towers later or something. I can probably offload pixel-\>ndc coordinate calculations by adding a projection matrix later if things need to be faster (not sure it'll make enough difference to worry about, but the option is there).
> 1 votes

---
Tags: opengl, python
---


# Question
Title: OpenGL can an Element Array Buffer points to only one VBO
I'm making a Minecraft style game and currently storing 36 vertices and texture coordinates per cube. Could I make an EBO for only the position and leave the texture coordinates as they are?

OK i think thsi is how i will do it.

I would have an array of 24 vertices(3\*GLfloat) and 24 texture coordinates(2\*GLfloat) for the corners

then i would have an EBO pointing to the corners with 36 indices

So memory total = 24\*3\*4 + 24\*2\*4 + 36\*4 = 624 bytes

instead of

36\*3\*4 + 36\*2\*4 = 720 bytes

# Answer
> 1 votes
No, you can't, however you can make it only use 24 vertices.

You can define each face with 4 vertices:

```
0, 0, 0
1, 0  0
1, 1, 0
0, 1, 0

```

Then the ibo would contain the data

```
0, 1, 3,
3, 1, 2

```

If you define each face separately, so that there's no overlap between separate faces, you need 6 * 4 = 24 vertices

If you calculate the byte count (let's say 1 value is 4 bytes) then your current solution is `36 * (3 * 4 + 3 * 4 + 2 * 4) = 1152` bytes. With only 24 vertices and the ibo (you need 36 value in the ibo for 1 cube) that becomes `24 * (3 * 4 + 3 * 4 + 2 * 4) + 36 * 4 = 912` bytes. (I counted the vertices, normals and texture coordinates, but if you have any more data, then the gap becomes bigger)

# Answer
> 3 votes
This is normally solved by adding an extra layer of indirection.

So, your GL\_ELEMENT\_ARRAY\_BUFFER will point to a vertex buffer containing two ints: one of which is a lookup for the position, the other of which is a lookup for the texcoord. In your vertex shader you read these, then use them to lookup other buffers (or textures) to get the actual data.

Of course, that means that your vertex fetching is a little more complex, which may negate any theoretical performance improvement from using less data. GPUs are counter-intuitive like that: sometimes the fast path involves using more memory.

---
Tags: opengl
---


# Question
Title: Could stealth and chase mechanics suit well for an exploration / branching paths game?
Our game focuses on exploring a city searching for clues and learning new skills to reach new locations to find something very valuable to the protagonist.

The game design is based on two ideas:

* Choices through gameplay. Instead of explicitly making the action of "choice", the outcome of a level objective is what makes the choice. For example: Gary's Eevee evolves into 3 different Pokémon depending on your previous battles with him in Pokémon Yellow. It's not something you chose; it's something that happened while you tried to win or lose against him.
* Real time actions. While you are doing an action (i.e. Jump over a fence), you may be interrupted by something or some NPC, and the resulting outcome differs a lot from the one expected by the player.

When we started testing the first levels, we noticed that the player may get bored exploring the streets of the city. The protagonist is a small sized animal (like an adult pet dog), and we wanted to make the scale of the city realistic relative to the main character, so in comparison the size differences of both protagonist and levels are huge.

So we thought of adding stealth and pursuit mechanics (the protagonist, as an animal, would have to avoid animal rescuers). Both of these mechanics seem to fit very well within the two main game ideas. But when it comes to implementing them, it becomes a huge hassle.

* Firstly, the player will be forced to escape once a pursuit sequence happens, trying to find a good hiding place, and will not stop to think where they should go.
* Then we have the problem that the game doesn't have a proper Game Over concept, but just bad endings, so we don't know how we should handle what will happen if the protagonist is caught. The only current possible "Game Over" situation is to starve (which on a normal gameplay would be almost impossible to achieve), and you'd have to start over from the very beginning because its considered a bad ending of the game. Getting caught might happen much more often, so if we do the same as for starting, it would be extremely frustrating for the player to play all the way from the beginning.
* Another problem, which is more production wise, is that it may turn out to be so time consuming to implement the AI of each NPC that may chase over the player, since we'd want to include factors such as personality, number of encounters with said NPC and the time the player has been within that NPC's FOV, and make a variation of pathfinding for these kind of Al's (we have to do it manually since we're using a custom engine).
* Also, we may have to rethink the design of certain streets and areas, which may alter the layout of the town, which is tightly designed after the branching story, the main axle of the game.

Is there a better way to include these stealth and chase mechanics, that minimize the occurrence of these problems? If not, would there be anotjer workaround?

# Answer
I find the first two "problems" not really to be big issues, in fact i think they can be positive experiences. I'll explain myself:

> Firstly, the player will be forced to escape once a pursuit sequence happens, trying to find a good hiding place, and will not stop to think where they should go.

If stealth is a mechanic, being spotted should have a punishment, in this case it is implicit, you must get out of your planned route to escape, thus you'll need to plan a new route based on your location after success.

> Then we have the problem that the game doesn't have a proper Game Over concept, but just bad endings, so we don't know how we should handle what will happen if the protagonist is caught. The only current possible "Game Over" situation is to starve (which on a normal gameplay would be almost impossible to achieve), and you'd have to start over from the very beginning because its considered a bad ending of the game. Getting caught might happen much more often, so if we do the same as for starting, it would be extremely frustrating for the player to play all the way from the beginning.

Being catched doesn't need to mean you get a game over, instead you might be taken to a different place, where you'll need to escape before you can continue with your main quest, this expands on the implicit punishment from my previous point.

These two concepts combined already give you two levels of punishment, which i feel are actually pretty balanced, as long as both the hiding from your pursuer and finding your way out of "jail" are fun experiences.

both punishments consume the player's time, which you could potentially use to alter the player's path towards one ending or another.

Now for your fourth point:

> Also, we may have to rethink the design of certain streets and areas, which may alter the layout of the town, which is tightly designed after the branching story, the main axle of the game.

you don't need to redesign the branching of the streets, instead you only need to find a way to implement hiding spots in the places that are already there. Also, this further enforces my second point in my opinion, if you get caught, you can potentially send the player to a 'jail' in a specific area that will potentially make the player get a "worse" ending.
> 2 votes

---
Tags: game-design, game-mechanics, level-design
---


title: Domain-specific languages for scripting

text:
# Question
Title: Domain-specific languages for scripting
As most of you know, embedded interpreters for languages like Lua and Python are widely used for scripting game logic, but I haven't seen much information on people going with domain-specific languages for their scripts, e.g. building a little logic scripting 'dialect' on top of the language used for the rest of the game, using macros or fluent programming or whatnot.

So my questions are as follows:

* What examples of such DSLs have you seen in real-world games?
* What problems were run into?
* Would you recommend this route for other game developers, and in what circumstances?
* Do you see this becoming more common as game development moves toward more metaprogramming-friendly languages, e.g. Boo?

# Answer
> 6 votes
My advice would be "don't".

I've used a domain-specific markup language for game data. It was a pain. I spent days designing it, and then every week or two I needed to tweak it to add more features. At one point I realized I needed to automatically generate some of my game data, and I ended up writing a small program to parse input files in the markup language, massage them, and output different files also in the markup language.

I honestly have no idea what I was thinking. The entire thing would have been simpler, more efficient, less bugprone, and far far less time-consuming if I'd just used Lua.

If you're working on such a restricted system that you can't start up a Lua environment, then perhaps you should use a DSL, but be prepared for agony. Otherwise I firmly believe you should just use Lua. Lua was originally designed as a simple data markup language and is still extremely conducive to using as such, and when (not if) you realize you need something more complicated, you've already got it. All of my current game development is done in Lua and I've never been more efficient or less bugprone.

I cannot recommend against DSLs strongly enough.

# Answer
> 2 votes
> I haven't seen much information on people going with domain-specific languages for their scripts, e.g. building a little logic scripting 'dialect' on top of the language used for the rest of the game, using macros or fluent programming or whatnot.

Scripting languages tend to be an expensive proposition in games. Even Lua, which is quite fast, is still very much slower than native code. Game teams are typically only willing to take that hit because it buys them two very big benefits in return:

1. The ability to change scripts without having to recompile and reload the game.
2. The ability for non-programmers to write scripts.

DSLs don't give you that, unfortunately.

# Answer
> 2 votes
I find it curious that your question limits itself to **internal** DSLs, since I'd rather advocate the use of an **external** DSL in order to get the ability to load scripts at runtime and especially to allow non-devs to write game logic in the DSL.

For instance, my current project is using a (for now) simple external DSL to specify part of the game logic that allows game designers to make balance tests mostly without dev intervention.

Of course you'll need to write a parser; to that end, I think the most recommended tool is ANTLR which targets quite a few languages. On my project though we went the parser combinator route with jParsec (our backend is Java, there are variants in other languages) which is quite nice for its close relationship with BNF but perhaps less well documented.

# Answer
> 2 votes
My advice would be: **Do**!

But only if you have a use for it.

No need to create a DSL if you are just going to use it yourself - internally.

Galaxy is the scripting language which the Startcraft II editor is using. It's a prime example of a domain specific language.

It targets game designers rather than programmers:

```
Timer - Start Raise Lava Timer as a One Shot timer that will expire in 20.0 Game Time seconds
Variable - Set Raise Lava Timer = (Last started timer)
Timer - Create a timer window for (Last started timer), with the title "Lava will raise in: ", using Remaining time (initially Visible)
Variable - Set Lava Timer Window = (Last created timer window)
Timer - Show (Last created timer window) for (All players)
Variable - Set Lava Death? = false

```

Sample Tutorial

Lisp is the perfect language to use to create domain specific languages, but there's other options, of course. Like Boo.

That way your designers/modders don't have to learn programming, even if it's just Lua, it's still programming.

Edit: Let me add that a DSL can be implemented in a scripting language - it's not synonymous with not using a scripting language. Especially if you are using Lisp or similar, since it lends itself extremely well to create domain specific languages.

# Answer
> 1 votes
Internal dsls are just syntactical sugar on a good API. The API is what is most important. After you have a good API making a dsl is trivial, and not that important.

# Answer
> 1 votes
If what you really need is a general purpose programming language then rolling your own is almost certainly a mistake. If your language seems to need variables, expression evaluation, loops, conditionals, classes, functions and the like then best stick to a known language like Lua, Lisp, Python, JavaScript, etc. \[Unreal have abandoned theirs.\]

But if what you need is mostly about defining data; is perhaps declarative rather than imperative; perhaps defines states and rules (like GDL); and does not need most of what a GP language does well, then consider a DSL.

But beware: creating languages and compilers can be very hard and prior experience is a big help. I would recommend a PEG parser (itself a DSL) based on an EBNF grammar (another DSL), and if that's too big an ask, then better not to try.

# Answer
> 0 votes
Arguably UnrealScript is a DSL. It seems to get the job done, although I think it's possible to make game scripting languages even more 'domain specific' than that. I would recommend making a DSL if there is something specific to the domain that will benefit from language changes - I have a few ideas in this area but nothing fully formed currently.

> Do you see this becoming more common as game development moves toward more metaprogramming-friendly languages, e.g. Boo?

I don't think that one fairly new engine supporting a language is evidence of game development moving in a given direction, however. It's early days yet.

---
Tags: scripting
---


# Question
Title: Should I use Unity for a "non-game" mobile app?
I have some experience with Unity but I always made games only. Right now I have an idea for an app but I don't think Unity is the most efficient way to do it. Probably Android SDK and OpenGL ES would be better but I have to learn them. **So should I learn a new tool or should I stick with what I already know and get this thing done?**

# Answer
> 2 votes
This is very dependent on the app. Unity is not only useful for games, but it should still be something game-like (eg. an architectural walkthrough). For a typical mobile UI app, I would recommend something more like Xamarin

# Answer
> 1 votes
This questions is a bit overly broad, but the simplest answer is use the best tool for the job. If you don't think Unity can best suit your application, use the technology that will.

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


# Question
Title: Help Understanding Cameras/View Matrices in DirectX11 (C#)
So I'm designing a soft game engine in C# on top of the SharpDX API (a C# wrapper for DirectX). As I'm designing the camera, though, I'm running into some issues getting the 3D perspective correct. I've read through a few tutorials and articles, but I can't seem to find what I'm doing explicitly wrong.

This is my current understanding: The world matrix is the identity matrix (of the world...) times the translation matrix of the model, times the rotation matrix of the model, times the scale matrix of the model, which should then give me the transformed location of each vertex in "world space." The view matrix would then be the output matrix of `LookAtLH(cameraPositionVec, targetPositionVec, upVec);`. Finally, the projection matrix seems to be the output of the `PerspectiveFovLH(fov, aspectRatio, nearDist, farDist);` So, I then took the transpose of each of these matrices, multiplied `world * view * projection` and I should be left with the final transformed vertex coordinate.

Here's the code I have so far. I've left the world matrix untouched by just setting the translation to the origin, the rotation of the model to the identity matrix, and the Scale to 1, which should mean I don't have to actually perform any world matrix calculations for the sake of simplicity right now.

```
// Setup and create the projection matrix.
projectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4.0f), ((float)GameWindow.WIN_WIDTH / (float)GameWindow.WIN_HEIGHT), 0.1f, 100.0f);

// Initialize the world matrix to the identity matrix.
worldMatrix = Matrix.Identity

...
//camera class
public Camera(Vector3 _position, Vector3 _target, Vector3 _rotation)
{
    position = _position;
    target = _target;
    rotation = _rotation;
}
public Matrix GetViewMatrix()
{
    //convert degrees to radians
    float pitch = rotation.X * 0.0174532925f;
    float yaw = rotation.Y * 0.0174532925f;
    float roll = rotation.Z * 0.0174532925f;

    //get rotation matrix and the relative up vector
    Matrix rotationMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, roll);
    Vector3 up = Vector3.TransformCoordinate(Vector3.UnitY, rotationMatrix);

    return Matrix.LookAtLH(position, target, up);
}

....

//set the view matrix
viewMatrix = camera.GetViewMatrix();

...
//Transpose the matrices
worldMatrix.Transpose();
viewMatrix.Transpose();
projectionMatrix.Transpose();

```

From there they are fed to the vertex shader, which is below. If I comment out the projectionMatrix multiplication though, the image shows up. If It's not commented out though, nothing renders to the screen, which leads me to believe that may be the issue.

```
//vertex shader
cbuffer MatrixBuffer
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};

struct VertexInputType
{
    float4 position : POSITION;
    float2 tex : TEXCOORD0;
};

struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : texCoord0;
};

PixelInputType main(VertexInputType input)
{
    PixelInputType output;

    // Change the position vector to be 4 units for proper matrix calculations.
    input.position.w = 1.0f;

    // Calculate the position of the vertex against the world, view, and     projection matrices.
    output.position = mul(input.position, worldMatrix);
    output.position = mul(output.position, viewMatrix);
    output.position = mul(output.position, projectionMatrix); //<-- If I comment this line, it renders to the screen
    // Store the texture coordinates for the pixel shader.
    output.tex = input.tex;

     return output;
}

```

I feel like I'm missing something really basic, because I think I'm pretty close. Thanks for any help you can provide.

# Answer
So, in the end, I'm not entirely sure why the above code doesn't work, but I believe it has something to do with the way that matrices are multiplied, which appears to vary, being either row-major or column-major. There's a much better description, which was posted as an answer to this question. Even with this in mind though, I was unable to fix the problem as my code stands, (possibly because of all the arbitrary transposing I've done near the middle of my code, which was inspired by some rather shoddy examples).

I then later stumbled upon another question regarding where I should be calculating my model-view-projection matrix at all. It seems that the best way to do such a task would actually be to do the calculation on the CPU and send that answer over to the GPU as a pre-processed matrix. I rewrote the hlsl file to this instead:

```
cbuffer MatrixBuffer
{
    matrix worldViewProjMatrix;
};

[...]

PixelInputType main(VertexInputType input)
{
    PixelInputType output;

    // Change the position vector to be 4 units for proper matrix calculations.
    input.position.w = 1.0f;

    // transform output mosition to screen space using w-v-p matrix
    output.position = mul(input.position, worldViewProjMatrix);
    // Store the texture coordinates for the pixel shader.
    output.tex = input.tex;

    return output;
}

```

Then, as per the suggestion on the first question I referenced, I calculated the model-view-projection matrix on the CPU using the following:

```
Matrix worldViewMatrix = worldMatrix * viewMatrix;
Matrix worldViewProjMatrix = (worldViewMatrix * projectionMatrix);
worldViewProjMatrix.Transpose();

```

I then wrote this to the buffer. The way in which I actually acquired the world, view, and projection matrices was not the issue at all. Hopefully this helps somebody else who has the same issue later.
> 1 votes

---
Tags: c#, rendering, camera, matrix, sharpdx
---


# Question
Title: Continous Movement and Gravity Switch With 1 button
I have a sphere with a rigidbody on it, and it moves to the right continously as I need it, but as it moves I want the space bar to be able to switch the gravity (so it either rides on the ceiling or on the floor), as it moves along to the right.

Please help, have been googling consistently for the past 3 hours.

Here is the code I have so far:

```
public class movement : MonoBehaviour {

    public float movementSpeed = 10;
    private bool haspressed;

    void Start()
    {
    }

    void FixedUpdate()
    {

        transform.Translate(Vector3.down * movementSpeed * Time.deltaTime);

        if (Input.GetKeyDown ("space") && haspressed == true) {
            transform.Translate (Vector3.right * movementSpeed * Time.deltaTime);
            haspressed = false;
        } else if (Input.GetKeyDown ("space") && haspressed == false) {
            transform.Translate (Vector3.right * movementSpeed * Time.deltaTime);
            haspressed = true;
        }
    }
}

```

Thank you sooo much!

# Answer
Figured it out.Now just need to figure out how to use only one key for this action.

```
using UnityEngine;

```

using System.Collections;

public class gravity : MonoBehaviour {

```
public float ychange = 5;
void Update () {
{
    if(Input.GetKey ("space")){

        Physics.gravity = new Vector3(0f,ychange,0f);}

}
    if (Input.GetKey (KeyCode.UpArrow)) {
        Physics.gravity = new Vector3(0f,-ychange,0f);}
    }
}

```
> 1 votes

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


title: tilting image for mode7 game in HTML5

text:
# Question
Title: tilting image for mode7 game in HTML5
I'm making a mode7 game like mario-kart and I need to tilt the image before I draw it, I have tried using a buffer canvas to tilt the image then draw it on the games canvas but this makes it laggy (because the image of map is 1280 x 2556.)

**So my question is:**

**How can I rotate my image before i draw it**

# Answer
This might be a bit late, but you could do this by rotating the image using CSS, if you want to dynamicly change the image you could rotate a canvas.

```
// Edit the prespective and rotation to get your desired result
canvasElement.style.transform = "perspective(600px) rotateX(20deg)";

```

Here is a JSFiddle: https://jsfiddle.net/8L4zgvkp/
> 1 votes

---
Tags: javascript, html5, performance, html-canvas
---