# Question
Title: Why is my openGL rendering faster when I time it with GL_TIME_ELAPSED
I have some code that was rendering too slowly, as in there was a noticeable lag in when updating the screen in response to user input. I tried profiling the CPU side code, but that did not seem to be the problem. So I tried measuring the time taken on the GPU side. When I did that, the rendering suddenly got faster!

I've set up conditional compilation set up so I can switch back and forth and the slowness returns if I remove the GPU timing call. It seems like my graphics card manufacturer was trying to cheat on benchmarks or something? Is there any other reason why this would happen? Here's the code in question:

(I'm using Rust but I hope that the OpenGL calls are clear enough to someone familiar with OpenGL from other languages.)

```
let query_ids = [0; 1];
if cfg!(feature = "time-render") {
    unsafe {
        gl::GenQueries(1, query_ids.as_ptr() as _);
        gl::BeginQuery(gl::TIME_ELAPSED, query_ids[0])
    }
}
// render some stuff...
if cfg!(feature = "time-render") {
    let mut time_elapsed = 0;
    unsafe {
        gl::EndQuery(gl::TIME_ELAPSED);
        gl::GetQueryObjectiv(query_ids[0], gl::QUERY_RESULT, &mut time_elapsed);
        gl::DeleteQueries(1, query_ids.as_ptr() as _);
    }
    dbg!(time_elapsed);
}

```

Did I mess up the calls to OpenGL somehow? The timings I'm getting out seem reasonable enough: they are all around the same value, fluctuating up and down by a few 10s of microseconds.

**Edit**: I tried @user1118321's suggestion of removing the query and adding a glFlush, but that did not have the same effect as the time elapsed query.

I've modified the code as follows:

```
    if cfg!(feature = "time-render") {
        let finish_now = std::time::Instant::now();
        let mut time_elapsed = 0;
        unsafe {
            gl::EndQuery(gl::TIME_ELAPSED);
            gl::GetQueryObjectiv(query_ids[0], gl::QUERY_RESULT, &mut time_elapsed);
            gl::DeleteQueries(1, query_ids.as_ptr() as _);
        }
        let finish_nanos = finish_now.elapsed().as_nanos();
        println!("query took {}ms", finish_nanos as f64 / 1_000_000.0);
        println!("rendering took {}ms", time_elapsed as f64 / 1_000_000.0);
    } else {
        let flush_now = std::time::Instant::now();
        unsafe {
            gl::Flush();
        }
        let flush_nanos = flush_now.elapsed().as_nanos();
        println!("gl::Flush took {}ms", flush_nanos as f64 / 1_000_000.0);
    }

```

If I compile the program without "time-render" enabled I get output like this when running it:

```
gl::Flush took 0.0011ms
gl::Flush took 0.0023ms
gl::Flush took 0.0004ms
gl::Flush took 0.0009ms
gl::Flush took 0.0013ms
gl::Flush took 0.0004ms
gl::Flush took 0.0008ms
gl::Flush took 0.001ms
gl::Flush took 0.0012ms
gl::Flush took 0.0024ms

```

If I compile it with "time-render" enabled I get output like this:

```
query took 0.5638ms
rendering took 0.206504ms
query took 0.569ms
rendering took 0.206255ms
query took 0.5856ms
rendering took 0.204844ms
query took 0.5473ms
rendering took 0.205176ms
query took 0.5342ms
rendering took 0.205259ms
query took 0.5867ms
rendering took 0.213891ms
query took 1.3657ms
rendering took 0.216547ms
query took 1.538ms
rendering took 0.208828ms
query took 0.6028ms
rendering took 0.20833ms
query took 0.5656ms
rendering took 0.207168ms

```

So when "time-render" is enabled the code takes longer to run, but the screen updates faster! Bizarre.

I've done a little reading on `glFlush`and this answer to a different question notes that calling `glFlush` before swapping the buffers in a double buffering setup will have no effect. So, it might be worth mentioning that the very net thing that happens after the function that contains the code I posted is run, is this `swap_buffers` function from a library is called. It then calls into platform specific code, but presumably it is using the OpenGL symbol I passed to it during startup to swap buffers for me.

**Edit 2**: I decided to try `glFinish` instead of `glFlush` in the above code, for completeness. If I do, then the percieved speed is actually as fast as with "time-render" enabled above! I get output like this though:

```
gl::Finish took 2.0424ms
gl::Finish took 1.6895ms
gl::Finish took 1.8569ms
gl::Finish took 2.7918ms
gl::Finish took 1.5629ms
gl::Finish took 1.4513ms
gl::Finish took 1.6008ms
gl::Finish took 1.7746ms
gl::Finish took 2.5587ms
gl::Finish took 1.7089ms

```

...which indicates that the code is taking slightly longer to complete than the GPU rendering and the time query combined. I also measured the total time the function containing the posted code took, and that bore that conclusion out. So I guess I'm going to keep the timing query in then, since in seems to be the fastest! I can only guess at what's happening inside the GPU/graphic driver but maybe the implicit flushing that the query does is skipping something that `glFinish` does? If that's the case, then it doesn't seem to be affecting the actual rendering! That at least sort of makes sense, I think.

# Answer
> 1 votes
This is a very poor design even before the issues you mentioned came to light.

In order to make these queries asynchronous like they are supposed to be, you're expected to jam a fence into the command queue immediately following the issue of the end timestamp.

Now, evidently the temptation in this code snippet is to read the value of end immediately, but ... surprise, surprise, the GPU has not even started working on your frame yet and waiting on the result is going to sit and spin while 2-4 or more frames go through the render pipeline and the GPU finally gives you a timestamp counter that you can readback.

> *If you do manage to read something back without waiting, the results are going to be undefined.*

*You are **killing CPU/GPU parallelism** and more than likely don't want performance measurements taken while the render pipeline is in duress.*

This is why your code is full of horrible flush / finish commands. Stop doing that and use a fence sync object instead. Once per-frame check the status of the fence you planted after your timestamp query. If the fence is signaled, now you can readback the timer query with no ill-effects.

> The GL, of course, has a way of checking whether queries are ready, but this is how that check is more or less implemented and other APIs basically require you to put fences in the command stream to figure out whether a command is retired yet or not, so it's handy to learn.

This most likely doesn't answer your question, however, if you're willingly waiting on something to finish that's generated through pipelined execution there's no telling what else is wrong with your software. I'd do a quick survey of all read-back sites and try to develop any code using those readbacks the ability to tolerate 3-4 frames of latency.

---
Tags: opengl, performance, optimization
---


# Question
Title: Layout problem when implementing chat UI in Unity
I want to implement UI layout in Unity:
And here's what I've already done in Unity using an scroll view and putting a `Vertical Layout Group` and a `Content Size Fitter` on its content
Now the problem is because I'm using `Vertical Layout Group` on scroll view's content I'm unable to assign the x value of these chat bubbles because I have to align the other user's chat bubbles to the left and align the self chat bubbles to the right just like the first image. Any ideas on that?

# Answer
Here is a quick proof of concept of how I would do this:

Wrap each text bubble in another object which has the width of the whole chat box.

1. The ChatBox has a Vertical Layout Group with "Force Child Expand" on. This causes the "Wrapper" child objects to always have the width of the full chat box.
2. The "Wrapper" child objects is solely responsible for defining the space in which the chat bubble should be aligned. You might want to hide this object by removing the `Image` and `CanvasRenderer` components so it's nothing but a `RectTransform`. I just left them visible in this screenshot to better illustrate what is going on.
3. The "ChatBubble" is then placed within the "Wrapper". To switch between left-aligned and right-aligned boxes, set the `Anchor` and `Pivot` positions like this:

You can use the Width of the ChatBubble and the Height of the Wrapper to control the horizontal and vertical size of the bubble.
> 4 votes

---
Tags: unity, ui-design
---


# Question
Title: How to make character not enter the platform when colliding on the side with the platform?
**I had a problem with detecting my character's collision with the enemy being detected in 2 ways:**

* side by side
* when it (character) jumps into the enemy's head.

I imagine it to be basic, so I figured this question would be not only on the site but also in countless other places.

**I researched this site and found related things, but not exactly what I would like:**

Getting 2D Platformer entity collision Response Correct (side-to-side + jumping/landing on heads)

Handling exact collisions on character controller and/or other objects in unity? (eg. head shot, chest , leg,etc)

**But because of this video I got it:**

https://www.youtube.com/watch?v=9LbutnLIj84

---

**The game I'm doing is platform, but instead of the character move, it's the platform that moves.**

**obj\_Plataform - Step Event:**

```
if jump==false{
    if !place_meeting(x,y+1,obj_Player){
        vspeed=-5;
    }else{
        vspeed=0;
    }
}else{
    if contJump<20{
        contJump+=1;
    }else{
        jump=false;
        contJump=0;
    }
}

```

This is a code that causes the platform to go up when it is not in contact with the player.

And it has a condition for the platform jump (it goes down and the `jump` variable becomes true, and after the counter reaches a certain value the `jump` variable becomes false).

**My problem is that the character can not get into the platform by colliding on the side with it (The character is the white cube):**

I thought about using `place_meeting` in relation to the x-axis, but the whole platform is just an object (error), because I do not know if it would be possible to move some of dozens of tiles at the same time in the correct way.

**Plataform:**

I also tried something related in a collision event among those involved, including using the character's x, but nothing worked.

I thought a condition to prevent the platform from walking left while it is colliding with the character.

**obj\_Plataform - Keyboard Event (left arrow):**

```
x-=10;

```

Above the current code to move the platform to the left.

# Answer
> 1 votes
Today I understood a little more about the function `place_meeting`.

**Documentation:**

https://docs.yoyogames.com/source/dadiospice/002\_reference/movement%20and%20collisions/collisions/place\_meeting.html

**obj\_Plataform - Keyboard Event (left arrow):**

```
if !place_meeting(x-7,y+3,obj_Player){
    x-=10;
}

```

With this code you prevent the platform from moving to the left if any part of it is colliding with the character.

**Two important points:**

* activate precise collision checking on the platform sprite.

* by adding a y-axis value (`y+3`), you give the platform a chance to move even if the character is a bit sunk in it.

**Value varies from project to project.**

---
Tags: collision-detection, game-maker
---


# Question
Title: How to support more than 4 XInput controllers?
I'm making a multiplayer game in GameMaker Studio 2. The game supports upto 12 controllers, where the first four are XInput controllers. The rest would be DirectInput.

If I try playing with 8 Xbox controllers, only 4 of them are detected in the game, as expected.

But, is there a way to get more than 4 Xbox controllers working?

# Answer
> 2 votes
Xinput library only supports 4 controllers at a time - please refer to the wiki page on Directinput -DirectInput Wiki. May take some work, but you could enumerate some of the controllers under Direct Input initially, then eliminate those being detected by XInput. That would require interrogating the GUIDs on the controllers. I believe you can obtain them in XInput.

---
Tags: multiplayer, game-maker, controllers, xbox-controller
---


# Question
Title: Unity character vibrates during idle animation
My player character vibrates in his idle pose for some reason. He has 3 animations (IdleState, WalkState, RunState) and the latter 2 run smoothly, but when I don't provide directional inputs and he enters his idle state, he looks like he had 100 espresso shots!

43 second video demo here: https://youtu.be/QuHPrkjx-T4

I am not using a blend tree for the moment and the animation used for IdleState was exported with only a single frame (frame 1) from Blender. Unity's FBX import panel has the animation listed as playing from frame 0 to 1. I have tried many different configurations for this animation in the importer, including looping, not looping, matching pose, setting animation length to 0. None of that fixed the jitters (the latter nullified the animation). I have restructured my scripts but have not found a solution for this yet.

My character uses 2 scripts, one to control movement, and another to control animation.

This one controls movement:

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

public class PlayerController : MonoBehaviour {

    private float charSpeed;
    public float walkSpeed;
    private float runSpeed;
    public float jumpForce;
    public CharacterController controller;
    public float gravityScale;
    private Rigidbody rb;

    public static Vector3 moveDirection;

    // Start is called before the first frame update
    void Start() {
        controller = GetComponent<CharacterController>();
        rb = GetComponent<Rigidbody>();
        charSpeed = walkSpeed;
        runSpeed = walkSpeed * 2;

    }

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

        if (Input.GetButton("Fire3"))
        {
            charSpeed = runSpeed;
        }
        else {
            charSpeed = walkSpeed;
             }

        // Declare movement vector
        moveDirection = new Vector3(Input.GetAxis("Horizontal") * charSpeed,
            moveDirection.y,
            Input.GetAxis("Vertical") * charSpeed);

        // Set y-axis movement conditions (jumping, grounded, free-fall)
        if (Input.GetButton("Jump") && controller.isGrounded){
            moveDirection.y = jumpForce;
        }
        else if (!controller.isGrounded)
        {
            moveDirection.y = moveDirection.y + Physics.gravity.y * gravityScale * Time.deltaTime;
        }
        else
        {
            moveDirection.y = 0;
        }

        // rotated 45 deg to align controls to camera instead of world space:
        Vector3 rotated = Quaternion.Euler(0,-45,0) * moveDirection;
        controller.Move(rotated * Time.deltaTime);

        Vector3 lookDir = new Vector3(rotated.x, 0, rotated.z);

        if (lookDir != Vector3.zero)
        {
            transform.rotation = Quaternion.LookRotation(lookDir);
        }
    }
}

```

...and this one plays the animations:

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

public class CharacterAnimator : MonoBehaviour
{

    private Rigidbody rb;
    Animator animator;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        animator = GetComponent<Animator>();

    }

    void FixedUpdate() // was Update(), no change
    {
        if (Input.GetAxis("Horizontal") == 0 && Input.GetAxis("Vertical") == 0)
        {
            animator.Play("IdleState");
        }
        else
        {
            if (Input.GetButton("Fire3"))
            {
                animator.Play("RunState");
            }
            else
            {
                animator.Play("WalkState");
            }
        }
    }
}

```

What is causing this jittery idle state bug?

# Answer
> 1 votes
**SOLVED (technically; it would still be better for me to set animations to be run by the animator instead of script):**

I set the animation play speed to 0 for the IdleState and that eliminated the jittery-ness during the IdleState animation. This worked because that animation only has one frame:

IMPORTANT NOTE: I had to get rid of the transitions (connections between states in the Animator panel) because it was causing my animations to not loop under my current setup. Now everything is smooth-running...and smooth-walking...and smooth-standing.

---
Tags: unity, animation, character
---


# Question
Title: Unity Editor - Adding Object Fields on button click
So I am trying to make a button that will spawn an object field and a float field when clicked. Each object field being unique, so I can add gameobjects to it. I can’t think of a way to do this. This is purely Editor Scripting. Also, if there is an option to delete a row (the object field and the FloatField) that would be amazing

# Answer
> 1 votes
Here's some quick code I wrote down. Hope this solves the issue you were having.

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

public class SomethingEditor : EditorWindow {

    private static List<Object> objs = new List<Object>();
    private static List<float> floats = new List<float>();
    private static Vector2 v = Vector2.zero;

    [MenuItem("MenuItem/Test")]
    private static void DoIt () { EditorWindow.GetWindow<SomethingEditor>(); }

    void OnGUI () {
        EditorGUILayout.BeginScrollView(v);

        if(GUILayout.Button("Create an object")) {
            floats.Add(default(float));
            objs.Add(default(Object));
        }

        for (var i = 0; i < objs.Count; i++) {
            objs[i] = EditorGUILayout.ObjectField(objs[i], typeof(Object), false);
            floats[i] = EditorGUILayout.FloatField(floats[i]);
        }

        if(GUILayout.Button("Print")) {
            for (var i = 0; i < objs.Count; i++) {
                Debug.Log(objs[i]);
                Debug.Log(floats[i]);
            }
        }
        EditorGUILayout.EndScrollView();
    }
}

```

You can obviously make changes to make the editor look better, but you can have something like this.

---
Tags: unity
---


# Question
Title: Need to separate textures for Unity prefabs
I'm a beginner at Unity and so I apologise if I'm asking a really stupid/simple question.

I have a number of 3d objects that were exported from a Blender project an then imported into Unity.

I grabbed the texture out of Blender and reapplied it in Unity.

Now I want to apply separate textures to each of the Prefab objects, but when I do, the texture change applies to all the prefabs. Likewise, if I try to duplicate one of the prefabs and apply a different texture, it applies to all of the prefabs.

Can I separate the prefabs so that I can apply individual textures to each?

Do I have to reimport the objects individually?

# Answer
> 1 votes
Thanks to a great comment by @DMGregory who put me on the right answer for this.

It was simply a matter of creating a new material for the Objects that I wanted to change the texture on.

The easiest way (for me) to do this was to:

1. create a new material,
2. apply the texture to it
3. edit the prefab and drag the new material onto it.

Super-simple when you realise that a material is a single thing and changing it will change all objects that use that material.

---
Tags: unity
---


# Question
Title: How to measure time interval (different languages)
What is the recommended way to measure time intervals for a game loop?

Consider the situation in which a developer is writing their own game loop. Using a third party game engine such that you do not write your own game loop is beyond this question.

In general I want the best API from the standard library, unless there is reason to not use it. The exception being well stablished game development libraries that do not force a game loop on the developers.

---

Ideally the solution is not to use System time. We want something unaffected by time zones, leap seconds, daylight saving, the user messing with the system clock, etc… plus the system time usually has poor resolution for games.

I also found Time a Function - Rosetta Code, it uses system time in some cases.

---

*This is a community wiki.*

# Answer
---

## JavaScript

**On the browser**

For code running in the browser, I would strongly advice to use requestAnimationFrame as game loop. See availability.

Example:

```
function update(timestamp)
{
    // …
    window.requestAnimationFrame(update);
}

window.requestAnimationFrame(update);

```

`requestAnimationFrame` takes a callback that will be called once per frame, matching the monitor refresh rate. The callback receives a double representing the milliseconds since time origin.

> **The time origin** The time origin is a standard time which is considered to be the beginning of the current document's lifetime. It's calculated like this:
>
> * If the script's global object is a Window, the time origin is determined as follows:
> * If the current Document is the first one loaded in the Window, the time origin is the time at which the browser context was created.
> * If during the process of unloading the previous document which was loaded in the window, a confirmation dialog was displayed to let the user confirm whether or not to leave the previous page, the time origin is the time at which the user confirmed that navigating to the new page was acceptable.
> * If neither of the above determines the time origin, then the time origin is the time at which the navigation responsible for creating the window's current Document took place.
> * If the script's global object is a WorkerGlobalScope (that is, the script is running as a web worker), the time origin is the moment at which the worker was created.
> * In all other cases, the time origin is undefined.

-- Mozilla

Aside from the game loop, you can get a milliseconds timestamp since time origin by calling `performance.now()`. See availability.

Example:

```
var start = performance.now();
// …
var elapsed = performance.now() - start;

```

I want to strongly recommend the talk Jake Archibald: In The Loop - JSConf.Asia 2018 that covers how the browser event loop works and when exactly `requestAnimationFrame` runs.

---

**On Node.js**

Node.js does not have `requestAnimationFrame`. Instead use `setImmediate`.

It can be a good idea to use `setTimeout` with the time for the next tick. And to do that effectively, you need to measure time… Thankfully `performance.now` continues to work in Node.js.

---

## Java

In Java you want to use System.nanoTime:

```
long start = System.nanoTime();
// …
long elapsed = System.nanoTime() - startTime;

```

I have seen claims that `System.nanoTime` is not thread safe. That is not true, it is thread safe. `System.nanoTime` delegats the request to the operating system, apparently there were some platforms that had bugs.

---

## Python

**With Pygame**

If you are using Pygame, you want to call `clock.tick`. It returns the milliseconds since the last call.

Note: It takes a desired frame rate as argument, and will insert delays if it is been called too soon for that frame rate.

In your game loop, you want to call it every iteration, passing the target frame rate:

```
clock = pygame.time.Clock()

while running:
    delta = clock.tick(60)
    # …

```

To measure elapsed time you want to use `get_ticks()` instead:

Example:

```
start = pygame.time.get_ticks()
# …
elapsed = pygame.time.get_ticks() - start

```

`pygame.time.get_ticks` returns milliseconds.

**Note**: Pygame uses SDL. In fact, `pygame.time.get_ticks` delegates to `SDL_GetTicks` which returns milliseconds (Uint32) since DSL initialization.

---

**Without Pygame**

If you are not using Pygame, use `time.perf_counter()`. It returns a float that represents time in (factional) seconds.

Example:

```
start = time.perf_counter()
# …
elapsed = time.perf_counter() - start

```

---

## C

**C on POSIX**

Use `clock_gettime`. You will need the `time.h` header. It takes a clock id that can be either `CLOCK_REALTIME`, `CLOCK_MONOTONIC`, `CLOCK_PROCESS_CPUTIME_ID`, or `CLOCK_THREAD_CPUTIME_ID` and a pointer to a `timespec`:

```
struct timespec {
    time_t   tv_sec;        /* seconds */
    long     tv_nsec;       /* nanoseconds */
};

```

The following is example usage:

```
struct timespec start, end;
double elapsed_sec;
clock_gettime(CLOCK_MONOTONIC, &start);
// …
clock_gettime(CLOCK_MONOTONIC, &end);
elapsed_sec = (end.tv_sec + end.tv_n_sec - start.tv_sec + start.tv_nsec)/1000000000.0;

```

**Note**: `clock_gettime` returns 0 on success. On failure it returns -1 and sets *errno*, it could be `EFAULT` (Invalid pointer) or `EINVAL` (Not supported clock id).

---

**C on Windows**

We will use `QueryPerformanceCounter` and `QueryPerformanceFrequency`:

```
// Once
LARGE_INTEGER frequency;
BOOL available = QueryPerformanceFrequency(&frequency);

LARGE_INTEGER start;
QueryPerformanceCounter(&start);
// …
LARGE_INTEGER end;
QueryPerformanceCounter(&end);
double elapsed_sec = (double)((end.QuadPart - start.QuadPart)/(double)frequency.QuadPart);

```

If `available` is false, you can fallback to `GetTickCount` which gives you milliseconds.

The answer to the question "Best way to get elapsed time in miliseconds in windows" has a nice wrapper.

---

**C on OSX, Objective-C**

We will use `mach_continuous_time` from `mach_time.h`.

```
// once
mach_timebase_info_data_t timeBase;
mach_timebase_info(&timeBase);
// unit conversion for nanoseconds
double timeConvert = (double)timeBase.numer / (double)timeBase.denom;

double start = (double)mach_continuous_time() * timeConvert;
//…
double elapsed = ((double)mach_continuous_time() * timeConvert) - start;

```

**Note**: `mach_timebase_info` can fail. It should return `KERN_SUCCESS`, otherwise, you would have to fall back to system time.

---

## C++

Use `std::chrono::high_resolution_clock::now`. You will need the `chrono` header.

Example:

```
high_resolution_clock::time_point start = high_resolution_clock::now();
// …
high_resolution_clock::time_point end = high_resolution_clock::now();

auto elapses_sec = (end - start).count();

```

See also `duration_cast`.

---

**SDL**

If you are using SDL, you can use `SDL_GetPerformanceCounter` and `SDL_GetPerformanceFrequency`. Example:

```
// Once:
uint64_t PerfCountFrequency = SDL_GetPerformanceFrequency();

// …

uint64_t start = SDL_GetPerformanceCounter();
// …
uint64_t end = SDL_GetPerformanceCounter();
double elapsed_sec = (double)((end - start) / (double)PerfCountFrequency);

```

**Note**: This method would be equivalent to `SDL_GetTicks` when no better timer is available.

---

## PHP

Use `hrtime`. When called with `true` as parameter, it returns nanoseconds. `int` or `float` depending on the platform.

Example:

```
$start=hrtime(true);
// …
$end=hrtime(true);
$eta=$end-$start;

```

`hrtime` is stable across requests, and is not susceptible to changes in system time.

**Before PHP 7.3.0**

You want `microtime`. It uses Unix time and will return a float in seconds if you pass `true` as argument.

Example:

```
$start = microtime(true);
// …
$elapsed = microtime(true) - $start;

```

`microtime` is stable across requests. It is based on system time.

---

## .NET (C#, VB.NET, etc…)

On Mono or .NET Framework, you want to use `System.Windows.Forms.Application.Idle` for your game loop. It has also been added to .NET Core 3.0.

And for the elapsed time, use a Stopwatch.

Example:

```
var stopWatch = new Stopwatch();
stopWatch.Start();
// …
var timeSpan = stopWatch.Elapsed;

```

Or for example with `ElapsedMilliseconds`:

```
var stopWatch = new Stopwatch();
stopWatch.Start();
// …
var milliseconds = stopWatch.ElapsedMilliseconds;

```

For the game loop we don't need to create an `Stopwatch` every frame. You can compute delta each loop like this:

```
var now = stopWatch.ElapsedMilliseconds;
var delta = now - milliseconds;
milliseconds = now;

```

`Stopwatch` will use high resolution timers if available. Otherwise, it falls back to system time.

---

## Processing

In processing you can use the `millis` function, which as the name suggest gives you milliseconds, from application start in this case.

Example:

```
int start = millis();
// …
int elapsed = millis() - start;

```

`millis` is also available in the ports of processing for **Python** (`millis`) and **Javascript** (`millis`).

---

## Ruby

You want `Process.clock_gettime`.

Example:

```
starting = Process.clock_gettime(Process::CLOCK_MONOTONIC)
# …
ending = Process.clock_gettime(Process::CLOCK_MONOTONIC)
elapsed = end - start

```

**Note**: If you want to measure the time code takes to run, use `Benchmark`.

---

## Swift

A in Objective-C/C on OSX, we will use `mach_continuous_time`:

```
var info = mach_timebase_info()
mach_timebase_info(&info)

let start = mach_absolute_time()
// …
let end = mach_absolute_time()
let elapsed_nanoseconds = (end - start) * UInt64(info.numer) / UInt64(info.denom)

```

**Note**: `mach_timebase_info` can fail. It should return `KERN_SUCCESS`, otherwise, you would have to fall back to system time.

---

## GDScript

We have a couple methods that returns monotonic time in Godot:

* `OS.get_ticks_msec` returns an `int` that represents milliseconds since the start of the engine (divide by `1000.0` to get seconds).
* `OS.get_ticks_usec` returns an `int` that represents microseconds since the start of the engine (divide by `1000000.0` to get seconds).

These methods are thread-safe.

*Although those are the units, be aware that the actual resolution depends on the platform.*

So we can get elapsed time like this:

```
var start_microseconds := OS.get_ticks_usec();
// …
var elapsed_microseconds := OS.get_ticks_usec() - startTime;

```

---

*This is a community wiki. Feel free to edit it to add or fix what is in here.*
> 5 votes

---
Tags: timestep
---


# Question
Title: How to use styles in Monogame.Extended.GUI?
So i was looking at the Monogame.Extended.GUI Project and used this instructions to set it up in a .net Core Project. So far everythings works fine. I followed the example of the demo and created a button like this

```
var button = new Button();
button.Content = "Button1";
button.BackgroundColor = Color.Transparent;

var demoScreen = new Screen
{
   Content = new StackPanel
   {
        Orientation = Orientation.Vertical,
        VerticalAlignment = VerticalAlignment.Centre,
        HorizontalAlignment = HorizontalAlignment.Centre,
        Items = { button }
   }
};

```

Now i want to give this Button a style, for example disable any mouse interactions like hover or mouse presses. The button has a HoverStyle and a PressedStyle property but i don't know how to use it.

```
   button.Hoverstyle = ???

```

# Answer
> 1 votes
Control styles are designed to be loaded from a `Skin` but you can also create them in code a bit like populating a dictionary.

```
new ControlStyle(typeof(Control)) {
    {nameof(Control.BackgroundColor), new Color(51, 51, 55)},
    {nameof(Control.BorderColor), new Color(67, 67, 70)},
    {nameof(Control.BorderThickness), 1},
    {nameof(Control.TextColor), new Color(241, 241, 241)},
    {nameof(Control.Padding), new Thickness(5)},
    {nameof(Control.DisabledStyle), new ControlStyle(typeof(Control)) {
            { nameof(Control.TextColor), new Color(78,78,80) }
        }
    }
}

```

An example of this can be found in the default skin implementation.

---
Tags: monogame, gui, monogame-extended
---


# Question
Title: How can I take screenshots with two cameras simultaneously in Unity?
I am trying to capture different parts of a scene created in Unity. I have two cameras capturing different parts of the scene. Now, I need to take screenshots using these two cameras simultaneously. Right now, every time take a screenshot, it only captures scene from one camera. Thank you!

# Answer
> 2 votes
A screenshot is done at the hardware level. It only knows what is visible on your hardware screen. It is not camera dependent.

What you are looking for is the camera rendering. Unity documentation provides us with a nice code snippet of how to do this:

```
using UnityEngine;

public class Example : MonoBehaviour
{
    // Take a "screenshot" of a camera's Render Texture.
    Texture2D RTImage(Camera camera)
    {
        // The Render Texture in RenderTexture.active is the one
        // that will be read by ReadPixels.
        var currentRT = RenderTexture.active;
        RenderTexture.active = camera.targetTexture;

        // Render the camera's view.
        camera.Render();

        // Make a new texture and read the active Render Texture into it.
        Texture2D image = new Texture2D(camera.targetTexture.width, camera.targetTexture.height);
        image.ReadPixels(new Rect(0, 0, camera.targetTexture.width, camera.targetTexture.height), 0, 0);
        image.Apply();

        // Replace the original active Render Texture.
        RenderTexture.active = currentRT;
        return image;
    }
}

```

---
Tags: unity, camera, scene
---


# Question
Title: Vectorial clothes / hair cuts that adapt on any character size, how is it done?
Rimworld characters are simple but very nice to watch. They have different sizes, hair cuts, clothes... And everything seems to adapt to everyone. How does that work technically ?

For example, any vest will adapt to every characters sizes. I highly doubt that the artists designed every vests for every body shape as it would be a tremendous amount of work.

I think they use vectors, and somehow get it to work. But how ?

See Veli & Baldwin or Tau & Kish below:

Or Flebe and maria below, they both wear a lightleather parka.

# Answer
> 2 votes
> I highly doubt that the artists designed every vests for every body shape as it would be a tremendous amount of work

I am pretty sure that this is exactly what they did. There aren't actually that many body shapes in the game. It's not much work because the torsos of the characters in Rimworld have no animation at all and the graphic style is very simplistic. You just need to create three frames per item and body shape: front, back and side (left and right can be mirrored).

Different materials with the same clothes cut and different skin tones for the same body can be created by recoloring the sprites at runtime.

The hair is another recolored sprite which is drawn on top of the character at runtime.

---
Tags: graphics, vector, graphics-design
---


# Question
Title: How can I make a computer opponent for my board game?
I am trying to create a game, not exactly checkers, but the level of its interactivity is on par with checkers as opposed to something more complex (I think) like chess.

Anyway, according to my analysis, the UI, gameplay, player turns, time constraints, rewards are very easy to implement.

What I find hard is the actual CPU logic.

I'm looking at checkers as an example because I used to play checkers on my PC and Nokia long before sophisticated modern AI became a thing. Are there techniques used in old checkers games that I could use to calculate which of its moves is the **most advantageous** for it to win the game?

I would implement a logic on my own but I need a special algorithm to compute every possible move, and this will def take me a decade to implement.

I am sure there is a smarter and quicker way but I have no idea.

# Answer
> 3 votes
You might be able to apply the minmax algorithm here. It can be applied to any turn-based game without information hiding, no randomness and a small number of possible moves each turn. The only thing you have to adapt to each game is the rating function.

First, you need a rating function. A rating-function analyzes the playing field, rates which player currently appears to have a better chance of winning, and outputs it as a positive (computer has an advantage) or negative (player has an advantage) number.

You could calculate the rating by simply checking material advantage: Who has more pieces on the board? A more advanced rating function might also check how the pieces are positioned. You could, for example, give a higher score to pieces which have many ways to move and few ways in which they can be attacked. You could also try to quantify progress to a strategical goal. In chess, that might be things like pawns being closer to promotion or control of the center of the board.

Writing a rating function which accurately judges the game situation is the part which requires the deepest understanding of the mechanics of your particular game. You might have to do a lot of playtesting.

Then you use this function to calculate the rating of every currently possible AI move followed by every possible player response to that move. Then pick the AI move where the enemy response with the worst rating (from the PoV of the AI) is still rated higher than the worst-rated response of every other AI move.

A cheap way to make the AI stronger is to not just explore one round in the future but even more rounds. But keep in mind that the computation time will increase exponential. A much more efficient and elegant way, however, is usually to improve your rating function so the AI can make better strategic decisions. When the game has a large number of possible moves each turn, the performance can be enhanced through alpha-beta pruning (not following obviously bad tree branches).

I am looking forward to some challenging matches against the AI of your game.

# Answer
> 0 votes
They used a rule based ai. The difference between regular programming and neural networks is the following.

In regular programming the Programmers get data and write rules to generate output.

In Neural networks the programmers get data and a set of expected outputs, write models and try to generate rules by training the models with random weights and variations.

For all digital games the rules are known beforehand and can be programmed, otherwise the game would never really end, because the rule to win or lose would be undefined.

Basic ai in modern games involves finite state machines, fuzzy logic, path finding, recursive calculation of many rounds beforehand to approximate the best success chance or strongest move before making a move (chess and round based games), handwritten ai often is cheating to provide the illusion of intelligence or challenge (halo 1)

I recommend to read the book "game ai programming by example".

---
Tags: algorithm, ai, turn-based, board-game
---


# Question
Title: Rendering multiple textures on same image for terrain with index buffers (LWJGL 3)
I have started with LWJGL3 and trying to built game engine. I'm stuck on generating terrains and this is my second big problem and I'm exhausted so I need some advice on how to solve my problem.

What I want to achieve : I want to have all textures in one place and to have some kind of texture map that I will use to render specific texture at that place.

example: textures

map

but result is

Only thing that I think is problem is because I use same points (index buffers)

So instead of 8 points, I have 6. Is it possible that then texture gets all messed up?

Should I use all points, even if they are at same or almost the same location? But then I would have a lot more vertices than actually need it.

# Answer
Use atleast 4 unique vertices per quad and dont use "shared vertices" between quads.

In your case it looks like the vertices are not shared but the uv coordinates dont match with the vertices due to wrong indexing. shared vertices can be spotted along the edges to the next quad, because interpolation would occur between shared edges, e.g. going from one texture into the other. its called vertex blending, in your case it doesnt look like vertex blending.

Each vertex (indexed vertex) must have a uv coordinate that matches the corners of your texture inside the big texture atlas. You are asking to implement a texture atlas based terrain with hard edges and without vertex blending. Please read about uv mapping, vertex coloring, vertex blending, texture atlas. it really helps to know the techniques in detail.

Thats how you can solve your problem:

1. Generate a big image that contains all your little snippets for the terrain with atleast 2 pixels space between every texture island or sprite. The image must be power of two. 256x256, 512x512, 1024x1024, etc. is power of two. Its more efficient and some gpus have limitations with non power of two textures.
2. draw your terrain on a sheet of paper by drawing all triangles independently and assigning a uv coordinate for every triangle. That sheet is your reference of expected output and you can use it for debugging (its because you need to match uv coordinates for every quad / triangle pair)
3. Dont use "shared vertices" between quads if you want hard looking edges between quad tile geometry and textures to get a classic 2d look. it means that every quad is independent and consists of its own unique 4 vertices, normally a quad is 6 vertices because you actually draw 2 triangles, but you can get away with "sharing" vertices inside the quad by using the center 2 vertices twice inside index buffer but not outside with the next quad!

if you use indexing to save some vertices you have to use DrawIndexed method and not regular draw! You can read about the difference when looking for vertex input layout, jagged vertex buffers, etc.
> 0 votes

---
Tags: opengl, java, textures, lwjgl3, multitexturing
---


title: How Can I Load Ads Particular Level?

text:
# Question
Title: How Can I Load Ads Particular Level?
How Can I Apply Ads Different Level?? I Create A 40 Level,

Ex:

* Level1 complete then load ads Interstitial
* Level2 complete then load ads Interstitial
* Level3 complete then load ads Rewarded
* Level4 complete then load ads Rewarded
* Level5 complete then load ads Interstitial
* Level6 complete then load ads Interstital

follow this same pattern in further levels(40)

Code:

```
 public string currentscenename;

 public string nextscenename;

 public void Next()        //code for next level
  {
        int num = PlayerPrefs.GetInt("Level", 0);
        Debug.Log("Num1:" + num);
        num++;

        PlayerPrefs.SetInt("Level", num);

        if (currentscenename == nextscenename)
        {
            Next();
            Debug.Log("loadlevel");
        }
        else
        {
             if (num % 4 == 3 || num % 4 == 0)         // it is working absolutely fine
            {
                //DebugPanel.Log("num1", "num2" + num % 4);

                if (rewardBasedVideo.IsLoaded())
                {
                     rewardBasedVideo.Show();   //this line generate reward ads
                    //DebugPanel.Log("rewarded", "rewardedads");
                    //DebugPanel.Log("inside ads" , "inside ads function");
                    Debug.Log("rewarded 1");
                }
            }
            if(num % 4 == 2 || num % 4 == 1)                                                                                //1 and 2
            {
                myclass.CallAds.Instance.AdsRequest();    //this line generate interstitial ads
                DebugPanel.Log("num" , "num" + num % 4);
                Debug.Log("interstitial 2");
            }
            SceneManager.LoadScene(nextscenename);
        }
  }

**Maths:**     problem is here my condition will not be run when coming Level5 and Level10,Level15,Level20,Level25,Level30,Level35,Level40
5 mod 4 =  1
10 mod 4 = 2

Problem is when coming Level5 and Level10 then not showning ads????plz help

```

I m Using Google AdmobAds: https://developers.google.com/admob/unity/start

Referance:

# Answer
You can use `OnLevelWasLoaded(int level)` but will be depreciated sometime so the docs say to subscribe to the SceneManagers sceneLoaded

```
using UnityEngine.SceneManagement;

public class YourAdScript: MonoBehaviour
{
   void Start
   {
     SceneManager.sceneLoaded+= this.OnLevelLoaded;
   }

   void OnLevelLoaded(Scene scene,LoadSceneMode mode)
   {
     //play ad
     if(rewardBasedVideo.IsLoaded())
       {
          rewardBasedVideo.Show();//this line generate rewarded ads
       }
   }
   void OnDisable
   {
      SceneManager.sceneLoaded-= this.OnLevelLoaded;
   }
}

```

note : be sure to unsubscribe in OnDisable().
> 0 votes

---
Tags: unity, mathematics, scene, advertisements, admob
---


title: How to store noise in a GL texture

text:
# Question
Title: How to store noise in a GL texture
I find that my procedural simplex noise in my fragment shader hurts performance, so I thought I would just use a stored noise texture instead.

I would like my noise values to have better than 8 bits precision, preferably 16 bits.

What would be a good format to store this texture in?

According to Khronos, GL\_LUMINANCE16 is deprecated.

Should I use **GL\_R16I** for this? What worries me is that it is listed as not texture filterable. That makes the format not useful for this purpose, I think? The man-page does not explain what the term means, but I gather it means that you are force to do NEAREST filtering.

I am looking for something that would work on both OpenGLES3 mobile hardware and on OpenGL desktop hardware.

# Answer
> 4 votes
The choice of formats for OpenGL ES is very limited, so you have to choose between `GL_R16F` and `GL_R8`. Both formats are available for desktop.

`GL_R16F` is probably enough for your purposes.. or is it? Values won't be normalized and it will require you to generate data on the CPU. The reason behind CPU-only restriction is because `GL_R16F` is not a color-renderable format, so you can't attach it to the framebuffer. But at least it will let you to use filtering.

Personally I think that 8 bits wouldn't be a bad choice, because it is filterable and for simplex noise you don't really need too much precision when in the end results are being interpolated in the shader. And it's an unsigned normalized integer format, meaning you won't have to deal with conversions to utilize full precision. And you can attach it to the framebuffer to use shader for noise computation.

---
Tags: opengl, textures, noise, opengl-es3
---


title: Using delta time for movement

text:
# Question
Title: Using delta time for movement
I'm currently involved in a college assignment where we must create a game with our own game engine. In my game, we have an enemy moving around with paths constructed with a A\* algorithm. Every frame I update his position but this is too dependent on the computer. Can you guys help to figure out how to solve this?

I tried to make him move only in even frames but, again, it's too time dependent and it's not smooth.

# Answer
> 2 votes
If we refer to physics 101 (Motion in a Straight Line: Crash Course Physics #1), we will find that linear motion works as follows:

```
position = initial_position + speed * elapsed_time

```

*Yes, I am assuming no acceleration.*

If we work with delta time from the last frame, then `initial_position` is just the previous position, so we have:

```
position = position + speed * delta

```

`speed` must be in units of distance over time, of course. And `delta` must be in units of time. When you multiply `distance/time` by `time`, you get the `distance` that the object moved.

```
moved_distance = speed * delta
position = position + moved_distance

```

You may need to do a time unit conversion depending of what units you used for `speed` and `delta`. For example, if your `speed` is in seconds, and your `delta` is in milliseconds, you would do this:

```
delta_in_seconds = delta_in_milliseconds / 1000.0
moved_distance = speed * delta_in_seconds
position = position + moved_distance

```

**Note**: If you define `speed` and `position` as a vectors, this continues to work. Which remind me, you should call your "speed vector" `velocity`, and your "moved distance vector" `displacement`.

So, if you have defined the speed at which an object should move, you can use this approach to figure out how much it moves each frame.

As per getting a delta, you did not specify what language or platform you are using. If you are not using an engine that gives you a delta, refer to How to measure time interval (different languages).

# Answer
> 0 votes
**You can do the following:**

* enemySpeed = speed you set for the enemy.
* finalSpeed = speed with the delta\_time
* delta\_time = time between one frame and another
* 33333.33333 = interval of time between one frame and another based on game with 30fps

This last value you can set based on the amount of fps you are making your game. It is only divide 1000000 by amount of fps.

**Example with a game made based on 30 fps:**

1000000 / 30 = 33333.33333...

**Formule to set the speed in your game:**

finalSpeed = enemySpeed * (delta\_time / 33333.33333)

**If by chance the pc of the person playing your game is bad and run at 20 fps. The following will happen:**

finalSpeed = enemySpeed * (50000 / 33333.33333)

finalSpeed = enemySpeed * (1.5)

* Assuming the speed you set for the enemy is 10.

finalSpeed = 10 * 1.5

finalSpeed = 15

Notice that there is a compensation, so even on a bad computer, the enemy will walk the same amount.

The opposite will happen if the person has a very good computer that causes the game to run with more fps.

I used my GameMaker knowledge as a reference.

---

**Complementing:**

15 * 20 (fps) = 300 units traveled

10 * 30 (fps) = 300 units traveled

---
Tags: movement, path
---


# Question
Title: How to prevent enemies from oscillating left and right during chase?
I have a grounded enemy with a simple chase state. When in this state, the enemy moves with constant vel.x toward the player.

If my player jumps directly above the enemy however, the enemy will quickly flip directions back and forth a few times, since each time the vel.x is updated it flips sign. If the player is on a ladder above the enemy, the enemy will just oscillate back and forth indefinitely. Very ugly.

My enemy does have an engaged state where he pauses and then attacks, but my player has a high jump and so can maintain a far enough distance to avoid triggering the enemy to enter this state.

**I am wondering what design choices I can make to prevent this ugly oscillation back and forth during chase.**

# Answer
> 2 votes
While your enemy is in their "Chase" state, you can apply a very simple fix.

```
if (abs(enemy.x - player.x) >= enemy.step_length)
{
    // The enemy is at least 1 step away from the player
    if (enemy.x > player.x) enemy.x -= enemy.step_length
    else if (enemy.x < player.x ) enemy.x += enemy.step_length
}
else
    // The enemy is close enough that the next step will overshoot

```

---
Tags: 2d, ai
---


# Question
Title: Fastest way to look up an entity with a set of components?
I'm currently trying to implement an ECS system, but I've sort of ran into a problem trying to fetch all of my entities that have a specific set of components. I currently have a Dictionary that maps a component name to a list of Guids (entities), so I have no problem fetching a list of entities if I were to query for just one component. But if I were to query entities for more than one component (e.g. all entities that have Render and Transform component), I run into a problem where it's no longer a constant time lookup.

I could probably loop through the entities to see if they contain that set of component names (they are stored in a dictionary that maps Guid to a list of strings), but I was thinking that there could be a faster way of doing this?

# Answer
> 2 votes
---

## Update

I have wrote Theraot.ECS inspired by this answer. It allows you to use `Guid`, `int` or whatever for the entities. It will allow you specify how sets of component kinds are handled. Two implementation provided: one uses a binary flag array, the other is based on hash sets.

Some lessons learned:

* `QueryCheck` (see original answer) should return one of three cases: add, remove, nothing to do. I created an enum for this.
* `BitArray`, not very good for this. I rolled my own `FlagArray` type.
* With the design proposed in this answer getting the entities from a query yields a view, not a snaptshot. It was very easy to make it a custom type that also provide events among other things.

I decided to merge creating the query and getting the entities for the query. This means that the call can only expensive the first time (if there are already entities). Subsequent calls are `O(1)`.

I also decided to change the phrase "component type" to "component kind" to avoid confusion with actual `System.Type` types.

The project is free and open source software, feel free to study it, use it, whatever. MIT license.

---

## Original Answer

I want to suggest is to maintain a set for entities for each query.

When a system starts, it will report the queries it needs (I assume it is usually a single one, yet, multiple could be supported).

The engine will create (and populate) new sets for those queries. By doing this, you would only need to go over every entity to populate the dictionary when a system is created. By creating all necesary systems before the entities, you do not need to populate the sets on creation at all.

Instead, when a component is attached to an entity, you will add it to the sets according to the queries. Alright, that is not trivial... we need to figure out what queries could change their result depending on the attached component. Similarly when removing.

So, if we express a query as a list of components that must be present, we can also create a dictionary that give you queries based on components. In fact, it is relatively easy to extend to have negative queries (as in "the entity must not have this component").

---

The process when a component is attached or removed is as follows:

1. Use the component to get the list of active queries that could apply
2. For each query:

2.1 See if the entity passes or not.

2.2 If it passes: Add it to the set for the query (if it was not already there)

2.3 If it does not pass: Remove it from the set for the query (if it was already there)

Then the system can simply get the set for the query it wants. Of course, the query would not exist if it was not created first.

We need something like the following:

```
Dictionary<ComponentType, HashSet<Query>> QueriesByComponentType;
Dictionary<Query, HashSet<Entity>> EntitiesByQuery;
Dictionary<Entity, HashSet<Component>> ComponentsByEntity;

```

Of course, you can use GUID for your entities, and I do not know if you want ConcurrentDictionary, and you would need a good hash for the HashSet, in fact a good hash for the Components is a good idea.

What follows is the same idea translated to code (some assumptions where made).

When the component is added or removed:

```
// O(n) where n = number of affected queries
var component = component_begin_added_or_removed;
var componentType = ComponentTypeManager.GetFrom(component_begin_added_or_removed);
var entity = this_entity;
// The code below should probably be extracted to another method:
// Try to update ComponentsByEntity, if no update you can return
if (QueriesByComponentType.TryGetValue(componentType, out var queries))
{
    foreach (var query in queries)
    {
        var set = EntitiesByQuery[query];
        if (query.CheckQuery(entity)) // Uses ComponentsByEntity
        {
            set.Add(entity);
        }
        else
        {
            set.Remove(entity);
        }
    }
}

```

**Note**: the remove case can be optimized futher if we know that all queries are positive (they only ask for a component to be present, but never for a component to not be present), which is the way entity-component-system is meant to be. If that is the case, you separete this code in a version for adding and another for removing, and the removing case does not need `CheckQuery`. You might also be interested in creating a version that takes multiple components to add at once (computing the union of the queries sets).

When the system is created:

```
// O(n) where n = number of components
var componentTypes = new []{componentTypeA, componentTypeB /*,...*/};
var query = QueryManager.GetFrom(componentTypes);
// The code below should probably be extracted to another method:
if (EntitiesByQuery.TryAdd(query, new HashSet<Entity>()))
{
    foreach (var componentType in componentTypes)
    {
        if (!QueriesByComponentType.TryGetValue(componentType, out var set))
        {
            set = new HashSet<Entity>();
            QueriesByComponentType.TryAdd(component, set);
        }
        set.Add(query);
    }
}

```

When the system wants to query:

```
// O(1)
var entities = EntitiesByQuery[query];

```

I said twice in comments that code should be extracted to another method. That is because that code would be the same for all entities and systems. In fact, I think it is wise to not expose the dictionaries directly. I suggest a Façade.

---

How many components do you have? There is a change you can represet the list of components that make up a query as a bit array. Which would also be useful to represent the list of components an entity has... and then, checking is bit wise and.

In fact `ComponentType` does not need to be a class, nor `Query`. And you already know `Entity` does not have to be a class either. I wrote it that way to not get into the specifics of how they are represented. In fact, you might as well take advantage of using alias directive plus extension methods.

---

**Addendum on the order of component types**

This can work even without having a strict order for the components types of a query (and yes, even for negative queries).

---

With that said, if you want to use a bit array to represent a set of component types, the component types would need consecutive numeric codes that also act as the indexes for the bits in the bit array.

You could use an enum and flags, such that only the bit that represents the component type is set and the rest are not set. That makes doing that bit wise and very easy, and give give you the best performance. However, it would also limit the number of possible component types to 64, since the base type would be at best a `ulong` which has 64 bits.

You can carry on with that idea beyond the 64 component types by using a `BitArray` instead.

If you start with the enum and then for whatever reason you need a large number of component types, you would have to change that. Please notice I consider the bit array an optimization. You can still do the same with a set of component types and iterating.

In fact the advice would be the opposite: \- Start with sets, but keep them isolated from the rest of the code. \- If they are affecting your performance, and you have already settled on the number of component types for your game, then optimize accordingly.

If you are creating a generic ECS, you could offer different strategies, and let the developer decide. Keep the same façade so most of the code is unaware of the difference, and use dependency injection to pass the strategy the developer wants.

---

**Addendum on the idea of negative component queries**

Sometimes it is useful to have a system that must run on entities that do not have a particular component. For example, you could have the system detect these entities, do some computation on then, and then add the componet so it does not run on it anymore.

How to do it? The idea is go back to the initial algorithm I proposed, before any optimization. Realize it is the same for adding and removing, it has symmetry. We can exploit that symmetry... if you remove a component, perhaps you should add the entity to the set of a query that requires to not have that component. Similarly when adding a component, perhaps you want to remove the entity from the set of a query that do not wants that component.

We, of course, have the problem of how to represent these negative queries. We need a concept of the negation of a component type. That way you can have queries that say "must have componentA and no componentB".

So a query can contain a component type, its negative or neither (a query with a component type and its negative should be rejected, as it makes no sense for an entity to have a component and not have it). And yes, for the bit array, that would mean two bits per component. Which for the enum approach means you could only have half the ammount of possible component types. Again, this is a trade-off.

---

**Addendum on disjuntion queries**

Disjuntions are another kind of query that is missing (an "Any" query instead of an "All" query).

You got to treat them separately (have queries marked as disjuntion). The base algorithm continues to be the same (when you add or remove, you check the queries that has the component type that is being added or removed and check if the query is satisfied and add or remove the entity on the set of the query accordingly), but the optimizations are different.

---

**Addendum on the idea of entities with multiple of the same component type**

It usually does not make sense, and in the cases it does, you probably want a hierarchy of components, such that an aggregation of components of a given type can also act as a component.

However if you want to allow entities with multiple components of the same type, then `ComponentsByEntity` would not use `HashSet`, but some sort of list... which also makes the system code more complex, because it has to deal with a variable number of components.

Then, in that case, being able to use a sorted list would allow a faster algorithm for checking a query than a regular list. If the list of components is large, a binary search will be good, otherwise, simply iterating in order will allow to discard soon. How large? Test.

By allowing an entity to have multiple of the same component type, checking if it satiesfies a query is slower. Alternatively, you could have another level of dictionaries. Which means more indirection, which means more overhead. As you can see, this idea comes with a trade-off, as usual there is price for versatility.

# Answer
> 5 votes
The way ECS implementations like the new one in Unity work is to use the concept of *Archetypes*.

An Archetype is the description of the components in a particular entity. Given sets of components, like `{position,rotation,mesh}` and `{position,rotation,particles}`, you have two different Archetypes. Both of them contain `{position,rotation}`, but the first Archetype also contains `mesh` while the second one instead additionally contains `particles`.

Every entity belongs to one and exactly one Archetypes. If components are added or removes, the entity then belongs to a new Archetype. By itself, this should make it easy to see how to find entities matching a query. Iterate through the Archetypes and find all matching ones. Then just iterate the entities in each matching Archetype. This is considerably faster than searching all entities because many entities will have the same archetype (e.g., every single static prop in your game world will be in `{position,rotation,mesh}` or some such). Some entities will be "unique" but those will be the exceptional case in any large populated game scene.

Within the Archetype, you keep the components in nice linear arrays. For example, for the `{position,rotation,mesh}` Archetype, its Chunk "layout" might look like:

```
| entity   | entity   | ... | entity   |
| position | position | ... | position |
| rotation | rotation | ... | rotation |
| mesh     | mesh     | ... | mesh     |

```

The advantage to this is that now you can correlate components together very efficiently. When processing all the entities in an Archetype, just look at the arrays, and you know that for a given index all the components in each array corresponds to the same entity.

Since each Archetype has its own arrays, each archetype will have an entity at index 0, and will its own array of `position` components at index 0. Your processing code then looks something like (in simplified code):

```
foreach archetype:
  if archetype matches query:
    for index in 0..archetype.entities:
      draw(archetype.positions[index], archetype.rotations[index])

```

With some generics you can factor all that away into a utility and your C# user code will probably look more like:

```
world.Query((int count, Position[] pos, Rotation[] rot) => {
  Parallel.For(0, count, () => {
    renderer.Draw(pos[i], rot[i]);
  }
});

```

That not only makes it very easy to correlate components, it also means the data is laid out nicely in the CPU cache which reduces cache misses and pipeline stalls. As a bonus, notice the use of `Parallel.For` in the above - if your actual update logic can use it, this approach makes multi-threading updates almost trivial. The other kinds of approaches out there using sets makes this incredibly difficult to do efficiently.

Note that Unity ECS (and other Archetype-based ECS) typically additionally have the concept of a Chunk, which is essentially the idea that the components in an Archetype are split up into fixed-sized blocks of memory (which fit a variable-size number of entities, based on the sizes of the components in that Archetype). That helps avoid memory fragmentation/bloat and makes multi-threading a bit easier in some cases, but isn't necessary for a simple implementation.

The damning part of an Archetype approach is that modifying entities is much harder. When a component is added to an entity, the entity changes Archetypes. This necessarily means that all the existing components must be copied from the storage of the original Archetype into the storage of the new Archetype. Further, these modifications can't be performed while the Archetypes' arrays are being iterated, so changes incurred during a world query have to be queued up and applied later. That's not all that tricky to write, and it performs better than you might think (so long as you perform changes in bulk), but it is extra implementation.

That said, of the handful of games I'm aware of that using actual shipping ECS architecture (and not some other or hybrid component model), most of them are using the Archetype approach. Minecraft (Bedrock/C++ edition) is the only exception as it uses EnTT, a C++ sparse-set ECS framework.

Which, if you're not keen on the Archetype approach, EnTT is probably a good place to look for implementation strategies (though again, it's C++, not C#). As mentioned, it uses the concept of sparse sets so that it *mostly* just iterates lists of components and uses basic set operation logic to find matches. Unlike the Archetype approach, it is neither data-oriented (doesn't guarantee contiguous/linear cache access patterns) nor especially multi-thread friendly (because underlying sets can be mutated) but it is otherwise relatively quick compared to the vast majority of other open-source ECS frameworks out there (and it's good enough for Minecraft, in any case).

---
Tags: c#, entity-component-system
---


# Question
Title: Card flip animation in a prefab. How to flip with local position?
I'm making a simple card game, with some cards laying on the table. I want to flip the card when it's clicked, so I thought I'd use an animation to do it (lift card up in the air, rotate it and lower it back down). It works as I want with one card, but when I save it as a prefab and instantiate another one next to it, the card (obviously) moves to the same position as the prefab (as the animation stores global position I guess).

Is there any way to make animations in local space, or is there any other way I should do the flip?

# Answer
You can create an animation at an object that is child of an any other game object. When you create an animation at that child object, transform values of that animation will be created according to parent object. In that way when you want to add the same animation to other objects that are child of an object, the animation works with transform values that are set to that new parent object.

To remove confusion, I can say it like that. You want your animation to change the local transform values of a child object not its world transform values. Changing transform values of parent objects provide the change of the position of the target object and its animation.
> 2 votes

---
Tags: unity
---


# Question
Title: Getting center cell of Unity3D's isometric Tilemap, the resulting position offsetted by a distance?
I am new to Unity3d's Tilemap system and found a problem I couldn't figure out at the time of writing this question. What I want to do is to create a bunch of GameObject overlaid in each of the tile's supposed location in the Tilemap grid. The GameObjects created are supposed to represent nodes for pathfinding purpose.

The problem shows when I get the position of the tile using Tilemap.GetCellCenterWorld(), the returned Vector3 is displaced by some value so it did not exactly represent the center position of the tile's cell.

Below is the screenshot of the problem: shown in the editor:

The instantiated gameobject have gizmos drawn on its position to ease visual debugging of the process, hence the array of small sphere mimicking the shape of the placed tiles.

The state of the gameobject hierarchy when the problem happened:

The process of instantiating the node is done in the Awake lifecycle method of PathNodeGenerator script attached as a component to PathfindingTile GameObject shown in the Hierarchy.

Below are the code written in PathNodeGenerator.cs

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

/// <summary>
/// PathNodeGenerator is responsible for generating nodes used
/// for pathfinding algorithm in the game.
/// </summary>
public class PathNodeGenerator : MonoBehaviour
{
    /**
     * containerGrid is the Grid component
     * that holds the tilemaps in the scene
     */
    public Grid containerGrid;
    public string nameOfTheBaseTilemap = "Floor";

    [System.Serializable]
    public class NodePrefabEntry {
        /**
         * Name refers to the tilemap name the prefab
         * supposed to represent in the code
         */
        public string name;
        public GameObject prefab;
    };

    public List<NodePrefabEntry> namedNodePrefabs = new List<NodePrefabEntry>();

    Dictionary<string, GameObject> environmentNodePrefabs = new Dictionary<string, GameObject>();
    Dictionary<string, Tilemap> environmentTilemaps = new Dictionary<string, Tilemap>();

    public List<GameObject> unsortedNodes;
    public GameObject[,] nodes;

    /// <summary>
    /// Populate data in Awake
    /// </summary>
    void Awake()
    {
        this.PopulatePrefabDictionary();
        this.PopulateTilemapDictionary();

        Tilemap baseTilemap;
        if (!this.environmentTilemaps.TryGetValue(
            this.nameOfTheBaseTilemap.ToLower(), out baseTilemap))
        {
            //TODO: handle error when the tilemap does not exist;
            Debug.Log("Does not exist yet in awake!");
        }
        this.transform.position = containerGrid.transform.position;
        this.GenerateNodes();
    }

    /// <summary>
    /// PopulatePrefabDictionary() populates the dictionary that holds name-prefab pair
    /// from the workaround list
    /// </summary>
    void PopulatePrefabDictionary()
    {
        for(int i=0; i < this.namedNodePrefabs.Count; i++)
        {
            this.environmentNodePrefabs.Add(
                this.namedNodePrefabs[i].name.ToLower(),
                this.namedNodePrefabs[i].prefab);
        }
        Debug.Log(String.Format("PopulatePrefabDictionary result: {0}",this.environmentNodePrefabs.Count));
    }

    /// <summary>
    /// PopulateTilemapDictionary() populates the tilemap dictionary
    /// in this object by iterating through the container grid's
    /// children an getting the tilemap component and its name as
    /// the value and key pair respectively in the dictionary.
    /// </summary>
    void PopulateTilemapDictionary()
    {
        Component[] tilemaps = this.containerGrid.GetComponentsInChildren<Tilemap>();
        foreach(Tilemap tilemap in tilemaps)
        {
            string name = tilemap.gameObject.name.ToLower();
            this.environmentTilemaps.Add(name, tilemap);
        }
        Debug.Log(String.Format("PopulateTilemapDictionary result: {0}", this.environmentTilemaps.Count));
    }

    /// <summary>
    /// Generate pathfinding nodes and interactive nodes from the
    /// tilemaps registered on this object.
    /// </summary>
    void GenerateNodes()
    {
        Tilemap baseTilemap;
        if(!this.environmentTilemaps.TryGetValue(
            this.nameOfTheBaseTilemap.ToLower(),out baseTilemap))
        {
            //TODO: handle error when the tilemap does not exist;
            Debug.Log(string.Format("{0} tilemap does not exist yet!",this.nameOfTheBaseTilemap.ToLower()));
        }

        //Prepare the tiles in Tilemap grid to be iterated through
        baseTilemap.CompressBounds();
        BoundsInt bounds = baseTilemap.cellBounds;
        TileBase[] allTiles = baseTilemap.GetTilesBlock(bounds);

        //Loop through the tiles on the Tilemap grid and
        //create PathNode prefab object on the location
        //of each available tiles
        for (int x = 0; x < bounds.size.x; x++)
        {
            for(int y = 0; y < bounds.size.y; y++)
            {
                TileBase tile = allTiles[x + y * bounds.size.x];
                if (tile != null)
                {
                    GameObject nodePrefab;
                    if (!this.environmentNodePrefabs.TryGetValue(this.nameOfTheBaseTilemap.ToLower(), out nodePrefab))
                    {
                        //TODO: handle error when the default node prefab does not exist
                        Debug.Log(string.Format("{0} prefab does not exist!",this.nameOfTheBaseTilemap.ToLower()));
                    }
                    Vector3 pos = baseTilemap.GetCellCenterWorld(new Vector3Int(x,y,0));
                    Debug.Log(string.Format("Node_{0}x{1}: ({2},{3},{4})",x,y,pos.x,pos.y,pos.z));
                    GameObject currentNode = Instantiate(nodePrefab, this.transform);
                    currentNode.name = string.Format("Node_{0}x{1}", x, y);
                    currentNode.transform.position = pos;
                }
            }
        }
    }
}

```

This behaviour persist in Unity3D 2019.2.0b7 , 2019.1.3f1, & 2018.3.11f1.

If anyone know what causing the displacement of the returned position or anything related to it, your inputs are very much appreciated. Thanks!

# Answer
After a while a found an answer. So the Tilemap instances have its own origin position in their parent grid object which can be accessed with `<Tilemap instance>.origin`. The origin position is equal to its minimum bound point after you compress the tilemap's cell bound.

So you can get the exact center world position of each tile in a tilemap by iterating each cell position got from the origin point coordinate to the origin point offsetted by the size of the cellBounds, and calling `<Tilemap instance>.getCellCenterWorld(cell position)`.
> 1 votes

---
Tags: unity, tilemap
---


# Question
Title: What is the geometrical interpretation of Input.GetAxis("Mouse X")?
According to the documentation, `Input.GetAxis("Mouse X")` produces a range of values from `-1` to `1`. However it will produce another range if it is setup to be delta mouse movement.

> Returns the value of the virtual axis identified by axisName.
>
> The value will be in the range -1...1 for keyboard and joystick input. If the axis is setup to be delta mouse movement, the mouse delta is multiplied by the axis sensitivity and the range is not -1...1.

# Question

I don't understand what the value means geometrically. Is it a displacement between two points each in consecutive frame updates? If so what is its unit? Pixels, points, centimeters, etc?

# Answer
This is something you can determine empirically. Drop in a script like this:

```
public class MouseDeltaCheck : MonoBehaviour
{
    public Vector2 screenPos;
    public Vector2 positionDelta;
    public Vector2 inputDelta;
    public Vector2 ratio;

    void Update() {
        Vector2 newScreenPos = Input.mousePosition;

        positionDelta = newScreenPos - screenPos;

        inputDelta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));

        if(inputDelta.x != 0f)
            ratio.x = positionDelta.x / inputDelta.x;
        if (inputDelta.y != 0f)
            ratio.y = positionDelta.y / inputDelta.y;

        screenPos = newScreenPos;
    }
}

```

In my experiments, the mouse delta value is approximately:

```
{Change in Pixel Position} * {Axis Sensitivity} / ({OS Scaling Factor} * 2)

```

Where `{Axis Sensitivity}` is the sensitivity value you've configured for the "Mouse X" and "Mouse Y" axes in the Input Manager, and the `{OS Scaling Factor}` is any scaling being applied outside the game (for instance, in Windows 10 Display Settings, I usually run my Surface with the "Scale and Layout" setting at its recommended value of 150% so text is a readable size on the high-resolution display).

I say "approximately" because there is some variance - likely due to the Unity deltas being summed from several hardware event deltas that might include fractions of a pixel, while the absolute position value is necessarily rounded to a whole pixel coordinate prior to scaling being applied. This variation is small and bounded - even when accumulating deltas over many frames spanning movement all over the screen, I never found the two measures of travel disagreed by more than 1.5 pixels (1.5x being my OS scaling factor at the moment).

I don't know what accounts for the `* 2` multiplier though.
> 1 votes

---
Tags: unity
---


title: What is the unit of time in Unity?

text:
# Question
Title: What is the unit of time in Unity?
In Unity what is the unit that time follows ? (milliseconds, microseconds or seconds?)

# Answer
You can answer this question yourself with a quick trip to the documentation:

Time.time

> The time at the beginning of this frame (Read Only). This is the time **in seconds** since the start of the game.

Time.deltaTime

> The completion time **in seconds** since the last frame (Read Only).
>
> This property provides the time between the current and previous frame.

etc.

Even without opening your browser, Intellisense shows you this information too:

Note that these are in-game time values that are subject to pausing when the app is suspended, or scaling if you're setting Time.timeScale for things like slow-motion effects. You can also use Time.unscaledTime / Time.unscaledDeltaTime to get the real time elapsed while playing the game, ignoring scaling effects (useful for animating UI at the normal rate even during a slow-mo sequence, for example).
> 3 votes

---
Tags: unity, realtime
---


# Question
Title: How can I add a delay to my enemy spawning in Greenfoot?
How can I add a delay between spawning my enemies in Greenfoot? I'm doing it from a class that is neither a world nor an actor, its made totally by me. I need to it spawn 3 enemies, 3 times, with a 1-second delay between each time. Here's what I've got now.

```
void attack()
{
    long beginTime = System.nanoTime();
    int i = 0;
    while(i < 3)
    {
        if ((System.nanoTime()-beginTime)/1000000000>1f)
        {
            for (int j = 0; j < 3; j++)
            {
                world.spawnEnemy();
            }
            i++;
        beginTime = System.nanoTime();
        }
    }
}

```

It's based off of this answer to this question. However, it does not at all give me the desired results. Instead, it entirely pauses everything else in the game (all of the actors, probably the world too, but I'm not sure) until the makeshift timer ends 1 second into it, and then spawns all 3 waves (all 9 enemies) at once.

# Answer
Let's walk through this code, pretending that `nanoTime = 0` at the start for simplicity.

1. We initialize `beginTime = 0` and `i = 0`
2. We check the `while` loop's condition, and `i` is indeed less than 3, so we enter the loop.
3. We check if the current time is 1 second later than begin time yet, but of course it isn't! We've barely executed two instructions since begin time. So we skip over the loop body.
4. We hit the end of the `while` loop, and check the condition again. `i` is still less than 3, so we re-enter the loop and go back to step 3.

* We keep doing this BILLIONS of times, because we do so little work inside the loop each time, `nanoTime` isn't much bigger each time we loop around.

    This is called a "busy-wait" or "spinning" - the processor is kept busy checking the clock then looping then re-checking the clock, so it's never allowed to exit this loop, return from this function, update the rest of your game state, process player input, or draw a frame. You've effectively stalled your game here.
5. Finally, an eternity of wasted CPU time later, we've managed to burn a second of time and our inner `if` condition finally passes. Huzzah! We enter its body.
6. We spawn 3 enemies.
7. We increment `i` to 1.
8. We set `beginTime` to 1000000100 or so.
9. We hit the end of the `while` loop and check the condition again. Oh no. `i` is *still* less than 3, so we're stil not allowing the CPU to move on yet! Back to step 3 we go, and burn another second doing nothing...

etc.

So, don't put a wait loop inside your game loop. Instead, what you really want to do is call this function periodically, and each time *check* if it's time to spawn a new wave, rather than hold the CPU hostage *until* it's time.

That might look something like this:

```
// Call this at the start of your level.
void SetUpWaves() {
    nextWaveSpawnTime = System.nanoTime() + 1000000000;
    wavesRemaining = 3;
}

// Call this periodically, say once per frame update,
// or at a coarser frequency if you prefer, since it changes state infrequently.
void SpawnWaveIfReady() {
    // Cheap early-out if it's not time to spawn a wave yet.
    if(System.nanoTime < nextWaveSpawnTime)
        return;

    // It is time! Spawn a wave!
    for (int j = 0; j < 3; j++)
    {
         world.spawnEnemy();
    }
    wavesRemaining--;

    // Work out when to spawn the next wave, which might be "never again."
    if(wavesRemaining > 0)
        nextWaveSpawnTime += 1000000000;
    else
        nextWaveSpawnTime = long.MAX_VALUE;
}

```
> 1 votes

---
Tags: java, spawning, greenfoot-engine
---


title: Show/hide soft-keyboard on demand

text:
# Question
Title: Show/hide soft-keyboard on demand
I'm writing simple chat-app using Unity. The problem with Unity's default implementation of soft-keyboard visibility is that it hides itself when i'm clicking outside of keyboard panel. What i want is that keyboard stays always shown until i explicitly tells otherwise.

For a couple of days i tried to find similar questions but none of them helped me. I have very little experience in "native" android development (i.e. Java). So far i managed to create simple native plugin for Unity. I tried to manually open keyboard with this code:

```
imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

```

The result was fine, except the keyboard had InputType set to TYPE\_CLASS\_NUMBER. For my app i needed TYPE\_CLASS\_TEXT. So i tried to research how to set InputType and stumbled on fact that this property can only be changed inside EditText object. As i'm writing my app in Unity, i had no way of finding my InputField's inside native code. So i tried to create EditText inside my native plugin. I followed the logic that if i create custom EditText, place it inside main layout and set visibility to NONE or make background transparent, then i can set focus to that element and be fine:

```
FrameLayout myLayout = activity.findViewById(android.R.id.content);
focusedText = new EditText(context);
focusedText.setFocusable(true);
focusedText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
myLayout.addView(focusedText);
focusedText.setFocusableInTouchMode(true);
focusedText.requestFocus();
focusedText.setBackgroundColor(activity.getResources().getColor(android.R.color.transparent));
imm.showSoftInput(focusedText, InputMethodManager.SHOW_FORCED);

```

The end result was a mess. Soft keyboard behaviour became undesirable. In order for keyboard to show, i first needed to select InputField, then i would see transparent EditText be created in the middle of my layout with all input characters visible. Even if all worked fine, it still looks like a wacky hack.

Does anyone stumbled across similar issues?

# Answer
> 1 votes
Forcing the keyboard to stay open may not be the best method as on some mobiles the keys will take up a good portion of the available screen space. If a user cannot un-focus the board it could lead to a bad experience for them.

With that suggestion out of the way you do not have to write a custom plugin to achieve the behavior you want. You can set up a boolean to store when you are completed with the keyboard(enter key or some other means). That way you can keep it in Focus until you are done by utilizing the scenes EventSystem.

```
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class YourClass : MonoBehaviour

public InputField inputField;
bool completedInput = false;

```

For example you can set the focus using

```
 EventSystem.current.SetSelectedGameObject(inputField.gameObject, null);

```

you can auto open the keyboard if needed with

```
inputField.ActivateInputField();

```

in combination with a completed boolean you could keep the board open by resetting the focus to the input if someone clicked out of the element or the inputfield is unfocused by other means before they are done.

```
 if(!completedInput)
        EventSystem.current.SetSelectedGameObject(inputField.gameObject, null);

```

another way that may prove useful is to check if you are not over a EventSystem object then either null their new selection or something along those lines.

```
if (!EventSystem.current.IsPointerOverGameObject())
    //do something

```

note that you can assign various keyboard layouts in codebehind or in the properties of a input field in the inspector.

```
inputField.contentType = InputField.ContentType.Autocorrected;

```

---
Tags: unity, java, android, keyboard, plugin
---


# Question
Title: Unity Collider2D is causing the game object to disappear upon collision
I have gone through just about everything to try and isolate this bug.

I have isolated it down to the enemy collider, but have not solved the issue.

When my player collides with my enemy, the enemy game object is destroyed and removed from the hierarchy (until reset).

Removing the enemy collider fixes this issue of course. However removing the player collider does not.

Neither the player nor the enemy has collider code written into their scripts, so I can't blame that. I did have an OnEnterCollision2D script added to the enemy game object, but have since removed it in an effort to debug the situation, and it did not do a thing.

There are no other scripts at play - only the relationship between player and enemy colliders.

I'm newish to Unity and coding, but I can't seem to find anything on this issue. Any help is much appreciated!

What. The. Heck.

If you're wanting to read through the scripts, you can here: https://forum.unity.com/threads/oncollisionenter2d-is-destroying-my-game-objects-and-i-cannot-figure-out-why.710837/

# Answer
> 1 votes
So I got some great advice on Reddit from user AverageArmadillo that I wanted to share and solved my issue.

"If you are using VS hit control + shift + F and under the search function change current document to entire solution to search your entire game solution. Look for Destroy.

Something... somewhere is making a call to destroy on collision. Remember that even inactive game objects with colliders can call collision on triggers. So if your player has some form of projectile they fire (I see an arrow in your scripts) if that arrow is not active in the hierarchy but present then it's trigger can still get fired. There is a chance that is happening.

I see it too in my game when bullets disabled still cause damage to enemies. The solution to that if it is the case was to add a check if object is active in hierarchy to the collision actions."

Turns out it was an issue with an old script in my archive folder that was calling a similar function to my new "hurt player" script.

---
Tags: unity, c#, 2d, collision-detection, collider
---


title: Problem making wave animation

text:
# Question
Title: Problem making wave animation
I want to simple wave-like animation using mesh. I thought that it would look like a wave if there would be a point at the middle of the mesh and change z axis of that point, and after this I change points at around of middle point one by one. However, it didn't happen.

What should I do to make a wave-like mesh animation?

**My code:**

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

[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]

public class Gridd : MonoBehaviour
{
    public Mesh mesh;
    public float axisCounter;
    public Vector3[] vertices;
    public int xSize, ySize;
    point nokta;

    int sayac = 0;

    private void Awake ()
    {
        mesh = new Mesh();
        Generate();
    }

    private void Generate ()
    {
        _generate();
    }

    private void OnDrawGizmos ()
    {
        draw();
    }

    void Start()
    {
        nokta = new point(1,1,xSize,ySize,vertices);
    }

    void Update()
    {
        createMesh();
        StartCoroutine(destroy());
    }

    IEnumerator destroy()
    {
        float zAxis = 0;
        while(true)
        {
            while(zAxis>=-axisCounter)
            {
                if(zAxis<=-axisCounter)
                {
                    break;
                }
                zAxis-=0.01f;
                nokta.func(xSize/2,ySize/2,zAxis);

                yield return new WaitForSeconds(0.01f);
            }

            while(zAxis<=axisCounter)
            {
                if(zAxis>=axisCounter)
                {
                    break;
                }
                zAxis+=0.01f;
                nokta.func(xSize/2,ySize/2,zAxis);

                yield return new WaitForSeconds(0.01f);
            }
        }
    }

    /*************************************************************************/

    void _generate()
    {
        mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;
        vertices = new Vector3[(xSize + 1) * (ySize + 1)];
        for (int y = 0; y <= ySize; y++)
        {
            for (int x = 0; x <= xSize; x++)
            {
                vertices[sayac] = new Vector3(x, y);
                sayac++;
            }
        }
        sayac=0;
    }

    void createMesh()
    {
        mesh.vertices = vertices;
        int[] triangles = new int[xSize*xSize*6];
        for(int y=0;y<ySize;y++)
        {
            for(int x=0;x<xSize;x++)
            {
                triangles[sayac] = (xSize+1)*y+x;
                sayac++;
                triangles[sayac] = (xSize+1)*(y+1)+x;
                sayac++;
                triangles[sayac] = (xSize+1)*y+x+1;
                sayac++;
                triangles[sayac] = (xSize+1)*y+x+1;
                sayac++;
                triangles[sayac] = (xSize+1)*(y+1)+x;
                sayac++;
                triangles[sayac] = (xSize+1)*(y+1)+x+1;
                sayac++;
            }
        }
        sayac=0;
        mesh.triangles = triangles;
    }

    void draw()
    {
        if (vertices == null)
        {
            return;
        }
        Gizmos.color = Color.black;
        for (int i = 0; i < vertices.Length; i++)
        {
            Gizmos.DrawSphere(vertices[i], 0.01f);
        }
    }
}

/*****************************************************************************/

public class point
{
    public int x;
    public int y;
    public int xSize,ySize;
    public int[,] _nokta;
    public int[,] dalga;
    int atlayici;
    int kolaynokta;
    int kolaynoktax,kolaynoktay;
    public Vector3[] vertices;
    bool buldumu = false;

    public point(int x,int y,int xSize,int ySize,Vector3[] vertices)
    {
        this.x = x;
        this.y = atlayici*y;
        this.xSize = xSize;
        this.ySize = ySize;
        this.vertices = vertices;
        this.atlayici = xSize+1;
        this._nokta = new int[xSize,ySize];
        this.kolaynokta = (xSize+1)*y+x;
        this.dalga = new int[ySize/2+1,xSize*ySize];
    }

    public void func(int x,int y,float z)
    {
        vertices[pointFinder(x,y)] = new Vector3(x,y,-z/2f);
        subWaves(x,y,z);
    }

    public void subWaves(int x,int y,float z)
    {
        if(!buldumu)
        {
            find(x,y,z);
        }
        int counter = 8;
        for(int a=0;a<ySize/2;a++)
        {
            for(int b=0;b<counter;b++)
            {
                vertices[dalga[a,b]] = new Vector3(vertices[dalga[a,b]].x,vertices[dalga[a,b]].y,_math(a,z));
            }
            counter+=8;
        }
    }

    /*************************************************************************/

    void find(int x,int y,float z)
    {
        int katman = 2;
        int wavex = x;
        int wavey = y;
        int _x=0;
        for(int a=0;a<ySize/2;a++)
        {
            wavex--;
            wavey++;
            int xarray=0;
            int yarray=0;
            for(int c=0;c<katman;c++)
            {
                dalga[a,_x] = pointFinder(wavex+xarray,wavey+yarray);
                xarray++;
                _x++;
            }
            for(int c=0;c<katman;c++)
            {
                dalga[a,_x] = pointFinder(wavex+xarray,wavey+yarray);
                yarray--;
                _x++;
            }
            for(int c=0;c<katman;c++)
            {
                dalga[a,_x] = pointFinder(wavex+xarray,wavey+yarray);
                xarray--;
                _x++;
            }
            for(int c=0;c<katman;c++)
            {
                dalga[a,_x] = pointFinder(wavex+xarray,wavey+yarray);
                yarray++;
                _x++;
            }
            katman+=2;
            _x=0;
        }
        buldumu = true;
    }

    int pointFinder(int x,int y)
    {
        int nokta = (xSize+1)*y+x;
        return nokta;
    }

    float _math(int a,float z)
    {
        z*=-1;
        float deger;
        deger=z/(1.25f+(a+1));
        return deger;
    }
}

```

**Below image (GIF) of result that I achieved:**

# Answer
> 0 votes
maybe instead of coding, you should make an animation and loop it. This could be done in a 3rd party program, like blender, and then exported to unity

# Answer
> 0 votes
I think you might appreciate the answers to your question in the catlikecoding blog. https://catlikecoding.com/unity/tutorials/flow/waves/

i don't know who makes this, but their content is amazing for procedural generation and they have a patreon if you want to give them a hand.

---
Tags: unity, algorithm, game-mechanics, physics-engine
---


# Question
Title: Mesh made in Blender is correct in Unity3D as a rendered mesh, but "empty" as a collider?
I created a simple stair "block" in **Blender**, and **it's rendered correctly**, but when I tick **"Generate Colliders"** and try to use it in a **Mesh Collider**, there is **nothing**.

(Ps.: I need the real mesh as a collider, not just that generated convex one)

Maybe a good clue is that my other objects' generated colliders are smaller than the rendered meshes themselves. Maybe this one is scaled to zero?

After triangulating:

And via Unity's automatic triangulation: (the original, non triangulated blender model)

# Answer
> 3 votes
this is just a guess that I am pulling out. but I see a missing line on the side of your stairs. No line showing up in unity seems like a hint.

you can see triangles 012, 234, and 145 because of the textures on them. but i bet that triangle 124 doesn't exist. despite having zero area it is still a missing triangle. That's important because depending on the algorithms used a missing triangle may cause the collider generation to fail. for instance, without a closed mesh, there may be an issue determining where the inside of the mesh is to determine where the normals of the collider are.

in blender, see if there is actually a 125, 245, or 124 triangle. if not, then select the 145 triangle surface, delete it without deleting the vertices. then select vertexes 1,2,4, and 5 and create a surface across them. you may need to do the same on the opposite side of the stairs.

Before a model is sent to a graphics card and typically when a model is imported to a game engine or created in a suite like blender, everything is converted to triangles. it is how a graphics card processes all shapes, technically lines and quads are supported natively in most graphics card too, but are rarely used and not as well supported. As you can see in your unity editor, the edges of triangles are visible on the model as i highlighted above. Unity triangulated the model on its way to importing the model. With no line being visible between points 2 and 5, either unity is not drawing that edge or its triangulation algorithm failed to create it. after triangulating in Blender you do have that line. Have you tried importing that triangulated model to unity instead?

I hope that can help.

## UPDATE

in future attempts we found that the vertex issue was not an issue. However we did stumble into another unity issue.

We found that when the mesh renderer was deactivated, the mesh collider generated correctly. We were able to solve the overall issue by nesting a copy of the same mesh inside itself. one level with only the renderer and the other with only the collider. This allowed the use of the concave collider

# Answer
> 0 votes
A first thought was that backface culling might cause troubles, but if you are using the default shader this issue should be visible in the rendering as well.

Did you play around with the MeshCollider Cooking Options?

Is it generating a Collider if you select the Convex option?

---
Tags: unity, blender, 3d-meshes, collider
---