title: OpenGL Tessellation Shader Not Working

text:
# Question
Title: OpenGL Tessellation Shader Not Working
I've been trying to play around with tessellation shaders in OpenGL for a couple of hours now, but I'm having trouble to get it to work. I've been following The Little Grasshopper Triangle Tessellation with OpenGL 4.0, and I believed I had done the necessary OpenGL bureaucracy to get it to execute (but apparently not). My setup geometry is basically two triangles combined into a square, with just two attributes: position and texture coords. I have a vertex, tessellation control + evaluation, and also a fragment shader. You'll find all of the shaders below, as well as the setup code for the shaders (it's a wrapper, but there is nothing too surprising in there). Anyway, I've also added a screenshot of when I have the tessellation shaders on and off, and when they aren't enabled (just the vertex and the frag. shader), everything works OK. I've on purpose done so the TCS doesn't give new geometry, it just tries to mirror the input given (I'm aware it won't tesselate anything yet), but that doesn't work either.

I've also tried to move over the transformations done in the vertex shader (i.e. the MVP-transform) to the TES, but that didn't seem to help either. I thought it might have been the cause since I was doing tessellation work in camera-space (that is what is being done below, but I've tried the latter as well).

I'm honestly baffled, I can't for the life of me figure out what could be wrong. Maybe it's just some typo or some sort of name conflict in the interface blocks but I can't spot it. Any help is greatly appreciated!

Thanks for the help!

---

```
#version 410

// Vertex shader

in vec3 position;
in vec2 texture_coordinate;

uniform mat4 model;
uniform mat4 projection_view;

out PipelineData {
    vec4 position;
    vec2 texture_coordinate;
} vs_out;

void main() {
    mat4 pvm = projection_view * model;
    vs_out.texture_coordinate = texture_coordinate;
    vec4 homogenous_position = vec4(position, 1.0);
    vs_out.position = pvm * homogenous_position;

    gl_Position = vs_out.position;
}

```

---

```
#version 410

// TessControl shader

layout(vertices = 3) out;

in PipelineData {
    vec4 position;
    vec2 texture_coordinate;
} tc_in[];

out PipelineData {
    vec4 position;
    vec2 texture_coordinate;
} tc_out[];

void main() {
    tc_out[gl_InvocationID].texture_coordinate = tc_in[gl_InvocationID].texture_coordinate;
    tc_out[gl_InvocationID].position = tc_in[gl_InvocationID].position;

    gl_TessLevelInner[0] = 1;
    gl_TessLevelOuter[0] = 1;
    gl_TessLevelOuter[1] = 1;
    gl_TessLevelOuter[2] = 1;
}

```

---

```
#version 410

// TessEval shader

layout(triangles) in;

in PipelineData {
    vec4 position;
    vec2 texture_coordinate;
} te_in[];

out PipelineData {
    vec4 position;
    vec2 texture_coordinate;
} te_out;

void main() {
    te_out.texture_coordinate  = gl_TessCoord.x * te_in[0].texture_coordinate;
    te_out.texture_coordinate += gl_TessCoord.y * te_in[1].texture_coordinate;
    te_out.texture_coordinate += gl_TessCoord.z * te_in[2].texture_coordinate;

    te_out.position  = gl_TessCoord.x * te_in[0].position;
    te_out.position += gl_TessCoord.y * te_in[1].position;
    te_out.position += gl_TessCoord.z * te_in[2].position;

    gl_Position = te_out.position;
}

```

---

```
#version 410

// Fragment shader

in PipelineData {
    vec4 position;
    vec2 texture_coordinate;
} fs_in;

uniform sampler2D diffuse_texture;

out vec4 color;

void main() {
    vec4 diffuse_texel = texture(diffuse_texture, fs_in.texture_coordinate);
    color = vec4(1.0); // color = vec4(diffuse_texel);
}

```

---

```
// Excerpt of the setup code, with tessellation (see image below).
glPatchParameteri(GL_PATCH_VERTICES, 3);
Shader vertex_shader { PATH("shader/triangle.vert"), Shader::Type::Vertex },
       tesselation_control_shader { PATH("shader/triangle.tesc"), Shader::Type::TessControl },
       tesselation_evaluation_shader { PATH("shader/triangle.tese"), Shader::Type::TessEvaluation },
       fragment_shader { PATH("shader/triangle.frag"), Shader::Type::Fragment };

ShaderProgram shader_program { vertex_shader,
                              tesselation_control_shader, tesselation_evaluation_shader,
                              fragment_shader };

```

---

```
// Excerpt of the setup code, tessellation disabled (see image below).
// glPatchParameteri(GL_PATCH_VERTICES, 3);
Shader vertex_shader { PATH("shader/triangle.vert"), Shader::Type::Vertex },
       // tesselation_control_shader { PATH("shader/triangle.tesc"), Shader::Type::TessControl },
       // tesselation_evaluation_shader { PATH("shader/triangle.tese"), Shader::Type::TessEvaluation },
       fragment_shader { PATH("shader/triangle.frag"), Shader::Type::Fragment };

ShaderProgram shader_program { vertex_shader,
                              // tesselation_control_shader, tesselation_evaluation_shader,
                              fragment_shader };

```

---

```
GLFW version: 3.2.1 X11 GLX EGL clock_gettime /dev/js Xf86vm shared
GLEW version: 2.1.0
OpenGL vendor: X.Org
OpenGL renderer: AMD CYPRESS (DRM 2.50.0 / 4.14.13-1-ARCH, LLVM 5.0.1)
OpenGL version: 4.1 (Core Profile) Mesa 17.3.1
OpenGL GLSL version: 4.10
OpenGL extensions: GL_AMD_conservative_depth GL_AMD_draw_buffers_blend GL_AMD_performance_monitor GL_AMD_pinned_memory GL_AMD_seamless_cubemap_per_texture GL_AMD_shader_stencil_export GL_AMD_shader_trinary_minmax GL_AMD_vertex_shader_layer GL_AMD_vertex_shader_viewport_index GL_ANGLE_texture_compression_dxt3 GL_ANGLE_texture_compression_dxt5 GL_ARB_ES2_compatibility GL_ARB_ES3_compatibility GL_ARB_arrays_of_arrays GL_ARB_base_instance GL_ARB_blend_func_extended GL_ARB_buffer_storage GL_ARB_clear_buffer_object GL_ARB_clear_texture GL_ARB_clip_control GL_ARB_compressed_texture_pixel_storage GL_ARB_conditional_render_inverted GL_ARB_conservative_depth GL_ARB_copy_buffer GL_ARB_copy_image GL_ARB_debug_output GL_ARB_depth_buffer_float GL_ARB_depth_clamp GL_ARB_derivative_control GL_ARB_direct_state_access GL_ARB_draw_buffers GL_ARB_draw_buffers_blend GL_ARB_draw_elements_base_vertex GL_ARB_draw_indirect GL_ARB_draw_instanced GL_ARB_explicit_attrib_location GL_ARB_explicit_uniform_location GL_ARB_fragment_coord_conventions GL_ARB_fragment_layer_viewport GL_ARB_fragment_shader GL_ARB_framebuffer_no_attachments GL_ARB_framebuffer_object GL_ARB_framebuffer_sRGB GL_ARB_get_program_binary GL_ARB_get_texture_sub_image GL_ARB_gpu_shader5 GL_ARB_gpu_shader_fp64 GL_ARB_half_float_pixel GL_ARB_half_float_vertex GL_ARB_instanced_arrays GL_ARB_internalformat_query GL_ARB_internalformat_query2 GL_ARB_invalidate_subdata GL_ARB_map_buffer_alignment GL_ARB_map_buffer_range GL_ARB_multi_bind GL_ARB_multi_draw_indirect GL_ARB_occlusion_query2 GL_ARB_pipeline_statistics_query GL_ARB_pixel_buffer_object GL_ARB_point_sprite GL_ARB_polygon_offset_clamp GL_ARB_program_interface_query GL_ARB_provoking_vertex GL_ARB_robustness GL_ARB_sample_shading GL_ARB_sampler_objects GL_ARB_seamless_cube_map GL_ARB_seamless_cubemap_per_texture GL_ARB_separate_shader_objects GL_ARB_shader_bit_encoding GL_ARB_shader_objects GL_ARB_shader_precision GL_ARB_shader_stencil_export GL_ARB_shader_subroutine GL_ARB_shader_texture_image_samples GL_ARB_shader_texture_lod GL_ARB_shading_language_420pack GL_ARB_shading_language_packing GL_ARB_stencil_texturing GL_ARB_sync GL_ARB_tessellation_shader GL_ARB_texture_barrier GL_ARB_texture_buffer_object GL_ARB_texture_buffer_object_rgb32 GL_ARB_texture_buffer_range GL_ARB_texture_compression_bptc GL_ARB_texture_compression_rgtc GL_ARB_texture_cube_map_array GL_ARB_texture_filter_anisotropic GL_ARB_texture_float GL_ARB_texture_gather GL_ARB_texture_mirror_clamp_to_edge GL_ARB_texture_multisample GL_ARB_texture_non_power_of_two GL_ARB_texture_query_levels GL_ARB_texture_query_lod GL_ARB_texture_rectangle GL_ARB_texture_rg GL_ARB_texture_rgb10_a2ui GL_ARB_texture_stencil8 GL_ARB_texture_storage GL_ARB_texture_storage_multisample GL_ARB_texture_swizzle GL_ARB_texture_view GL_ARB_timer_query GL_ARB_transform_feedback2 GL_ARB_transform_feedback3 GL_ARB_transform_feedback_instanced GL_ARB_uniform_buffer_object GL_ARB_vertex_array_bgra GL_ARB_vertex_array_object GL_ARB_vertex_attrib_64bit GL_ARB_vertex_attrib_binding GL_ARB_vertex_shader GL_ARB_vertex_type_10f_11f_11f_rev GL_ARB_vertex_type_2_10_10_10_rev GL_ARB_viewport_array GL_ATI_blend_equation_separate GL_ATI_meminfo GL_ATI_texture_float GL_ATI_texture_mirror_once GL_EXT_abgr GL_EXT_blend_equation_separate GL_EXT_draw_buffers2 GL_EXT_draw_instanced GL_EXT_framebuffer_blit GL_EXT_framebuffer_multisample GL_EXT_framebuffer_multisample_blit_scaled GL_EXT_framebuffer_sRGB GL_EXT_packed_depth_stencil GL_EXT_packed_float GL_EXT_pixel_buffer_object GL_EXT_polygon_offset_clamp GL_EXT_provoking_vertex GL_EXT_shader_integer_mix GL_EXT_texture_array GL_EXT_texture_compression_dxt1 GL_EXT_texture_compression_rgtc GL_EXT_texture_compression_s3tc GL_EXT_texture_filter_anisotropic GL_EXT_texture_integer GL_EXT_texture_mirror_clamp GL_EXT_texture_sRGB GL_EXT_texture_sRGB_decode GL_EXT_texture_shared_exponent GL_EXT_texture_snorm GL_EXT_texture_swizzle GL_EXT_timer_query GL_EXT_transform_feedback GL_EXT_vertex_array_bgra GL_IBM_multimode_draw_arrays GL_KHR_context_flush_control GL_KHR_debug GL_KHR_no_error GL_MESA_pack_invert GL_MESA_shader_integer_functions GL_MESA_texture_signed_rgba GL_NVX_gpu_memory_info GL_NV_conditional_render GL_NV_depth_clamp GL_NV_packed_depth_stencil GL_NV_texture_barrier GL_NV_vdpau_interop GL_OES_EGL_image GL_S3_s3tc

```

# Answer
> 1 votes
After a couple of minutes after asking the question I was finally able to figure it out. It seems I missed to change the draw call to use patches instead of triangle primitives. For future reference to other ppl, when working with tessellation shaders, always use patches when drawing and set the amount too.

Below is the fix.

```
glPatchParameteri(GL_PATCH_VERTICES, 3);
Shader vertex_shader { PATH("shader/triangle.vert"), Shader::Type::Vertex },
       tesselation_control_shader { PATH("shader/triangle.tesc"), Shader::Type::TessControl },
       tesselation_evaluation_shader { PATH("shader/triangle.tese"), Shader::Type::TessEvaluation },
       fragment_shader { PATH("shader/triangle.frag"), Shader::Type::Fragment };

ShaderProgram shader_program { vertex_shader,
                              tesselation_control_shader, tesselation_evaluation_shader,
                              fragment_shader };

// in a galaxy far, far away.... from this code.

// Don't use! Tessellation shaders use GL_PATCHES!!!
// glDrawElements(GL_TRIANGLES, vertex_array.size(), // <-- ISSUE
//               GL_UNSIGNED_INT, nullptr);

// Use instead a call like below or DrawArrays.
// In conjunction with a glPatchParameter data.
glDrawElements(GL_PATCHES, vertex_array.size(), // <-------- FIX!
               GL_UNSIGNED_INT, nullptr);

```

---
Tags: opengl, c++, shaders, tessellation
---


# Question
Title: How to add the sound effect of a ball rolling, based on his velocity?
I have a ball which roll (like all ball does :) ) ...

My ball can roll on different type of surfaces (2 or 3) and at different velocity.

I don't know how to approach to reproduce in my game the sound effect.

I can assume to do :

1. Get an Sfx of a rolling ball
2. Run in loop if my ball is moving

then ?

Well.. i need some help.

Thanks

# Answer
I've solved.

If I move up/down the audio.Pitch based on rigidbody.velocity.magnitude, i obtain what i was looking for

Example:

\_audio.pitch = rb.velocity.magnitude / AudioSpeedAdjuster;
> 3 votes

---
Tags: unity, audio, sound-effects
---


title: Creating a skybox in Allegro 5

text:
# Question
Title: Creating a skybox in Allegro 5
I'm trying to render a "skybox" using Allegro 5, that 3D objects can move around "in front" of. I'm having trouble figuring out how to set up the projection transform and where to put the vertices for the quads that will have the background texture applied.

The plan is to use an orthographic transform the size of the skybox textures to place the quads, and only use rotation for the camera. Once the skybox is placed the depth buffer bit will be cleared and other objects perspective-transformed from their respective world-coordinates as normal.

The orthograpic transform API has the form

```
void al_orthographic_transform(ALLEGRO_TRANSFORM *trans,
 float left, float top, float n,
 float right, float bottom, float f)

```

while the struct which holds the vertex data the transform will be applied to has the form

```
Fields:

x, y, z - Position of the vertex
color - ALLEGRO_COLOR structure, storing the color of the vertex
u, v - Texture coordinates measured in pixels

```

If my skybox textures have pixel widths and heights of say w and h, the same for all 6 sides, how should the vertices be created and transforms applied using the API to render it properly?

# Answer
I've programmed with Allegro 4 and 5, but never done 3D with it. That said, I have done OpenGL with just plain Winmain and GLUT and it is all pretty much the same. All a skybox is, is a cube, each side has a 90 degree FOV (field of view), totaling 360 for all four north, south, east and west views, plus the top and bottom texture, which is also a 90 degree FOV. You basically just create a normal textured cube, except you reverse the winding to clockwise so the front face of each side faces inward, instead of out. When you render the skybox, you disable lighting and just give it a plain white colour. You can disable the depth buffer, fog etc... when drawing it. Also don't forget to clamp the texture edges so they are seamless. Then it's just a matter of rotating it, the center of the cube being the player's position. You do not translate it (move it) at all.

It's really not difficult at all to do. If you can create a textured cube, you can make a skybox.

Note: there are newer ways to do Skybox's with modern OpenGL and more optimal ways to render it with depth testing turned on believe it or not. There's some more modern information on how to do cubemaps and skyboxes at the following URL which could be coupled with Allegro or any other framework you use.

https://learnopengl.com/#!Advanced-OpenGL/Cubemaps
> 2 votes

---
Tags: opengl, 3d, transformation, allegro
---


# Question
Title: Which is more important to convey: good gameplay or good story?
While you can do both (and should strive to do so), when you're prioritizing what to focus on, you'll have to pick one to put effort into. So which is more important to convey: good gameplay or good story?

# Answer
You can (and probably should) do both at different stages of the product. How much or how little you invest into each option is entirely up to you.

You should probably spend *more* time on whichever of the two interests you more. The most important thing is to be able to *finish* your game, and you'll have a better chance of doing so if you are engaged with and enjoy the product you're making. No matter how much you like the process, there *will* be days when you're quite sick of it, so anything you can do to stack that deck in your favor helps.

You can have gameplay without a story (c.f., Tetris). But while you can tell story without gameplay, that's not a game. Even so-called "walking simulators" (like Firewatch) have a small element of mechanical interaction within them. Consequently, I'd generally advise that in the earliest stage of a project you focus most on the gameplay. Hone at least the core loop of game until it feels fun.

After that, if you have a story in mind, you can switch gears to focus more on its pacing and its integration with the mechanics of the game. Part of that process will often involve wanting to tweak mechanics to better mesh with the story -- that interplay is a unique feature of a game, after all, and it's good to play it up.

But as above, cycle between these in proportion to how they fit into the kind of game you're making, which in turn should reflect at least in part the kinds of things you enjoy in games yourself.
> 1 votes

---
Tags: game-design
---


# Question
Title: OpenGL interleaved position and normal data
I have an OpenGL question!

Say I have data, interleaved in the format

`[vec3 normal, vec3 vert1, vec3 vert2, vec3 vert3]`

all stored in one VBO (one set per triangle). My vertex shader would have the following attributes:

```
in vec3 normal;
in vec3 position;

```

Is it possible to extract the data this way? Or would I need to duplicate the normal for each vertex (eg. `[vec3 normal, vec3 vert1, vec3 normal, vec3 vert2, vec3 normal, vec3 vert3]`)?

# Answer
> 0 votes
OpenGL has no built-in concept of triangle or face normals; only vertices have normals.

If you wish for every fragment/pixel within the triangle to be drawn using the same normal, then you will need to provide that same normal for each of the three vertices that define the triangle. So yes, you need to duplicate the normal for each vertex.

---
Tags: opengl, c++, vbo
---


title: Texture upside down

text:
# Question
Title: Texture upside down
I'm making a top down 3d game. I made a model in blender, uv unwrapped it, and made a texture for it.

Texture in blender from the top:

I saved the model as a .blend file and the texture as a png.

I imported them in to unity, made a material and added the texture. But, when I add the material to the model the texture is upside down.

Texture in unity from the top:

I can't fix it myself and google was not helpful this time. Thank you.

I messed a round with tiling like Fabio S. said:

With these settings, I got:

Here is the uv map of the model:

# Answer
> 0 votes
I don't know for sure why you are having this issue, but I think you should probably try to change the values in your Tiling to -1 to see if that fixes the problem.

---
Tags: unity, textures, blender
---


# Question
Title: How should I design my score to visually accommodate large numbers?
I am creating a simple punching game that counts the total number of punches dealt.

Could you suggest a way for my game to visually accommodate very large numbers (\>100000). Currently my wire-frame looks like this:

How should I display very large numbers here? I thought about shrinking the fonts, and creating abbreviations, but I'm not sure it's the proper way to go.

# Answer
> 3 votes
A 64-bit unsigned integer can represent values from 0 to 18,446,744,073,709,551,615. That should be *plenty* large enough to track the number of punches scored by a user in your game.

As for displaying the value... at a bare minimum you should make sure to use the (locale-specific) appropriate digit grouping and separators. The number above is formatted using the US English convention of putting commas between every three digits, for example.

For *really* big numbers, though, digit grouping starts to get less effective. At that point, breaking the value down into pictographic groups can help. For example, represent every 1,000 hits with a punching glove icon and every 10,000 with a punching glove with a stick of dynamite on it, or something. Then you can draw large scores as (assuming `*` is the punching glove icon, and `!` the glove-with-dynamite icon):

```
2! 3* 122

```

Which represents 23,122 hits. You can adjust the scales accordingly, of course. This means that users only really need to track a three digit value in their head as they glance at the score, which should be reasonable for most people.

Writing out the values as words, as noted in the comments, is also a good option. However, if you expect your scores to get *really* big, icons will take up less horizontal space. And you don't have to translate them into other languages (probably).

The downside, of course, is that it may not be immediately obvious what value each icon stands for.

---
Tags: game-design, ui-design, user-experience
---


# Question
Title: How can I edit a float that is in another script? (In C#)
So basically, I have one script for the UI, which holds the float, score. Then I also have another script on my coin that detects when the player collides with it. What I want it to do is change the value of score, but I don't know how to change it, as it is in the UI script. How can I do this?

# Answer
It's really hard to help you solve a programming question if you don't provide any code...

Here is the idea, supposing the script attached to your UI is called `UIScript`

```
// Coin script

// Drag & Drop the gameobject holding the `UIScript` into the inspector
public UIScript theUIScript;

private void OnCollisionEnter(Collision collision)
{
    // Your code when a collision is detected ...

    theUIScript.AddPoints( 10 ) ;
}

```

---

```
// UI Script

public UnityEngine.UI.Text scoreText;

private int score = 0 ;

public void AddPoints( int points )
{
    score += points ;
    scoreText = score.ToString();
}

```
> 2 votes

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


# Question
Title: Implementing modular game control with JSON/etc. config file?
I'm having trouble wrapping my head around a method to compartmentalize my game control scheme within the game loop in an efficient way. Currently this is basically how my control works in bad pseudocode / JavaScript. I think this type of scheme is pretty standard for simple games..

```
Init() {

    function onKeyDown( event ) {
        switch( event.code ) {
            case 'KeyA':
                moveLeft = true;
            case 'KeyD':
                moveRight = true;
            etc...
    }

    document.addEventListener( 'keydown', onKeyDown, false );

}

GameLoop() {

    CheckControls();
    MoveWorldObjects();
    Render();

}

CheckControls() {

    if ( moveLeft ) velocity.x -= 10;
    if ( moveRight ) velocity.x += 10;
    etc...

}

```

This method has worked fine for me so far, especially since the eventListening is abstracted, and relatively quick for what I need it to do. However, as my game gets bigger the controls are starting to look very disorganized and I'm starting to wonder if this is a good program flow for a larger game.

Another problem is the fact that there are *multiple* control schemes in the game, so different characters will use different keys to activate different skills. It made sense to me to try loading different schemes at run time from JSON files, but I can't wrap my head around how I would do event handling from JSON, because I can only store values/gameStates, which I am already doing. Adding a JSON layer to the controls doesn't seem like it would help me at this point.

Is there an approach to organizing game control that I should read about? Or is it a good idea to keep all of the control responses very close to the game loop and simply try to work around that limitation. Or perhaps there is a way to separate basic controls (like movement) from more advanced/less high-speed responses like pulling up a UI?

Thanks in advance for any help! -G

# Answer
> 2 votes
This is the keyboard input method that I have been using in javascript.

First define the `keyboard` function, which I have shamelessly copied from somewhere (I'm honestly not who the original author was but it appears on StackOverflow a few times).

```
function keyboard(keyCode) {
    var key = {};
    key.code = keyCode;
    key.isDown = false;
    key.isUp = true;
    key.press = undefined;
    key.release = undefined;
    //The `downHandler`
    key.downHandler = function(event) {
        if (event.keyCode === key.code) {
            if (key.isUp && key.press) key.press();
            key.isDown = true;
            key.isUp = false;
        }
        event.preventDefault();
    };

    //The `upHandler`
    key.upHandler = function(event) {
        if (event.keyCode === key.code) {
            if (key.isDown && key.release) key.release();
            key.isDown = false;
            key.isUp = true;
        }
        event.preventDefault();
    };

    //Attach event listeners
    window.addEventListener(
                            "keydown", key.downHandler.bind(key), false
                            );
    window.addEventListener(
                            "keyup", key.upHandler.bind(key), false
                            );
    return key;
}

```

This bit of copy-and-past code gets hidden away, but now it allows us to do definitions like this, which used the keycode to define variables of keys.

```
 var left = keyboard(37),
     up = keyboard(38),
     right = keyboard(39),
     down = keyboard(40);

```

Now we add event functions to each key for `press` and `release`.

```
left.press = function() {
    movingLeft = true;
};

left.release = function() {
    movingLeft = false;
};

```

I would not advise to execute game code in the callbacks, but leave it in the main event loop. You can shift all of your input logic to these functions, though. For example, I am setting a flag above and then I will check that flag in the main loop. I am not trying to add velocity or do any game logic in the event.

This stays in the game loop

```
if ( movingLeft ) velocity.x -= 10;
if ( movingRight ) velocity.x += 10;
etc...

```

---
Tags: javascript, control, json
---


# Question
Title: Speedup Dev process for bug fixing and debugging in Unity?
*We're using Unity 2017 for a big Indie game. at the moment We have some issues with our development speed:*

In order to fix issues and bugs, We used the visual studio and attach the process to Unity and go through the code step by step. every time we change something (even just a line of code) we back to unity and wait for all scripts to recompile which takes up to 1 minutes sometimes. after that, we run the game and go to the place that bug happened which takes us about two minutes.

> I was wondering if there was a Best practice for fixing issues and debugging in Unity which brings us speedup on script compiles and also helps us to get to bug location faster.

# Answer
> 2 votes
Use assembly definitions available in 2017.3.

> Unity automatically defines how scripts compile to managed assemblies. Typically, compilation times in the Unity Editor for iterative script changes increase as you add more scripts to the Project.
>
> Use an assembly definition file to define your own managed assemblies based upon scripts inside a folder. To do this, separate Project scripts into multiple assemblies with well-defined dependencies in order to ensure that only required assemblies are rebuilt when making changes in a script. This reduces compilation time. Think of each managed assembly as a single library within the Unity Project.

You can try to separate your code into sections that are as decoupled as possible so that changes to app code will only need to recompile a few pieces at a time. Of course if you have a backend framework that you are debugging it will require recompiling quite a bit on top of it. If that is the case, you may want to create a separate project to reproduce just the issues you are trying to fix.

# Answer
> 2 votes
You could also consider writing unit tests which can be run externally to your game.

I have been using the built in Unity Test Runner and have saved countless hours fixing bugs by simply writing tests to validate my code.

Test driven development is certainly something I would recommend you implement especially as your project starts to grow in size and your architecture is changing organically.

---
Tags: unity, c#, development-speed
---


# Question
Title: Start iTween MoveTo from a specific node? (Unity)
I just started using iTween as part of my day/night cycle. I'm trying to move the sun and moon along a curve, but I want have the sun/moon start at a specific location depending on the time of day. That would mean beginning the `MoveTo()` function from, say, the 3rd node instead of the 1st node, but I can't figure out how to access specific nodes.

If that's not possible, is there some other workaround? I thought of making several paths of two nodes each and calling the next path once the first one finishes, but then the object has to move in a series of straight lines.

# Answer
> 1 votes
You must call iTween once. You would then call it each update. For example:

```
 public class doubleTween : MonoBehaviour {

     // Use this for initialization
     void Start () {
         iTween.RotateBy(gameObject,iTween.Hash("x", .25,"time",2, "easeType"
             , "easeInOutQuad", "loopType", "pingPong", "delay", .2));

         iTween.MoveTo(gameObject,iTween.Hash("x",6,"time",4,"loopType","pingPong"
             ,"delay",.4,"easeType","easeInOutQuad"));
     }

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

     }
 }

```

Hope this helps!

# Answer
> 1 votes
I am still not sure how to start at an exact percentage, but you can start from a specific node with something like this:

```
public int PathShift;

void Start() {

    Vector3[] UsePath = iTweenPath.GetPath("MyPath");
    ShiftArray(UsePath, PathShift);

    iTween.MoveTo(
        gameObject,
        iTween.Hash(
            "path", UsePath,
            "time", 200,
            "orientToPath", true,
            "moveToPath", false,
            "loopType", "loop",
            "easetype", "linear"
        )
    );

}

public static void ShiftArray<T>(T[] arr, int shift) {
    shift = shift % arr.Length;
    T[] buffer = new T[shift];
    System.Array.Copy(arr, buffer, shift);
    System.Array.Copy(arr, shift, arr, 0, arr.Length - shift);
    System.Array.Copy(buffer, 0, arr, arr.Length - shift, shift);
}

```

---
Tags: unity, curves
---


# Question
Title: Unity Rigidbody stops directly after moving
I'm creating a skating game, my Idea now for moving was when I move and then dont press any button anymore to move, it should still roll a bit and decrease momentum after a short while to fully stop. My problem now is when I dont press any buttons anymore after moving, it stops automaticly.

I came up with the idea of giving the rigidbody a force to the direction of the player, what is kinda working like I want to have it but its not realy connected with the momentum, it stops a little bit in the air or while I am skating then slowly going to stop. I want to use the momentum of my move Float "speed" to get keep the momentum and slowly decrease till it stops.

This is my code I came up with. I COMMENTED THE CODE ARE WHAT I CAME UP WITH LOOK ON "void Rolling" FUNCTION.

---

```
//MOVEMENT FLOATS
public float speed; //starting Speed float
public float maxspeed; // Maximum Speed float (changeable)
private float minspeed = 0;
public float dcrsSpeedMltpr; //decreaseSpeedMultiplier (changeable)
public float runSpeed;
public float turnSmoothing; //Smoothness of rotating (changeable)
public float jumpSpeed; //Speed of the Jump (changeable)

public GameObject rayCastGround; //Raycasting if Player is onGround or not
private Vector3 movement; //Sets the movement
private Vector3 targetDirection;
private Rigidbody playerRigidBody;
private Animator anim;
public LayerMask Groundmask; //Groundmask for Jump Bool

public bool isGrounded;
public bool isSkating = false;

void Awake()
{
    playerRigidBody = GetComponent<Rigidbody> ();
    anim = GetComponent<Animator>();
    speed = 0f;
}

void FixedUpdate()
{
    float lh = Input.GetAxisRaw ("Horizontal");
    float lv = Input.GetAxisRaw ("Vertical");

    Jump ();
    Move (lh, lv);
    Rolling ();

    if(lh > 0 || lv > 0 || lh < 0 || lv < 0 )
    {
        if(isGrounded)
        {
            anim.Play("SkatingAnim");
        }
    }
    else
    {
        if(isGrounded && speed == 0f)
        {
            anim.Play ("SkatingIdleAnim");
        }
    }
}

void Move (float lh, float lv)
{
    movement.Set (lh, 0f, lv);
    //movement = Camera.main.transform.TransformDirection(movement);

    //RUNSPEED
    if (Input.GetKey (KeyCode.LeftShift) && isGrounded)
    {
        movement = movement.normalized * runSpeed * Time.deltaTime;
    }
    //SET THE SPEED OF MAX AND MIN SPEED!
    else
    {
        if(Input.GetKey (KeyCode.A) || Input.GetKey (KeyCode.D) || Input.GetKey (KeyCode.W) || Input.GetKey (KeyCode.S))
        {
            speed = speed + dcrsSpeedMltpr * Time.deltaTime;
            if(speed >= maxspeed)
            {
                speed = maxspeed;
            }

            isSkating = true;
            if(isSkating)
            {
                anim.SetBool ("isOnSkating", true);
            }
        }
        else
        {
            isSkating = false;
            if(!isSkating)
            {
                anim.SetBool("isOnSkating", false);
            }

            speed = speed - dcrsSpeedMltpr * Time.deltaTime;
            if(speed <= minspeed)
            {
                speed = minspeed;
            }
        }
        anim.SetFloat("Skatespeed", speed);
    }

    movement = movement.normalized * speed * Time.deltaTime;

    playerRigidBody.MovePosition (transform.position + movement);

    if (lh != 0f || lv != 0f)
    {
        Rotating(lh, lv);
    }
}
//HERE IS THE CODE I CAME UP WITH ADDFORCE ON RIGIDBODY IT SHOULD ROLL A BIT AFTER STOPPING MOVING TILL THE MOMENTUM IS ZERO.
void Rolling()
{
    //MOVES A LITTLE BIT FURTHER WHEN PLAYER STOPS SKATING
    AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);
    if(!isSkating) //<- WHEN THE PLAYER STOPS SKATING IT GOES TO ROLL ANIMATION AND SHOULD THEN DECREASE ITS MOMENTUM TILL ZERO
    {
        playerRigidBody.AddForce(transform.forward * speed * 1.75f);
        Debug.Log(speed);
    }
}

void Rotating (float lh, float lv)
{
    targetDirection = new Vector3 (lh, 0f, lv);

    Quaternion targetRotation = Quaternion.LookRotation (targetDirection, Vector3.up);

    Quaternion newRotation = Quaternion.Lerp (GetComponent<Rigidbody> ().rotation, targetRotation, turnSmoothing * Time.deltaTime);

    playerRigidBody.MoveRotation(newRotation);
}

```

# Answer
You should consider adding a Physic Material to your skate and bring down the Dynamic and Static frictions.

Debugging is difficult and you have a lot of things going on in your script. Something could be interfering with something else. I suggest you strip it down and slowly add things back to it. Start with something like the below script that will move a cube left and right, pressing he up and down arrows. Once you have the deisred behavior, then add more of your script and see where it is breaking it.

```
public float force;

private Rigidbody rg;

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

void FixedUpdate()
{
    if (Input.GetKey(KeyCode.UpArrow))
    {
        rg.AddRelativeForce(Vector3.right * force ,ForceMode.Force);
    }
    if (Input.GetKey(KeyCode.DownArrow))
    {
        rg.AddRelativeForce(Vector3.right * -force, ForceMode.Force);
    }
}

```
> 1 votes

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


# Question
Title: Proper way to set a RigidBody's maximum velocity
I am trying to gradually accelerate a GameObject with a RigidBody attached until it reaches a maximum velocity, at which point it becomes unable to gain any more velocity.

* I know I can simply reset the object velocity to an arbitrary maximum velocity every frame if it overshoots, but I've repeteadly heard that manually setting an object's velocity is a very bad practice in the context of Unity's physics system.
* I am also aware that in a physical sense, objects don't have a "maximum velocity" and that such a thing will always be artificial.

I can think of several ways to achieve this, but given these limitations, I would like to know if there's a standard, optimum way to do this.

# Answer
> 3 votes
What you want to do is not to set the max velocity, but void applying any additional force once you get to a certain speed. Something like the example below. Watch the if statement

```
public float force;
public float sqrMaxVelocity;

private Rigidbody rg;

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

void FixedUpdate()
{
    if (Input.GetKey(KeyCode.UpArrow) && rg.velocity.sqrMagnitude < sqrMaxVelocity)
    {
        rg.AddRelativeForce(Vector3.up * force ,ForceMode.Force);
    }

}

```

---
Tags: unity, physics, rigidbody, rigid-body-dynamics
---


# Question
Title: How to create a user-friendly magic spell system?
I'm designing a small 2D top-down open-world survival-ish game with a magic spell system. The way it works so far:

* The player receives a "wand" at the beginning of the game
* As the player encounters new items and enemies, they gain spells to help them use those items/defeat those enemies

The problem I'm having is designing a way to cast the spells. At first, I just bound different spells to keys 0-10, but very soon the number of spells overwhelmed it, and you also have the problem of lower level spells not being used in the late game but still being bound to the most useful keys.

So, what's the best way to make a user-friendly spellcasting system? I can overhaul the way magic works in my game if needed.

EDIT: Just to clarify, I'm developing for PC in real time with large variation in spell type and purpose, although this question should apply to all platforms.

# Answer
There's no "best" way. The game design in your case is intimately connected with the UI design.

However, given your setup, I'll lay out (haha get it) some advice.

You're right about the lower-level spells being on the most convenient keys can be a problem. I would recommend something along the lines of Diablo 2 and 3 where you assign spells to keys in an interface. That way the user chooses which spells he wants to be readily accessible.

How those keys are set up will depend on the details of your game. Diablo 3 rigidly only allows 6 spell choices; choosing wisely is one of the important things players do in that game.

Diablo 2 allows all the function keys (and maybe more; I haven't played it since they made a ton of changes), so the player has many more spells accessible. In fact, any spell can be cast by opening the skill tree and selecting it with the mouse. That's more cantankerous and not useful in quick-reaction situations, so again the player is making choices about what is easily accessible.
> 30 votes

# Answer
Almo's advise to **allow the player to assign spells to hotkeys** according to their own preference is good. You can increase the number of spell slots if you allow modifier keys like `Ctrl` and `Shift` to access additional hotkey bars (but keep in mind that when the player has one hand on the keyboard in the typical `W``A``S``D` position and the other hand on the mouse, any numbers beyond 5 become awkward and beyond 7 become impossible to reach while also holding `Ctrl` or `Shift`).

Alternatively you can use a **hotkey bar cycling** system. Allow the player to set up multiple hotkey bars and have keys which cycle through the bars the player configured. That way the player can easily use different hotkey configurations for different situations.

But you might also want to think about less orthodox input methods.

**Mouse gestures**, for example. Represent each spell with a symbol. In order to cast the spell, the player draws that symbol with the mouse. You can reduce the complexity by combining it with hotkeys. For example, use a hotkey to select the element and then use a gesture to select how that element is used. However, recognizing mouse gestures reliably is not easy to program, and you have to implement it well to really judge if it is usable. I would only recommend you to try this when you are either 99% sure you want to go this way, when you have enough budget that burning a few hundred man-hours on this isn't an issue or if there is good 3rd party technology for this available for your technology stack.

Another option is to assign spells not just to single keys but to **sequences of keys**. Magicka is an interesting example. The game has over a thousand different spells, but they are cast with just 8 hotkeys. Simple spells are just one hotkey followed by a click, more complex ones have longer combinations. A frost ball is thrown with the sequence `D``Q``R``Click` and the mighty "Blazing Arcane Steamball" with `D``S``Q``F``Q``F``F``Click`. No, this system does not have a very beginner-friendly learning curve (and making the entirety of it available to the player after just a brief tutorial makes it worse). But mastering this system by figuring out the best combinations for each situation feels very rewarding for most players. After a while players memorize the sequences for their favorite spells and can cast them from muscle memory.

---

But if all of this is still not adequate to cover the variety of spells in your game, look into ways to reduce the number of spells available to the player at any given time. When you have spells which are "not being used in the late game", then why does the player even *have* them in the late game? When a late-game spell is simply a better version of an early-game spell and makes it obsolete, then it could just replace it completely in the user-interface.

There might also be some spells which are so situational that they don't deserve a hotkey. Those might be used from a menu. Monitor your testplayers and see which spells get used very rarely and usually not in time-critical situations (long-lasting buffs, for example). Ban those to the menu. A spell which is just used as part of the story might not even be a spell in the game-mechanical sense. When you have a "lift frog-shape curse" spell and exactly one person in the game who got turned into a frog, just have the player-character cast it in a cutscene.
> 21 votes

# Answer
In addition to the old classic, coming from fighter games - key combos. The better the spell, the longer the combo. This has the added benefit of feeling like casting, and a high level spell actually requires a bit more mental power.

If the mouse is an option then Legend of Grimrock has a nice idea - a 4x4 or 5x5 square board (can't remember). The combos are clicked on this board, as if you're drawing a spell.
> 8 votes

# Answer
A different angle is to eliminate

> the problem of lower level spells not being used in the late game

Two sample approaches to this are:

* All spells *scale* throughout the game; e.g. the spell that throws a puff of fire in the beginning of the game is the same spell that throws raging firestorms at the end of the game.
* Progression can come in the form of *upgrades* to spells. Firepuff was a brand new spell, but later on when you get fireball, it *replaces* firepuff. And when you find firestorm, it *replaces* fireball.
> 6 votes

# Answer
This answer might not be the one you want but I would suggest that you reduce the number of available spells to a number which can be bound to a your available hotkeys. Whats the point in having 100 spells which aren't any different from another? If you have a fireball which costs 5 mana (or whatever ressource you use) and deals 10 damage or a magic projectile which costs 10 mana and deals 20 damage, these spells aren't really different. Try to design spells which serve a different purpose and upgrade earlier spells to keep them relevant in terms of damage/cost.

If you want a special aspect or effect which is different from any other spell in your game then that should get your player another spell. Of course these can overlap but try to create spells which serve new purposes or solve different problems (or the same problems using a different approach) instead of adding new spells which are just upgraded versions of your old earlier spells.

Additionally you could check out Transistors skill system: https://transistor.gamepedia.com/Functions

Each "Function" has some effect (like damage, slow, charms enemies) and some way of targeting enemies (projectile, player dashes and hits enemies in the way, area of effect...). But you only have 4 different slots which you can assign these skills to. These slots are bound to 4 different keys which is easily manageable. As you gain more than 4 Skills you can combine them to get more powerful Skills which apply both effects. Therefore you get interesting combinations, let the player have enough different skills to solve different problems all while only using 4 keys.

With different problems or different ways to solve them I'm thinking of the following (just some examples):

* Problem: Huge/Strong enemy

Solution: Deal damage based on health of enemy (deals more because the enemy has very much health)

* Problem: Huge number of small enemies

Solution: Area of effect damage

* Problem: Player needs to escape or kite enemies, player needs to evade Attacks

Solution: Some teleport or dash spell
> 3 votes

# Answer
I've played a fair share of multi spell games where you have to be selective out of the roughly hundred spells to your availability.

For keyboard only control, I would have LOVED a sort of windows tab system where I can quickly scroll through my preset combos, defence, repair, press alt tab, click on window or alt tab through it.

In games like diablo and skyrim, there are plenty of cool spells i'd love to have used more, but using them was too elaborate when traversing a dungeon, diablo with the skill tree you had to remember exact spot, skyrim with the powers menu or the overly cluttered favorites menu.

To be able to quickly scroll in an already familiar way through presets would be a boon.

`ALT` \+ `Tab`, `2`, `alt` \+ `tab`, click, `3` is quick to do, and would help being to use all the cool stuff you code into your game.

If you feel adventurous, you could add speech control. Train an ai to recognise several speech patterns for your spell, have it part of the game as a mini game to train people to vocalise the spells properly to learn the spells for them to function. How awesome would it be to `fus do rah` against your computer and something would happen.
> 3 votes

# Answer
The default solution (most used, most widespread, most known to players) is a spell slot system.

You have a series of visible slots on the UI (between 2 and 10), which are assigned to default keys. In a game dialog the user can select which abilities are assigned to which slot. That game dialog always looks more integrated into the game than the Settings menu (where you change sound, graphics and key bindings). Examples are countless, but here's one from Spellforce III:

It's crucial that you **don't let the user bind spells directly to hotkeys** with this approach. The user binds spells to spell slots, and spell slots are bound to hotkeys. Keybindings are part of the setup and configuration experience, depend on the player and device, and are changed 0-2 times during the entire game. Switching spells is part of the gameplay, depends on the character and character progression (and is therefore part of the save state), and will be done 10+ times during the game.

There are plenty of alternative options, be it literal musical chants, combos, mouse patterns, voice recognition, or even something Kinect-based. But almost all of them prevent a player from letting a game rest for a year and then picking it up again with a old save, because too much learning and specialized knowledge is needed to play.
> 3 votes

# Answer
I can see 3 ways you can choose from:

1. **Categories the spell system**. Make a category for spells like this: Fire Spells contain Fireball, Firewall, Firewave, Firestorm, Firefall, etc., Cold Spells contain Ice Blast, Frost Nova, Blizzard, Frozen Orb, Glacial Spike, etc. and so on for Lightning spells, Earth spells, Water spells, Undead spells, etc. You could use the TES: Skyrim's category type: Destruction spells, Conjuration spells, Alteration spells, Illusion spells, Restoration spells.
This way you can set a key 0..9 to open up a category of spells and then use 0..9 to pick the spell in that category. So for instance if number 2 opens up the Cold spells and the forth spell there is Frozen Orb then by pressing 2-4 you cast a Frozen Orb. It would be good to have Q and E for instance, or some other two keys for favourite spells. it would be also good to be able to order the categories and order the spells within the categories making it user friendly for each user.
2. **Use a smart system that is set by the user**. Allow the user to set up favourite spells to the 0..9 keys. If you are using the mouse it's good to have a possibility to have a primary spell assigned to the left mouse button and an alternative spell assigned to the right mouse button; it's nice to be able to assign spells of your choice to those buttons. You could use the scroll wheel to scrolls through spells that could be assigned to the left or right mouse button for instance. You could create a radial popup menu for the middle mouse button (click the scroll wheel) with several customly favourited spells.
3. **Embed a hand-drawn spell system**. *(mouse gestures)* I saw this in one game the name of which I unfortunately no longer remember. Each spell is represented as a symbol that can be hand-drawn in one mouse click (I mean you press the mouse button and hold it - draw the symbol without releasing it, release when the drawn-symbol equals the symbol of the spell). Symbols can be letters that form a closed line or some made-up chars, for instance: letter '**O**' - for "**Obmolior**" (latin) - '*put in the way as an obstruction*' that will create an anti-spell shield in front of you or some counter-curse obstacle that will prevent you from being hit by spells. This system, however, is quite difficult to create and embed into a game.
> 0 votes

# Answer
> At first, I just bound different spells to keys 0-10

Rather than binding *individual spells* to keys, you might bind *functionality* to keys.

For example, rather than having three separate keys for fire, ice, and lightning attacks, you can have a single key for elemental attack, which automatically selects the most effective element for the target.
> 0 votes

---
Tags: game-design, design-patterns, ui-design
---


# Question
Title: How to simulate an elastic force, using Hinge Joint ?
I've a bucket connected to a rope.

I would like that when a ball fall in my bucket , my bucket "bounce"down and up .. like it is connected to an elastic rope.

How can i do that ?

Thanks

# Answer
You need to look into Spring Joint. I don't think the Hinge Join is appropriate to solve your issue.

Video Demo:

https://drive.google.com/file/d/1IpSi3Pg01kPa0mrAiemXcMs6tM--2QYb/view?usp=sharing

Unity3D documentation:

https://docs.unity3d.com/Manual/class-SpringJoint.html
> 1 votes

---
Tags: unity, physics
---


# Question
Title: How to "reset" velocity.y when entering water?
I'm using a raycast controller and kinematic ridigbody.

The way I've got my project set up is that I have a set of default values, such as gravity, jump height, etc., and when I enter a certain trigger, such as water, these values change (or, more specifically, I override these values temporarily).

My velocity.y += gravity * time.deltaTime, but there are some bugs if I jump into the water. For example, if I jump in from above then the velocity.y does not change in the water until I collide with the bottom of the water. Essentially it looks like I'm performing a normal jump, and only once I land will the changed gravity in the water trigger affect my movement. Also, if I jump in the water trigger from the side it sometimes propels me very high in the air.

When I print out the gravity value it does change immediately when I enter the water, but it seems the downward force from falling is never changed until I hit the bottom of the ocean floor.

```
public ControllerParameters2D Parameters { get { return overrideParameters
   ?? defaultParameters; } } //Returns updated parameters, or default
                             //parameters if overrideParameters is null

public void LateUpdate()
{
    JumpInSeconds -= Time.deltaTime; //Calculates how long until the player can jump again

    velocity.y += Parameters.gravity * Time.deltaTime; //Adds the force of gravity to the character's y velocity, scaled per time

    Move(Velocity * Time.deltaTime); //Moves the character per its velocity, scaled by time
}

public void OnTriggerEnter2D(Collider2D other)
{
    var newParameters = other.gameObject.GetComponent<ControllerPhysicsVolume2D>();

    if (newParameters == null)
    {
        return;
    }

    overrideParameters = newParameters.NewParameters;
}

public void OnTriggerExit2D(Collider2D other)
{
    var newParameters = other.gameObject.GetComponent<ControllerPhysicsVolume2D>();

    if (newParameters == null)
    {
        return;
    }

    overrideParameters = null;
}

```

# Answer
> 1 votes
One way to do that is to use vector2.scale().

This scales every value of a vector by a respective value of another vector. So you could say:

```
OnTriggerEnter2D(Collider2D){
  velocity = Vector2.Scale(velocity, new Vector2(1,0));
}

```

You can also do a check to see if the velocity's y value is negative (which means you're falling), then do a ontriggerstay2d check to see if he's still in the water, and scale the vector by a float. this way his velocity will change over time while he's in the water. make sure you don't set these values in update, or lateUpdate.

I also think the reason he doesn't slow down when he enters the water is because you might be setting the gravity in the update function. Set it in the start or awake function, and change it in ontriggerenter and ontriggerexit.

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


# Question
Title: Assets from Tiled background layer not appearing in Cocos2d-x
I'm running into an issue with a Tiled map used as a background image for a scrolling scene. I'm using two sprite sheets to provide assets for a background layer. In Tiled, all of these assets appear correctly, but in cocos2d-x, the assets from WorldSelectBG01.png do not appear. Any thoughts on what might be going on here?

Here's what the TMX file looks like:

```
<?xml version="1.0" encoding="UTF-8"?>
<map version="1.0" tiledversion="1.0.3" orientation="orthogonal" renderorder="right-down" width="1" height="10" tilewidth="640" tileheight="640" nextobjectid="15">
 <tileset firstgid="1" name="WorldSelectBG01" tilewidth="640" tileheight="640" tilecount="6" columns="3">
  <image source="WorldSelectBG01.png" width="1920" height="1280"/>
 </tileset>
 <tileset firstgid="7" name="WorldSelectBG02" tilewidth="640" tileheight="640" tilecount="6" columns="3">
  <image source="WorldSelectBG02.png" width="1920" height="1280"/>
 </tileset>
 <layer name="Background" width="1" height="10">
  <data encoding="csv">
1,
2,
3,
4,
5,
7,
8,
9,
10,
11
</data>
 </layer>
 <objectgroup name="GameSelectButtons">
  <object id="1" name="gd0" x="394" y="6308"/>
  <object id="5" name="gd1" x="251" y="6253"/>
  <object id="6" name="gd2" x="140" y="6113"/>
  <object id="7" name="gd3" x="227" y="5972"/>
  <object id="8" name="gd4" x="362" y="5907"/>
  <object id="9" name="gd5" x="499" y="5806"/>
  <object id="10" name="gd6" x="458" y="5651"/>
  <object id="11" name="gd7" x="336" y="5583"/>
  <object id="12" name="gd8" x="241" y="5477"/>
  <object id="13" name="gd9" x="294" y="5365"/>
  <object id="14" name="gd10" x="322" y="5213"/>
 </objectgroup>
</map>

```

And in cocos2d-x, I'm reading it like this:

```
void ABTScene::AddBackgroundTileMap(const std::string& backgroundTiledMapFilename)
{
    if (backgroundTiledMapFilename.empty())
    {
        return;
    }

    const cocos2d::Size visibleSize{ cocos2d::Director::getInstance()->getVisibleSize() };
    const cocos2d::Vec2 origin{ cocos2d::Director::getInstance()->getVisibleOrigin() };

    _backgroundTiledMap = cocos2d::TMXTiledMap::create(backgroundTiledMapFilename);
    CC_ASSERT(_backgroundTiledMap);
    if (_backgroundTiledMap)
    {
        CCLOG("Background tile map read from resource file: %s", _backgroundTiledMap->getResourceFile().c_str());
        cocos2d::Vector<cocos2d::TMXObjectGroup*>& objectGroups{ _backgroundTiledMap->getObjectGroups() };
        for (const cocos2d::TMXObjectGroup* objectGroup : objectGroups)
        {
            CCLOG("Object group found in tilemap: %s", objectGroup->getGroupName().c_str());
        }

        // all tiles are aliased by default, let's set them anti-aliased
        for (const auto& child : _backgroundTiledMap->getChildren())
        {
            static_cast<cocos2d::SpriteBatchNode*>(child)->getTexture()->setAntiAliasTexParameters();
        }

        _backgroundTiledMap->setAnchorPoint(cocos2d::Vec2(0.0f, 0.0f));
        _backgroundTiledMap->setPosition(origin);
        const float bgImageScaleFactor = visibleSize.width / _backgroundTiledMap->getContentSize().width;
        _backgroundTiledMap->setScale(bgImageScaleFactor);

        this->addChild(_backgroundTiledMap, -1);
    }
}

```

# Answer
Thanks to Thorbjørn Lindeijer for the answer!

The problem, as he advised, was that cocos2d-x only allows one tileset per layer - separating the background into layers solved the problem.

Updated file looks like this, and works. (Compression obscures the details, but each tile layer is only using assets from its paired tileset.):

```
<?xml version="1.0" encoding="UTF-8"?>
<map version="1.0" tiledversion="1.0.3" orientation="orthogonal" renderorder="right-up" width="1" height="18" tilewidth="640" tileheight="640" nextobjectid="15">
 <tileset firstgid="1" name="WorldSelectBG01" tilewidth="640" tileheight="640" tilecount="6" columns="3">
  <image source="WorldSelectBG01.png" width="1920" height="1280"/>
 </tileset>
 <tileset firstgid="7" name="WorldSelectBG02" tilewidth="640" tileheight="640" tilecount="4" columns="2">
  <image source="WorldSelectBG02.png" width="1280" height="1280"/>
 </tileset>
 <tileset firstgid="11" name="WorldSelectBG03" tilewidth="640" tileheight="640" tilecount="6" columns="3">
  <image source="WorldSelectBG03.png" width="1920" height="1280"/>
 </tileset>
 <tileset firstgid="17" name="WorldSelectBG04" tilewidth="640" tileheight="640" tilecount="4" columns="2">
  <image source="WorldSelectBG04.png" width="1280" height="1280"/>
 </tileset>
 <objectgroup name="GameSelectButtons">
  <object id="1" name="gd0" x="390" y="11424"/>
  <object id="5" name="gd1" x="247" y="11369"/>
  <object id="6" name="gd2" x="136" y="11229"/>
  <object id="7" name="gd3" x="223" y="11088"/>
  <object id="8" name="gd4" x="358" y="11023"/>
  <object id="9" name="gd5" x="495" y="10922"/>
  <object id="10" name="gd6" x="454" y="10767"/>
  <object id="11" name="gd7" x="332" y="10699"/>
  <object id="12" name="gd8" x="237" y="10593"/>
  <object id="13" name="gd9" x="290" y="10481"/>
  <object id="14" name="gd10" x="318" y="10329"/>
 </objectgroup>
 <layer name="Tile Layer 1" width="1" height="18">
  <data encoding="base64" compression="zlib">
   eJxjYCAdMAIxExAzAzELELMCMQAA1AAQ
  </data>
 </layer>
 <layer name="Tile Layer 2" width="1" height="18">
  <data encoding="base64" compression="zlib">
   eJxjYCAM2IGYA4g5gZgLhxoABDAAIw==
  </data>
 </layer>
 <layer name="Tile Layer 3" width="1" height="18">
  <data encoding="base64" compression="zlib">
   eJxjYEAF3EDMA8S8QMwHxPwMxAEADFAAQg==
  </data>
 </layer>
 <layer name="Tile Layer 4" width="1" height="18">
  <data encoding="base64" compression="zlib">
   eJwTZGBgEAJiYSAWYSAfAAATSABL
  </data>
 </layer>
</map>

```
> 1 votes

---
Tags: cocos2d-x, tiled
---


# Question
Title: How can I check if the ray is hitting specific objects names?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Map : MonoBehaviour
{
    public Camera mapCamera;
    public Text objectWasHit;
    public GameObject mouseOvered;
    public float distanceToHit = 1000;

    private Camera[] cameras;
    private List<GameObject> objectsToHit = new List<GameObject>();

    // Use this for initialization
    void Start()
    {
        cameras = Camera.allCameras;

        GameObject levels = GameObject.Find("_Level");
        foreach (Transform child in levels.transform)
        {
            child.gameObject.AddComponent<UnityEngine.MeshRenderer>();
            objectsToHit.Add(child.gameObject);
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.M))
        {
            if (mapCamera.enabled == false)
            {
                foreach (Camera cam in cameras)
                {
                    cam.enabled = false;
                }
                mapCamera.enabled = true;
            }
            else
            {
                foreach (Camera cam in cameras)
                {
                    cam.enabled = true;
                }
                mapCamera.enabled = false;
            }
        }

        bool rcHit = false;
        Vector3 mouse = Input.mousePosition;
        Ray castPoint = mapCamera.ScreenPointToRay(mouse);
        RaycastHit hit;
        Debug.DrawRay(castPoint.origin, castPoint.direction * distanceToHit, Color.magenta);
        if (Physics.Raycast(castPoint, out hit, distanceToHit))
        {
            rcHit = true;
            if (mouseOvered != hit.collider.gameObject)
            {
                mouseOvered = hit.collider.gameObject;
            }
            objectWasHit.text = mouseOvered.name;
        }

        if (!rcHit && mouseOvered != null)
        {
            mouseOvered = null;
        }
    }
}

```

Now it's hitting every gameobject and then display the object that was hit name:

```
objectWasHit.text = mouseOvered.name;

```

But I want it to display the name of the object/s only if it hit one of the objects in the List objectsToHit.

# Answer
> 3 votes
Use Unity Gameobject Tags to assign a tag just before adding them to the list so later you can check the hit only on gameobjects with that tag. First create a new tag on the editor

# Answer
> 3 votes
You can check what the Raycast hit by checking the tag:

```
hit.collider.compareTag("otherThingsTag");

```

or by checking the name:

```
hit.collider.name.Equals("otherThingsName");

```

If you want to check if multiple gameObjects are hit, then you can put them in a List and check what has been hit:

```
List<string> names = new List<string> { "thing1", "thing2" };
foreach (var name in names)
{
  if(hit.collider.name.Equals(name)
  {
     //do stuff
  }
}

```

# Answer
> 0 votes
I don't know if this is helpful but if you want to Raycast to specific object types you can attach a script to the objects that you want to find and look for that script. Something like this:

```
if (hit.transform.gameObject.GetComponent<AIUnit>() != null)
{
    Debug.Log(hit.transform.gameObject.name);
}

```

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


# Question
Title: "The associated script cannot be loaded", how can I see what script is associated?
I have a couple objects that are throwing errors in the warning log:

> The referenced script on this Behaviour (Game Object 'myObject') is missing!

Here is what they look like in the inspector:

How can I see what script is (or was) associated?

# Answer
> 2 votes
You can't. Scripts in Unity are linked by unique ID, and in this case you have no script connected to that UID.

This can happen if you copied & pasted scene/script files without their associated .meta files, which are where Unity stores this UID association. These files are hidden by default, making them easy to miss when organising your project outside of Unity. When Unity sees a script file with no .meta file, it generates a new one with a new UID.

This can also happen if you're working on a shared project and have not configured your version control system to handle metadata files correctly. Each user on your project ends up with their own UIDs for new files, which don't match up to everyone else's.

If you need to investigate this forensically, try going back to the source of any files you recently imported or synched to your project, or to your last working version. Find what script is associated with that UID in this source/working version, and change the UID in your current version to match. The .meta files are plain text, so a regular text editor will do the trick here.

---
Tags: unity
---


# Question
Title: Is my frame rate being calculated correctly?
I'm having a long headache (which may not be that complicated) with this frame rate thing. I already tested several frame rate algorithms, lastly I tested this here and they all gave something strange at some point, like choppy movements, skipping and other bizarre things.

Now I've used this "Variable Step" from the answer of this link and everything is running fine, but with all the stress past because of this I would like to know if the frame rate is actually right now:

(Just mentioning that this frame rate algorithm is from the user "Stephane Hockenhull" that is on the last link.)

```
Uint32 iMinimum_Fps_Delta_Time = (1000/50); // minimum 50 fps, if the computer is slower than this: slow down.
Uint32 iLast_Game_Step = SDL_GetTicks(); // initial value

while(bRunning) {
    Uint32 iNow = SDL_GetTicks();

    // Check so we don't render for no reason, avoid having a 0 delta time
    if(iLast_Game_Step < iNow) {

        Uint32 iDelta = iNow - iLast_Game_Step;

        if(iDelta > iMinimum_Fps_Delta_Time) iDelta = iMinimum_Fps_Delta_Time; // slow down if the computer is too slow

        //////////////////////////////////////////////////////////////////////////////////////////////////////////
        pState_Manager->handle_events(iDelta);
        pState_Manager->update(iDelta);

        iLast_Game_Step = iNow;

        SDL_SetRenderDrawColor(cEngine::oWindow.get_renderer(), 0, 0xAC, 0xE6, 0xFF);
        SDL_RenderClear(cEngine::oWindow.get_renderer());
        pState_Manager->draw();
        SDL_RenderPresent(cEngine::oWindow.get_renderer());

        cKey_Handler::clear_keys();
        cJoystick_Handler::check_joystick_connection();

        while(SDL_PollEvent(&oEvent)) {
            if(oEvent.type == SDL_QUIT) {
                bRunning = false;
                break;
            }
            else if(oEvent.key.keysym.scancode == SDL_SCANCODE_RETURN){
                bRunning = false;
                break;
            }

            if(oEvent.type == SDL_KEYDOWN) {
                if(oEvent.key.repeat == 0) cKey_Handler::set_pressed_keys(oEvent);
            }
            else if(oEvent.type == SDL_KEYUP) cKey_Handler::set_released_keys(oEvent);

            if(cJoystick_Handler::aDual_Shock_4) {
                if(oEvent.type == SDL_JOYHATMOTION) cJoystick_Handler::set_hat(oEvent);
                else if(oEvent.type == SDL_JOYAXISMOTION) cJoystick_Handler::set_axis(oEvent);
            }
        }

        pState_Manager->handle_inputs();
        //////////////////////////////////////////////////////////////////////////////////////////////////////////
    }
    else SDL_Delay(1);
}

```

Some useful (maybe) information:

**Renderer is set to:**

```
SDL_CreateRenderer(this->aWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

```

**Window's size is 960x720 and renderer logical size is:**

```
SDL_RenderSetLogicalSize(this->aRenderer, 960, 720);

```

# Answer
I would suggest you move

```
iLast_Game_Step = iNow;

```

Up just under your IDelta minimum test as you are executing logic in between that may affect your stepping. if you have anything that causes slow down between that and the setting of Last game step, then its going to cause your frame rate to jump up and down. As that logic is not being counted against the complete frametime.
> 0 votes

---
Tags: c++, sdl, game-loop, sdl2, frame-rate
---


# Question
Title: Does LibGDX have methods capable of creating dynamic text like in candy crush?
As you see, the "Retry" button and the "Invite Friends" button are both animated, smoothly and cleanly.

If I were to do this in Libgdx, would I have to use the Animation class and provide multiple texture regions of the buttons to create this animation effect? Or are in built methods included to help simulate this effect?

I've seen examples of people claiming you must use OpenGl ES methods directly. Is that true? Are there extensions to help create this effect?

# Answer
> 0 votes
If you're using `Actor`s you can use `Action`s to stretch the image. The action you're looking for is `ScaleByAction` which can be accessed using the `Actions.scaleBy` method.

So your code might look something like this:

```
Stage stage = ... // Create stage
Button button = ... // Create button

// Stretch button out, then in, then out, etc.
Action stretchSequence = Actions.sequence(Actions.sizeBy(10, 0, 1), Actions.sizeBy(-10, 0, -1));
// Repeat that sequence indefinitely
button.addAction(Actions.repeat(RepeatAction.FOREVER, stretchSequence));

stage.addActor(button);

// Then in your render() method
stage.act();
stage.draw();

```

---
Tags: java, libgdx
---


# Question
Title: representing transforms without a world/global reference frame
**Background:**

I'm trying to make a segmented/portal-based game engine that supports impossible (non-euclidean?) geometry.

By segmented/portal-based I mean the world is divided into segments which are connected by portals. This technique was used by the engines for classic shooters like Doom and Duke Nukem 3d.

The portals do not look or function like the portals in the game Portal, which is unfortunately what most of the results that queries containing "portal" bring up.

Each area is in its own coordinate system with each portal defining the transformation between the portal entrance in the origin segment and the portal exit in the destination segment.

It is possible for there to be multiple portals connecting the segments and for those portals to have different transformations. If I understand correctly, this makes the world non-euclidean and precludes storing a transformation for each connected segment on a segment.

Objects have transforms for each segment they are present in. So instead of the usual transform setup of objects having a local transform, a parent transform, and a world transform there is no world transform and it is possible to have more than one "parent" transform.

Advanced math is not my strong point. I understand the basics of the transformations but there are some details I don't fully grok and almost certainly some important or useful properties that I am not aware of.

**Questions:**

Where do I "store" or "collect" the results of applying transformations to an object?

Do I apply them to the object's local tranform or do I apply it to the object's transforms relative to "parent" segments?

It seems like a bad idea to accrue transformations on the local transform, but perhaps I don't understand the purpose of the local transform.

**Research before asking question:**

tutorial on simple portals in unreal that helped with outlining the transformation logic, but is focused on unreal and does not answer my questions.

flipcode portal rendering tutorial which gets brought out anytime there is a question about portal-based rendering. I have read through it a couple times, although the small font is hard for me to read so it is very possible I missed some details.

related question

related question

discussion on gamedev subreddit

# Answer
You do not need to have multiple reference frames in order to support portals.

You mentioned Duke Nukem 3D as the kind of portal system you want. That game fakes 3D using a technique called Sector-Over-Sector. Rooms are actually overlapping over the same 2D space, but because objects in different sectors do not see or interact each other, you can fake the appearance of multi-story levels. For example, look at this map layout:

This represents two rooms connected via a pathway. The two rooms overlap each other, but because you cannot view both rooms at the same time, it gives the illusion of being a top-and-bottom floor.

One downside of this technique is that you need to track which sector every object is in. Another is that you don't have arbitrary, "teleporting" portals.

Another technique is to use "true" portals, like you see in the game Portal. With this technique, you can connect parts of the map that are completely separate. Then you don't have to worry about which sectors objects are in, as the world position alone identifies where something is. One downside here is that each portal contains a transform - usually translate, but could have others like rotation - and for everything passing through these portals, you need to apply the portal transformation. This is especially troublesome for rendering, as you have to recursively perform rendering passes for each portal in view.
> 2 votes

---
Tags: 3d, mathematics, architecture, transformation, portals
---


# Question
Title: How to tell whether the joystick axis is released (not pushed) in SDL2 or in general?
I'd like to implement an event listener that triggers character movement (left/right/up/down or stay) according to the direction of pushed axis on the joystick. Due to jittering, the approach I found is to set area near (0, 0) as dead zone. However, by this approach, I can't tell when the axis is no longer pushed and goes back to the center. It's a very typical usage of joystick axis but I couldn't find helpful info elsewhere. Thanks in advance.

# Answer
> 1 votes
My experience is from working on a gamepad wrapper interfacing with the GLFW library, which appears to have a similar joystick API to SDL.

It can be difficult to discern the difference between a jittery unused joystick and someone slightly nudging it. For this situation, we can rely on *duration* as a practically differentiating factor i.e. a user likely won't be imitating a jittery yet resting joystick for very long.

This basically means you'll have to keep track of the joystick's previous position and a timestamp of the position when it enters the dead zone. Each time you resolve joystick motion, you'll have to check if the joystick has been in the dead zone for a length of time you decide on. The following pseudo code might help imagine what the reasoning could look like.

```
if (isInDeadZone()) {

    if (wasNotInDeadZonePreviously()) {
        // Just entered dead zone so record the time

    } else if (hasBeenInDeadZoneLongEnough()) {
        // Assume the user let go of the joystick

    } else {
        // Here the joystick's been in the dead zone but not enough time
        // has passed to consider the possibility that it was released.
        // This last clause isn't necessary for finding what you want and
        // is only here to clarify what happens when the logic falls
        // through.
    }

} else {
    // Someone is presumably using the joystick
}

```

Of course, the idea above could create false positives when the user manually holds a joystick within the dead zone for long enough. One way to guard against this is to have the dead zone customizable so it can be lowered as much as possible per joystick in order to make it harder to accidentally trigger the resting state.

# Answer
> 0 votes
```
struct ClassName
{
    static SDL_Joystick* controller;
    static Sint16 axis_x, axis_y;

    // ...initializes everything ...

    inline static void set_axis(const SDL_Event& e)
    {
        if(e.jaxis.which == 0) {
            axis_x = SDL_JoystickGetAxis(controller, 0); // 0 indicates x
            axis_y = SDL_JoystickGetAxis(controller, 1); // 1 indicates y
        }
    }
};

```

Then, inside the poll-event loop:

```
while(SDL_PollEvent(&e)) {
    // ..
    if(ClassName::controller)
        if(e.type == SDL_JOYAXISMOTION) ClassName::set_axis(e);
}

```

Now put this somewhere to get the specific dead zone range:

```
printf("AX: %d AY: %d\n", ClassName::axis_x, ClassName::axis_y);

```

---
Tags: sdl2, controllers, joystick
---


# Question
Title: Separate player rating systems for attackers and defenders
Imagine a kind of tower defence game where each player specialises either in defence or attack (a player is either one or the other in all games). In each game the attacker and the defender get separate scores. I want a leaderboard for the best defenders and a separate leaderboard for the best attackers. What are appropriate player rating systems in such a scenario? The ideal system is also efficient in that it produces robust rankings even if only a fraction of all possible attacker/defender combinations are actually played.

All the scoring systems I am aware of (e.g. Elo ratings or Microsoft TrueSkill) assume that both players are treated on an equal footing. I'd be extremely grateful for any pointers to relevant scoring systems.

# Answer
You can still use ELO rating in this situation.

ELO would not work properly if players sometimes play with advantage and sometimes with disadvantage. But that's not the situation you are in. When players always play the same role, they always have the same disadvantage. ELO makes no difference between a systematic disadvantage due to the game always being stacked against specific players or a disadvantage because some players simply have less talent.

You also don't need to have players play directly against each other in order for their ratings to be comparable. The whole point of ELO ratings is to be able to infer the relative strength of two players based on their performance against other opponents. It is even possible to compare the ELO ratings of chess players who weren't even active players at the same time. The ELO scores of two players who never met will be predictive as long as the graph of all games played has at least some remote connections between them.

ELO tells you the expected likeliness of a player beating another player. When there is a really successful defender who wins almost all games, then that defender will have a high ELO rating. When only a very few attackers are able to beat that defender from time to time, they must be exceptionally good attackers, so they also deserve a higher ELO rating than those who always lose against that defender.

When your game is asymmetrical with one role having a systematic advantage, then the ELO ratings of attackers and defenders won't be comparable. The disadvantaged players will have a lower average ELO. That means if players would be able to play both roles, you would need to track the defense-ELO rating and attack-ELO rating separately for each player. But you said you are already going to do this by having separate leaderboards for attack and defense and having each player create two separate user accounts if they want to play both.

Regarding Microsoft TrueSkill: I don't know enough about that system to tell if these points also apply to it or not.
> 2 votes

# Answer
This is possible with existing scoring systems. You need to treat **attacking players separately from defending players**, even if they are the same player.

Suppose you have three players (1, 2, 3), who have played a bunch of games against each other, both as attackers and as defenders. Instead of scoring them as if there were three players, split that into six: (A1, A2, A3, D1, D2, D3). That is, pretend that there are three players attacking exclusively, three players defending exclusively. No "A" player plays against another "A" player, same for the "D" players.

This is fine because the scoring systems should be able to rank players that don't play each other. The scores for attackers and defense would probably be different, say if the game was unbalanced between attack and defense, or if some players play attack more than defense and so on. You will need to scale each set of scores differently, in order to grade them.
> 0 votes

# Answer
Since the common part of a tower defense game is the tower, the scoring system could be based around the percentage of the tower remains at the end of the game.

An attacking player who does a lot of damage should receive a higher score than one who only does a little bit of damage.

Likewise, a defending player should score highly if a lot of their tower remains compared to one who's tower consistently gets destroyed.

This is assuming the play is one on one. If it's multiplayer, then the attacking player score calculation remains the same (based on individual damage caused with a small bonus for total damage) but the score for defenders should be put to lean more towards the number of individual attackers they kill with a small bonus for total remaining tower.
> 0 votes

---
Tags: game-design, multiplayer, leaderboards, scoring, ranking
---


# Question
Title: Some example of basic algorithms and frameworks used in game creation
I understand this sounds like a broad topic, I'm asked to have those skill from one of my applied job description. The thing is that i have been with Unity3d for 2~3 years, but I'm not really sure what are they asking for, it would be the best if you could give me a list of names or some examples to start with.

Thank you.

# Answer
> 1 votes
Yeah, that's definitely too broad, but here there are some examples of what you may need:

Algorithms

* Pathfinding algorithms, such as A\*, which are the basis for AI
* Raycasting algorithms, useful for determining the line of sight, sometimes for casting shadows and bullet collisions... (Good tutorials on 2d visibility/shadow)
* (I think they are called) Flooding algorithms, search the internet for those.
* maybe all the stuff regarding collision detection and response. It's not an "algorithm" but it's fundamental. Maybe search something like 2D collision, there are quite a few tutorials. (If you want and have time you can look different approaches to the problem, such as impulse resolved collisions or speculative collisions)

Frameworks I think the most used are:

* physics framework/engines such as Box2D, Bullet
* game structure: Artemis for example is an entity component system framework
* graphics: SDL, Qt

I don't know any of these frameworks, I prefer learning the raw algorithms, and I don't think you really should know them (they are too many), if they ask you study it, if they don't (and you don't need that for some kind of project), learn the algorithms.

---
Tags: game-design, algorithm
---


title: Airplane passenger point of view scene

text:
# Question
Title: Airplane passenger point of view scene
I'm building a game with unity where a lot of scenes take place in an airplane as a passenger seated near the window, the airplane has to do a take off and a landing.

I can't find any examples of similar scenes anywhere on Internet. So I was wondering which would be the best approach to do this :

* Simulate the airplane physics, "checkpoints" system where the airplane travels through each checkpoints (**current solution**)
* Animate the airplane with the unity animator system (tried it but it feels really cheap)
* Static plane but make things move around him (possibility to have better lightings inside the plane as it is static)
* 360° Videos

The current solution works ok but I'm looking for improvements. I found the intro scene from *The Forest* pretty similar to what I'm trying to acheive here and I was wondering how they did it.

The current system works like this :

The plane has two engines script who control the speed of the plane. Another script controls the yoke, roll and pitch of the plane. And the last script is the 'Autopilot', each checkpoint tells the plane where to go and at whitch speed. You have to tweak the values until you have a good result which can be really time consuming.

Thank you !

# Answer
You already mentioned the best solution, make the plane static and change the surrounding area. Especially when you mention the Forest, it is clear that the view out of the window isn't as important as what is going on in the plane. When choosing you should always consider where the focus is on. In plane view or the outside. Both is easy changeable.
> 1 votes

---
Tags: game-design
---


# Question
Title: Disable audio listener warnings? "There are no audio listeners...", "There are 2 audio listeners..."
The scene I'm working in constantly spams the message `There are no audio listeners in the scene. Please ensure there is always one audio listener in the scene`. If I add a dummy camera with an Audio Listener, I then get `There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene`.

I know this happens because our camera is created programmatically, with an audio listener. I also realize this will not affect the non-development build in any way.

Is it possible to disable these warnings completely?

# Answer
> 2 votes
I ended up enabling the Audio Listener on our login camera, then destroying it programmatically when the player camera spawns (this is what was causing the issue).

```
 staticCamera= GameObject.Find("StaticCamera").GetComponent<Camera>();
 Destroy(staticCamera.GetComponent<AudioListener>());

```

---
Tags: unity
---


title: What is the near plane equation in NDC?

text:
# Question
Title: What is the near plane equation in NDC?
I'm trying to compute the line intersecting my plane (transformed to NDC) and the near plane.
I have troubles to get a correct result and I think it is coming from the near plane equation.

I suppose that the equation in normalized device coordinates is \\$N=(0,0,1)\\$ and \\$O=(0,0,near)\\$.
But what is the value of \\$near\\$? Is it constant or it depends on the frustum?

# Answer
In NDC, the clipping planes are a box that goes from -1 to 1.
Near plane equation is therefore \\$Z+1=0\\$ and far plane \\$Z-1=0\\$
> 3 votes

---
Tags: opengl, transformation, frustum
---


# Question
Title: Unity: Change Text with Time (Text Flashes)
I am trying to display instructions within the Unity game. The idea is to have the instructions appear over time. For example, "instruction 1" then wait 5 seconds and show "instruction 2" instead of instruction 1 (on the same spot, in this case, I am changing the "message" variable in the code to change the instructions). This code does change the instructions but the problem is that it does it in a haphazard fashion. It appears that "instruction 1" is replaced with "instruction 2" and then it reverts back to "instruction 1" within a second and then back to "instruction 2" so instead of just 1-appearing-\>1-disappearing-\>2-appearing-\>etc in a smooth fashion, it does this weird flashing thing before proceeding to the next instruction. How could I fix this?

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

public class Growing : MonoBehaviour {

    public Text instructions;
    public string message;

    void Start () {
         instructions.text = message;
    }

    void Update () {

         Instructions();

         //other code to begin moving a game object
    }

    IEnumerator Instructions() {
        //run instructions
        message = "GET READY FOR YOUR FOCUSED BREATHING EXERCISE";
        yield return new WaitForSecondsRealtime(5);
        message = "MAKE SURE YOUR BODY IS COMFORTABLE";
        yield return new WaitForSecondsRealtime(5);
    }

```

# Answer
> 1 votes
Or the coroutine method:

You were almost correct, what you needed to do was wrap the `Instructions()` invocation inside a `StartCoroutine()` call. This lets Unity add the method to the task scheduler. Then, make sure you call it only once, either by putting it in `Start()` (as I've done below) or inside some other conditional that prevents multiple copies of the coroutine from being created simultaneously.

```
void Start () {

     StartCoroutine(Instructions());

     //other code to begin moving a game object
}

IEnumerator Instructions() {
    //run instructions
    message = "GET READY FOR YOUR FOCUSED BREATHING EXERCISE";
    yield return new WaitForSecondsRealtime(5);
    message = "MAKE SURE YOUR BODY IS COMFORTABLE";
    yield return new WaitForSecondsRealtime(5);
}

```

# Answer
> 0 votes
You start a new coroutine every time you call "update". YOu are not the first to ask this, and I'm not the first to answer, so let me just quote someone else:

> Yes, coroutines run independently, like separate threads. When you start a coroutine, an instance of it is created and starts running. If you start the same coroutine again, another instance is created and runs independently of the other, and so on. This is a blessing in some special cases, but much more often may become a curse: if you start a coroutine each Update, for example (a very common error), a new instance will be created each frame, crowding the memory and eating the CPU time in a few minutes
>
> http://answers.unity3d.com/questions/309613/calling-startcoroutine-multiple-times-seems-to-sta.html

As a starting point, try the following instead:

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

public class Growing : MonoBehaviour {

    public Text instructions;
    float instructionStartTime = -1;

    void Start () {
        LaunchInstructions();
    }

    void LaunchInstructions()
    {
        instructionStartTime = Time.time;
    }

    void Update () {
        if (instructionStartTime > 0 && Time.time >= instructionStartTime)
        {
            if (Time.time - instructionStartTime < 5)
                instructions.text = "GET READY FOR YOUR FOCUSED BREATHING EXERCISE";
            else if (Time.time - instructionStartTime < 10)
                instructions.text = "MAKE SURE YOUR BODY IS COMFORTABLE";
            else
            {
                instructionStartTime = -1;
                instructions.text = "";
            }
        }
        //other code to begin moving a game object
    }

```

---
Tags: unity, text
---


# Question
Title: synchronized transform is always 0,0,0 in Photon unity
I'm making a simple zombie co-op game with Unity and Photon and have problem with sync enemy transform.

First, I need to explain my idea of chasing enemy AI. Enemies are using NavMeshAgent to finding path, but I thought finding path on every player's computer is too much.

So I thought that it would be great if the zombie's target player is current player(The player who actually playing this game, not a master), then enables NavMeshAgent to finding path, otherwise, just update transform received from network(synchronized).

I think my idea is fine, so I made it. This is the code.

1. NetworkEnemy Script: This script sync animation and transform data via network. Using RPC to synchronize animation and use OnPhotonSerializeView to synchronize transform data.

```
public class NetworkEnemy : Photon.MonoBehaviour {
    Chasing chasing;        // The Chasing Script. I will explain later.
    GameObject target;
    NetworkPlayer targetNetworkPlayer;
    Vector3 syncPos = Vector3.zero;
    Quaternion syncRot = Quaternion.identity;
    ...

    void Start() {
        // target is Player and has NetworkPlayer component which derieves Photon.MonoBehavior. Of course, Player has PhotonView component.
        target = chasing.Target;
        targetNetworkPlayer = target.GetComponent<NetworkPlayer>();
    }

    void Update() {
        // Interpolate player loc/rot only target isn't local player.
        // Because if the target is local player, NavMeshAgent will control it.
        // IsLocalPlayer returns photonView.isMine
        if(!targetNetworkPlayer.IsLocalPlayer) {
            transform.position = Vector3.Lerp(transform.position, syncPos, 0.1f);
            transform.rotation = Quaternion.Lerp(transform.rotation, syncRot, 0.1f);
        }

        ... // Check is dead or something like that here...
    }

    ...

    public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) {
        if(stream.isWriting) {
            stream.SendNext(transform.position);
            stream.SendNext(transform.rotation);
        }
        else {
            syncPos = (Vector3) stream.ReceiveNext();
            syncRot = (Quaternion) stream.ReceiveNext();
        }
    }

    ...
}

```
2. Chasing Script: It controls(enable/disable) NavMeshAgent. If the target player is local player, turn this on. Else, turn this off. Also it checks player in the attack range and do attack.

```
public class Chasing : Photon.MonoBehaviour {
    NavMeshAgent agent;
    GameObject target;
    NetworkPlayer targetNetworkPlayer;

    ...

    void Awake () {
        ...
        agent = GetComponent<NavMeshAgent>();

        SetTarget(GetClosestPlayer());    // GetClosestPlayer returns closet Player GameObject
    }

    public void SetTarget(GameObject player) {
        target = player;
        targetNetworkPlayer = player.GetComponent<NetworkPlayer>();

        // If target is local player(photonView.isMine), activate NavMeshAgent
        if(targetNetworkPlayer.IsLocalPlayer) {
            agent.enabled = true;
        }
        else {
            agent.enabled = false;
        }
    }

    ...
}

```

I tested this code online but it wasn't working as I expected.

So I tested about 5~6 times and finally figured out what happens actually(I updated some of them. Please read carefully). Before that, I'm just gonna call "Master" player is A, and other is B.

1. In Player A(Master) sight
    1. If the target is A, it works
    2. If the target is B, it has (0,0,0) position
2. In Player B sight
    1. If the target is A, it works
    2. If the target is B, it works

In NetworkEnemy script, you were saw these codes:

```
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) {
    if(stream.isWriting) {
     stream.SendNext(transform.position);
     stream.SendNext(transform.rotation);
  }
  else {
     syncPos = (Vector3) stream.ReceiveNext();
     syncRot = (Quaternion) stream.ReceiveNext();
  }
}

```

I'm synchronizing it's transform but why another player got 0,0,0 only it wasn't master?

Is my idea is wrong? Then should I activate NavMeshAgent always to every zombies from every players? If that so, how to solve the issue that each player's game calculates different path?

Those scripts are observed by PhotonView component. There is no more scripts that updates zombie's transform, they're all.

If I approach wrong way, then it will be very appreciate it how to make Co-op enemy path finding system efficiently.

Any advice will very appreciate it.

# Answer
> 1 votes
I solved this problem by using RPC. Remove whole OnPhotonSerializeView code and add new RPC Function like this:

```
[PunRPC]
void UpdateZombieTransform(Vector3 pos, Quaternion rot) {
    syncPos = pos;
    syncRot = rot;
}

```

And in Update function, paste this code:

```
if(!targetNetworkPlayer.IsLocalPlayer) {
    transform.position = Vector3.Lerp(transform.position, syncPos, 0.1f);
    transform.rotation = Quaternion.Lerp(transform.rotation, syncRot, 0.1f);
}
else {
    photonView.RPC("UpdateZombieTransform", PhotonTargets.Others, transform.position, transform.rotation);
}

```

I don't know why it works and why OnPhotonSerializeView is not :( I solved this problem, but can anyone tell me why this is works?

Anyway if you faced same problem as me, I hope this solution work for you. Thanks.

# Answer
> 0 votes
One thing: let do the master client the work: spawn enemies, add target and calculate the path.

And only synchronized the position/rotation on other clients.

Maybe `OnPhotonSerializeView` doesn't work properly because your script doesn't inherit from `IPunObservable`.

And using RPC for syncing position and rotation isn't a good idea.

---
Tags: unity, multiplayer, transformation, photon
---