# Question
Title: Bullet spread changes depending on the camera direction
I'm working on an FPS game. I want to make a little bit of difference in shooting direction, only on the horizontal axis.

To do this, I wrote this code:

```
Temp_Shake_Horizontal.x = Random.Range(-0.1f, 0.1f);

if (Physics.Raycast(the_camera.position, the_camera.forward + Temp_Shake_Horizontal, out BulletDecal_Hit, Mathf.Infinity))
{
     Quaternion HitRot = Quaternion.FromToRotation(Vector3.forward, BulletDecal_Hit.normal);
     decals_Objs[decal_Index].transform.position = BulletDecal_Hit.point;
     decals_Objs[decal_Index].transform.rotation = HitRot;
}

```

But I don't know why, when I rotate the camera, the result is changing!

Here is what it looks like when I face in one direction (this is the intended result):

But when I rotate the camera about 90 degrees to the left or right, the result is no horizontal variation: the bullets all line up in a vertical column.

Why does this happen, and how can I solve this issue? I want the result to always be like the first picture, with random variation side-to-side.

# Answer
> 1 votes
```
Temp_Shake_Horizontal.x = Random.Range(-0.1f, 0.1f);

```

This shake is always applied along the world x-axis. That means, if you're aiming along the world x-axis, the shake is being applied forward & backward along your direction of fire (ie. not changing the direction).

To apply the shake relative to your current facing direction, do this:

```
Temp_Shake_Horizontal += Random.Range(-0.1f, 0.1f) * the_camera.right;

```

You'll want to clear this shake out between uses so it doesn't accumulate - I assume you're already doing that based on the `Temp_` name on the variable, but I can't see that part of your code, so you may need to make additional tweaks.

# Answer
> 0 votes
Actually my problem solved by this way :

```
Temp_Shake_Horizontal = Random.Range(-0.1f, 0.1f) * the_camera.right;

```

without +

---
Tags: unity, physics, vector, raycasting, first-person-shooter
---


title: Aiming in a twin stick shooter

text:
# Question
Title: Aiming in a twin stick shooter
I am trying to implement a **twin stick shooter** game, sometimes referred to as **dual stick shooter** where the left stick controls movement, and the right stick aims a gun.

What I do now, is directly map the stick angle to the gun angle, if the deflection is large enough. In pseudo code:

```
// jx in [-1,1]
// jy in [-1,1]
if lenght (jx,jy) > 0.5 :
    gun_angle = toangle( jx, jy )

```

This gives a very unsmoothed, twitchy signal for the aim.

The gun can flicker in any direction in a single frame.

In theory, the most responsive scheme, but on-screen looks far too twitchy.

So I wonder: should I sacrifice some responsiveness for a smoother signal?

Should I make the gun swivel around as I reverse the direction of the joystick, or just set it hard, like I do now?

I've been considering using the stick signal as input to a PID controller that does the actual gun rotation, but would like to know whether that's an appropriate solution for this application.

# Answer
> 2 votes
The general rule of thumb in game design is that it is better for a game to *feel* right than to *be* right. So smoothing out the gun movement can be a viable method to make it appear less twitchy. I am not sure, though, if using a proportional–integral–derivative controller is the best technique here. Have you considered just taking the average of the past few input measurements? However, without actually playing or even seeing your game, I am just guessing here.

Another thing you might want to experiment with is the size of the deadzone of your firing thumb stick. When you give a shooting signal even if the stick is just moving a tiny bit away from the center, you will get a lot of unintentional "phantom shots" in random directions even if the player's firing finger is just resting. So you might want to define a minimum distance from the center which is required to trigger a shot. Keep in mind that not all gamepads are the same, so you might want to make the deadzone size configurable.

# Answer
> 1 votes
You always have the option of slowing down the responsiveness, by limiting hte speed at which the character can turn as you mentioned; but there is also another possibility if the game play is feeling 'perfect' with the current responsiveness: You could instead slow down the animation to blend better while maintaining the game play responsiveness, for example by having the body of the character turn at a maximum speed while the arm holding the gun could swivel past that and effectively cover the full range when both are used together.

---
Tags: game-design, control, gamepad
---


# Question
Title: Google Play Services Message Handling with Libgdx
I'm looking for some idea of how to handle Reliable Messages in Google Play Services with libGDX. So far I've been using it like this: I was waiting for message with `OnRealTimeMessageReceivedListener`, setting an outside `byte[]` array to the message received, changing a flag that suggests that new message arrived to true, getting that message in my libGDX class using methods from interface, setting `newMessage` flag again to false, handling message, and so again waiting for new one

```
private OnRealTimeMessageReceivedListener mMessageRecievedHandler = new OnRealTimeMessageReceivedListener() {
        @Override
        public void onRealTimeMessageReceived(@NonNull RealTimeMessage realTimeMessage) {

            //Handle received message here

            byte[] message = realTimeMessage.getMessageData();

            /*byte tbye[] = message;
            ByteBuffer bb = ByteBuffer.wrap(tbye);
            if(bb.getFloat() == 1884) {
                Log.d("MESSAGETEST", "Message received in anL : " + debugIntL);
                debugIntL++;
            } */

            byteArray = message;

            newMessageFlag = true;
        }
    };

@Override
    public boolean getNewMessageFlag() {
        return newMessageFlag;
    }

@Override
    public byte[] getMessage() {
        newMessageFlag = false;
        return byteArray;
    }

```

Libgdx class:

```
@Override
    public void render (float delta) {
    ...
    checkForNewMessage();
    ...
   }

private void checkForNewMessage() {

    if(game.customHandler.getNewMessageFlag()) {
        handleMessage(); // handling message here
    }

}

private void handleMessage() {

        byte[] message = game.customHandler.getMessage();

        ByteBuffer bb = ByteBuffer.wrap(message);

        float typeOfMessage = bb.getFloat();

        if(typeOfMessage == NEW_UNIT_MESSAGE) {

            Gdx.app.log("MESSAGETEST", "Message received in gdx : " + debugInt);
            debugInt++;
            ...
           }
       }

```

But the result is, when uncommenting the code in `OnRealTimeMessageReceivedListener` and adding similar log to my `handleMessage();` that some messages are skipped between receiving it in listener and checking for new in my libGDX class, I don't know why, maybe because some `render` calls take longer to do everything inside and it skips through one check call when there's significant number of those in small amount of time

On the image you can see that first log is from `OnRealTimeMessageReceivedListener`, which receives every message, but the second one is from `handleMessage`, and at 251 there it wasn't called, so `handleMessage` just skipped this message and went to the next one.

So here's my question, what's good way to handle those messages so that I won't skip any?

# Answer
> 0 votes
so if anyone has the same problem i think i found the solution, there's been no problems with that so far, i'll edit this answer if it turns out to have some problems.

Anyway, the solution is as follows, I completely abandoned the idea of checking for new message with flags, and then handling it, instead in main class with `OnRealTimeMessageReceivedListener` i created `private List<byte[]> byteArrayList`and changed listener to:

```
private OnRealTimeMessageReceivedListener mMessageRecievedHandler = new OnRealTimeMessageReceivedListener() {
        @Override
        public void onRealTimeMessageReceived(@NonNull RealTimeMessage realTimeMessage) {

            //Handle received message here

            byte[] message = realTimeMessage.getMessageData();

            byteArrayList.add(message);

        }
    };

@Override
public List<byte[]> getArrayOfMessages() {
    return byteArrayList;
}

```

Then in the libGDX class instead of `checkForNewMessage()` in `render` method i just put the `handleMessage()`there which looks like this

```
private void handleMessage() {

        if(!game.customHandler.getArrayOfMessages().isEmpty() && game.customHandler.getArrayOfMessages() != null) {

            byte[] message = game.customHandler.getArrayOfMessages().get(0);
            game.customHandler.getArrayOfMessages().remove(0);

            ByteBuffer bb = ByteBuffer.wrap(message);

             // Rest of handling message...

```

This way it won't skip anything, because every message is inside a `ArrayList`, and `handleMessage()` handles every message that is inside of it one by one.

---
Tags: libgdx, google-play-services
---


# Question
Title: SceneKit flickering with Ambient and Omnidirectional lights
I have a project where I have a sphere with a png texture that represents a planet (or a moon in the videos I'm attaching).

Wrapped around that sphere I have a hexasphere (implemented using the results of my question from last year: How to orient a hexagonal tile on a geodesic sphere (Goldberg polyhedron)?).

Almost everything works just fine however I've noticed that in some situations, the hexasphere flickers at some points.

From my experiments, it seems that the problem is the lighting I am using.

The hierarchy of nodes I have is as follows:

```
bodyContainer    OMNI
    planet         OMNI (sphere, radius:0.987 with image texture as it's only (diffuse) material)
    hexasphere   AMBIENT (hexasphere, radius: 1.0 as described in the linked question)

```

There are two light sources, both placed at the centre of the "sun" in my larger model. OMNI is an Omnidirectional light source with default settings. AMBIENT is an Ambient light source.

The reason that "body" uses OMNI is that I want the planet or moon to have a light and dark side which changes as the body orbits the sun.

The hexasphere that is co-located with the body by being a sibling of the body in the same container. It needs to use the AMBIENT light source so that it is equally visible on the dark side of the planet or moon.

What I'm noticing, it that when I move the camera further away from the planet, the parts of the hexasphere closest to the camera seem to flicker, and I seem to be able to see through to some of the hexasphere's cells on the opposite of the sphere.

Here are some videos to show what I'm seeing.

This first shows the scene in it's full 'glory' with all nodes in play as described above:

https://youtu.be/o3hdpuLoSbQ

This next one shows the same hierarchy, however I've changed the planet body to use the AMBIENT light instead. Note that there is no flicker, but also, I've lost the dark/light side of the planet.

https://youtu.be/O0Ca-MrYgJc

In this 3rd video, I've replaced the body texture with a simple translucent blue color, and reverted to using the OMNI light. It looks great, but the flickering is back.

https://youtu.be/ftGWnaqoN5I

Finally, I've changed back to the AMBIENT light again, but kept the blue body texture. Note that the flickering is gone again.

https://youtu.be/c6i5vjOEauw

I'm quite positive that this is something I can fix, but I don't understand yet how. Is this simply a weakness in the lighting mechanisms in SceneKit?

Is there something special I should be doing to allow the outer hexasphere to render cleanly (i.e. without the flickering), with the ambient light, whilst having the inner sphere that is using an omni light?

**UPDATE**

I've found one solution that appears to work, however I'm not sure if this will result in a lower quality visual overall. If I set the material property `litPerPixel` to NO, then the problem I've outlined goes away. I'm just not sure that the presumed "lower quality" rendering might cause other problems elsewhere.

# Answer
> 1 votes
I would recommend either rescaling the scene so that things don’t get 600,000 units away, or adjust zNear in proportion to zFar. As the ratio of zFar:zNear gets greater, the depth buffer precision decreases, appearing as z-fighting in surfaces near each other. As the default ratio in SceneKit is 100:1, adjusting zNear to be on the order of 1000 would keep the same ratio, although that does seem quite large. You could try something closer to 10 or 100, and see how that affects the scene.

See here for some details about the ratio problem: https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluPerspective.xml

---
Tags: lighting, scenekit
---


# Question
Title: Texture won't appear using a vector of unique pointers of an Object
I am working on a top down 2d shooter game. I have a player Sprite and a Bullet class. I made a vector of pointers to Bullet to store the bullets. Here is the code of the vector and the functions I’m using:

```
    std::vector<std::unique_ptr<Bullet>> b;

    while(win.isOpen)
    {
    //Getting Key Press
    if (Keyboard::isKeyPressed(Keyboard::Space))
    {
        space = true;
    }
    else
    {
        space = false;
    }
    if (space)
    {
        Bullet b1;
        b1.setPos(player.getPosition());
        b.push_back(std::make_unique<Bullet>(b1));
    }

    for (auto& it : b)
    {
        //Keep Updating
        it->update();
    }

    //Bullet out of Screen
    for (int i = 0; i < b.size(); i++)
    {
        if (b[i]->getPos().y < 0.0f)
        {
            b.erase(b.begin() + i);
            i--;
        }
    }

    //Drawing Bullet
    for (auto& i : b)
    {
        win.draw(i->getSprite());
    }
     }

```

The game runs fine but the bullet’s texture won’t load. I’m assuming it has something to do with the vector but I don’t know how to solve it. Here is the Bullet class: Header:

```
 #pragma once
 #include <SFML/Graphics.hpp>

 using namespace sf;

 class Bullet
 {
private:
Texture t;
Sprite bullet;
Vector2f pos;
public:
Bullet();
void setPos(Vector2f pos);
void update();
Sprite& getSprite();
Vector2f getPos();
};

```

Cpp File: #include "pch.h" #include "Bullet.h" #include

```
Bullet::Bullet()
{
//Setting Texture
if (!t.loadFromFile("Graphics/bullet.png"))
{
    std::cout << "Bullet Texture Failed to Load\n";
}
else
{
    t.loadFromFile("Graphics/bullet.png");
    bullet.setTexture(t);
}

}

void Bullet::setPos(Vector2f pos)
{
//Setting Position
this->pos = pos;
bullet.setPosition(this->pos);
}

void Bullet::update()
{
pos = bullet.getPosition();

bullet.move(0.0f, -4.0f);

}

Sprite& Bullet::getSprite()
{
return bullet;
}

Vector2f Bullet::getPos()
{
return pos;
}

```

# Answer
> 2 votes
# Why is there this issue?

The issue is here:

```
if (space)
{
  Bullet b1;
  b1.setPos(player.getPosition());
  b.push_back(std::make_unique<Bullet>(b1));
}

```

Let's look at the `Bullet` class (the relevant parts):

```
class Bullet
{
private:
  Texture t;
  Sprite bullet;

public:
  Bullet()
  {
    //Setting Texture
    if (!t.loadFromFile("Graphics/bullet2.png"))
    {
      std::cout << "Bullet Texture Failed to Load\n";
    }
    else
    {
      t.loadFromFile("Graphics/bullet2.png");
      bullet.setTexture(t);
    }
  }
};

```

and the `Sprite` class (the relevant parts):

```
class SFML_GRAPHICS_API Sprite : public Drawable, public Transformable
{
public:
    Sprite() :
      m_texture (NULL) {}
    void setTexture(const Texture& texture, bool resetRect = false)
    {
      m_texture = &texture;
    }
    const Texture* m_texture;     ///< Texture of the sprite
};

```

When a `Bullet` instance is created, the object is created on the stack. The issue comes when you add it to the vector and then get out of the scope. It's most likely moving the objects within to a new location, moving the `Sprite` and the `Texture`. But notice that the `Sprite` has a reference to the texture? This texture will be deleted when we'll come out of the scope of the `if (space)`. Even if we move everything, there is nothing to tell the `Sprite` that the `Texture` has moved.

# How to solve it?

The trivial solution is to create your `Bullet` on the heap right away, using `std::make_unique`:

```
if (space)
{
  b.push_back(std::make_unique<Bullet>());
  b[b.size()-1]->setPos (player.getPosition());
}

```

This way, the references will always stay in place in memory and the image will show.

Doing this will "fix" your issue. But the next step is: you'll notice that when you spawn a `Bullet`, there is some slight lag.

This is most likely due to the lines:

```
if (!t.loadFromFile("Graphics/bullet2.png"))
{
  std::cout << "Bullet Texture Failed to Load\n";
}
else
{
  t.loadFromFile("Graphics/bullet2.png");
  bullet.setTexture(t);
}

```

You're reading a file twice. IO operations are the most costly operations on a system. We can fix this by loading all of our textures at startup, and then passing a reference to them to our `Bullet` instance.

We'll then end up with something like this in your `main()`:

```
...
//Creating the Vector
std::vector<std::unique_ptr<Bullet>> b;
std::map<std::string, std::unique_ptr<Texture>> textures;

auto load_texture = [&]( std::string texture_path, std::string texture_id ) {

  std::unique_ptr<Texture> new_texture = std::make_unique<Texture>();

  if ( new_texture->loadFromFile( texture_path ) )
  {
    textures[texture_id] = std::move( new_texture );
  }
  else
  {
    std::cout << "Failed to load \"" << texture_id << "\" for path \"" << texture_path << "\".\n";
  }
};

load_texture( "Graphics/bullet2.png", "bullet" );

bool space = false;

...

if (space)
{
  auto texture = textures.find( "bullet" );

  b.push_back(std::make_unique<Bullet>(*texture->second));
  b[b.size()-1]->setPos (player.getPosition());
}

...

```

And a `Bullet` class like this:

```
class Bullet
{
private:
  Texture& t;
  Sprite bullet;
  Vector2f pos;
public:
  Bullet(Texture& texture);
  ~Bullet();
  void setPos(Vector2f pos);
  void update();
  Sprite getSprite();
  Vector2f getPos();
};

Bullet::Bullet(Texture& texture)
  : t(texture)
{
  bullet.setTexture(t);
}

```

The added advantage here is that you'll be using less memory (you really don't need to have the same image multiple times in memory).

---

*This is based on the code you supplied on your other answer. I have uploaded the relevant changes to a github repository.*

---
Tags: c++, sfml
---


# Question
Title: How can I position framebuffer objects on the screen in OpenGL?
I currently have two framebuffers which are drawn using

```
glBlitFramebuffer(0, 0, 1920, 1080, 0, 0, 1920, 1080,
    GL_COLOR_BUFFER_BIT, GL_NEAREST);

```

But the texture does not take up the whole screen, and I would like to position it at a certain x,y on the screen. The images by default start from 0,0 and then span the width/height provided, however I would like the image to start at say, `[100, 100]` and span the width/height provided.

How would I do this?

# Answer
> 1 votes
The last 4 positional parameters to the function are for destination position. The position can be changed using this, but the image pixels must be exact or the image won't be displayed.

# Answer
> 0 votes
```
void Graphics::fboToScreen(GLuint fbo){
    int w, h; getWindowSize(w, h);
    int startAtX = 100;
    int startAtY = 100;
    glBlitNamedFramebuffer(fbo, 0, 0, 0, w, h, startAtX, startAtY, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
}

```

---
Tags: opengl, frame-buffer
---


title: How Can I Roll A Cube In Unity?

text:
# Question
Title: How Can I Roll A Cube In Unity?
Roll a cube in 1 direction Hi, I want to move a cube just to the front when the screen is taped in my Unity 2D project. I have seen some codes about this but I just need to move it in one direction (front).
Can someone help me?

# Answer
Find vertex with lowest height and rotate whole cube around that point.
> 1 votes

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


# Question
Title: Are all referenced sprites loaded into memory for each object?
I'm trying to understand how Unity works behind the scenes. Let's say I have a GameObject that has a large number of sprites attached to it in an array (think a deck of cards). Each GameObject represents 1 card.

For simplicity, each card has all the sprites for all the card faces. So it has 52 sprites + 1 for the card back (all in a sprite sheet of course).

If I have all 52 cards placed in the world. Does this mean I have 53\*52=2756 sprites, or is there only one instance of each sprite that's being displayed (ie does it only use the resources of 52 active sprites)?

I guess what i'm asking is if I have a bunch of sprites attached to a GameObject, are they all instantiated when the object is created, or are they only created when they are actually attached to the sprite renderer?

Would it be more efficient to only attach the current cards value sprite (ie just the back and the face for the cards value)?

# Answer
> 2 votes
# ...Maybe

The answer is going to depend *entirely* on how you're generating the sprites. If you're doing something like `Resources.Load` in a single place and querying or assigning them to the array manually, then no, you won't have 2756 sprites in your scene (only 52). e.g. like this.

On the other hand, if you're calling `new Sprite(...)` *yourself* and passing in a texture, and doing this in a script that runs on each GameObject, then yes, you'll have 2756 total sprites (and waste memory as they will not die on their own).

I learned this by mistake in one of my own projects where I had a menu that was being rebuilt every frame and invoking some utility code that called `new Sprite(...)` and Unity would chew through memory like no one's business until finally crashing. Once I was able to isolate the problem to "its this screen..." I was able to locate the errant (and extraneous) UI construction and remove it.

If you're doing `Resources.Load` *on each GameObject* then I'm *pretty sure* Unity caches the results and only creates a single copy (52 sprites not 2756), but I haven't actually tried to break it. With the same kind of code but for Asset Bundles I suspect the same thing, but haven't messed with it.

---
Tags: unity, sprites
---


title: Unity3d How to add collider to borders

text:
# Question
Title: Unity3d How to add collider to borders
I have a box with a hole in it. Is it posible to add a collider only to the dark blue showed at the img? (But only at the borders, not a box collider. Let's say i want some object to get in the box, but cannot touch the blue bars). And how to?

# Answer
Yes you can.

1. First make a plane of shape of the blue border which you want.
2. Add collider to it.
3. Now create a box and place it to the plane so close that both plane and box look like one single object. Don't add any sort of collider to object.
4. Save it as a prefab. So that you can use it later as well.

Note: Make the plane and the box object in an empty game object.
> -1 votes

---
Tags: unity, collider
---


title: how to draw a dashed path in Javascript

text:
# Question
Title: how to draw a dashed path in Javascript
I need to draw a brick curved path but i need to be able to put an arrow pointing to any a brick by API. something like this:

i thought to use canvas but i'm not sure i can get a reference to each brick and fire events.

# Answer
The HTML5 canvas has no memory of specific shapes which were drawn to it. So you are responsible for remembering where you drew each brick polygon. You could simply create an array where you store the coordinate-pairs for each brick. In fact many games which use HTML5 canvas work that way: The positions and visual information of all objects in the game are stored in data structures which are separated from the canvas. The canvas gets completely erased each frame and then gets redrawn from scratch.

Another option is to use an SVG object instead of a canvas. SVG is also a form of mutable image element, but it is shape-oriented, not pixel-oriented. That means it is possible to assign IDs to objects you add to an SVG document tree and later find and manipulate them by ID. You can even attach mouse event handlers to individual objects in an SVG image.
> 2 votes

---
Tags: javascript
---


# Question
Title: How do I reduce overdraw in a forest scene with lots of foliage?
Unity comes with an *overdraw view* that looks something like this:

We've probably all seen it, and have probably been advised to *check for overdraw*. How do you go about actually doing anything about it?

## My specific case:

I'm currently seeing a lot of overdraw from my terrain grass and trees as they do not respect occlusion culling. This seems to be a limitation in Unity. Is there anything I could do about it to reduce overdraw without losing the lush environment?

For reference, here is the foilage responsible for most of the overdraw and I'm exploring options other than to simply reduce the amount of foliage in the scene and lose the aesthetics:

# Answer
**Overdraw** is a complex subject and there is ***no one size fits all approach*** to solving overdraw problems, but **reducing the number of overlapping objects** that Unity cannot automatically sort is key. The best place to start investigating this issue is in Unity’s Scene view; there is a Draw Mode that allows us to see overdraw in our scene and, from there, identify where we can work to reduce it.

The most common culprits for excessive overdraw are:

1. transparent materials,
2. unoptimized particles
3. and overlapping UI elements

, so we should experiment with optimizing or reducing these. This article on the Unity Learn site focuses primarily on Unity UI, but also contains good general guidance on overdraw.

Ref: *Optimizing graphics rendering in Unity games*
> -2 votes

---
Tags: unity, rendering, optimization
---


# Question
Title: Multithreading MMO Server. A thread per area OK?
As a personal project, I'm setting up a MMO, and writing the server in C#/.NET Core.

As of now my architecture is as follows: The world exists of different areas ( you can go from area to area trough portals ). An area is called a 'room' on my server. Each room has it's own list of clients ( players, each with their TCP stream ).

Now I was wondering if it was ok that I run each room on it's own thread. Each room will manage it's own update cycle ( game loop / room ), as it's independant of other rooms.

My worry is that as the game grows, I will get lots of areas and that a thread per area isn't that great of an idea.

So my question is: Am I doing something wrong or non-benificial in the future ? Am I better off having 1 thread for the game logic for all the rooms ? Or is it ok to have a thread per room ?

# Answer
I think this might be a viable architecture. The biggest source of bugs in multithreaded applications is shared access to data. So when the rooms have little to no communication with each other and need little to no access to the data not explicitly owned by them, then they seem like the obvious candidate for units of parallelization.

If you are worried about *too much* parallelization, keep in mind that it is usually easier to reduce threading than to introduce more of it. When it turns out you would like to handle rooms sequentially after all, then it is usually not much of a refactoring effort to change your update-method to process multiple rooms in a loop instead of just one. On the other hand, chopping a single-threaded architecture into a multi-threaded one after the fact can quickly end up in a buggy mess.

By the way, you might want to organize your code around the `ThreadPool` class and pass `Task`s to it where each task consists of performing a single update-tick for a single room. The ThreadPool can be configured to use a specific number of threads. You shouldn't set it higher than the number of (virtual) CPU cores. When you give it more tasks than it has threads, those tasks will be enqueued and processed as soon as a thread is finished. That means you can leave your update scheduling to the framework.
> 7 votes

---
Tags: c#, multiplayer, mmo, multithreading
---


# Question
Title: Combining Minecraft and Dwarf Fortress: Simulating autoplay in a pseudo-infinite procedurally generated world?
One of the interesting things about Dwarf Fortress (and other procedurally generated games like Civilization) is that the game simulates multiple AI factions interacting with each other over time (what might be termed "autoplay") to generate an evolving world which changes over time, even whilst the player is playing the game.

On the other hand, simulating all the factions simultaneously is surely going to become a bottleneck as the map grows. With a bigger map and more factions, the performance requirements become exorbitant. Minecraft gets around this problem by simply storing the inactive chunk in memory as-is as soon as the player leaves the area. The minecraft world is a static, never-changing place. When a player comes back from a trip, the chunk is exactly as he left it. No world evolution occurs. Everything is always the same.

The most straightforward approach to this, which is to just to make chunks remain loaded in memory even after the player is no longer in them, has the same performance issues as mentioned earlier - as the player moves across thousands of blocks, you will sooner or later run into computation limits. Moreover, this does not solve the general problem of faction simulation - factions can expand or contract through many chunks, whereas keeping one chunk loaded in memory would not affect its neighboring chunks, so that doesn't quite achieve the same effect as autoplay.

The "solution" that I thought of is to come up with a closed form formula that simulates autoplay somehow. That is, a function f(time,coordinates), such that given the time and and coordinates of a block, will tell you what state that block should be in. The problem with this is that this assumes a truly predeterministic world evolution, in which players have control over only their local chunk and no others. In other words, no butterfly effect. Furthermore, when a player leaves a chunk, he has made some changes to it, but the function cannot take those changes into account when computing the state of the block the next time the player enters it, in other words all changes that the player made to the block are lost as soon as he leaves. This is obviously not ideal.

Am I asking for something impossible?

# Answer
> 5 votes
**Fake it!**

It's a game, after all. We approximate constantly.

Simulations have an inverse correlation between fidelity and size/scope, so given fixed hardware you'll have to compromise. If you want a huge world, you'll need to reduce fidelity.

Always ask: **Can the player tell the difference?**

### Variable Fidelity

This answer, broad as it is, relies on the idea that you can adjust your AI/world simulation's fidelity fairly easily, which I think is beyond what I can explain here. In general, the idea is to aggressively relax constraints as you reduce fidelity, thereby reducing the time it takes to simulate.

E.g., say you have an NPC with 'thirst', and it lives in an house near-ish to a body of fresh water.

* **Highest-fidelity:** Path-plan how each NPC gets from their current location to the water, and have that NPC execute this at a time appropriate for their thirst level, which is affected by their other activities.
* **High-fidelity:** Vaguely assert that NPCs in an area can reach the water, taking X units of time to do so, so any time that "high-level action" is taken, they lose some units of time and lose thirst.
* **Mid-fidelity:** The NPCs live near water and have jobs with thirst 'costs'. Use those costs to reduce the NPCs' available time.
* **Low-fidelity:** There's a population of NPCs in an area with a mix of jobs, quenching thirst occupies X% of their available time.
* **Very-Low-fidelity:** A faction has a population that loses X% of its time to resolving thirst. Eventually this time can accumulate to represent large-scale works (building dams), or going to war over water rights, etc.
* **Lowest-fidelity:** Regions of size Y and climate Z tend to have P-Q factions, population ranging from M to N. Z climate means those factions spend J-K% of their time related to thirst and thirst endeavors.

etc.

The highest fidelity is for use when the player's in the area and may be watching, or has made significant changes the area. Lowest fidelity is for when you just want to say "Are there any factions to the east of the currently known map that might launch an attack on a water-rich nation?"

The important thing, again, is that players likely won't be able to tell the difference, if you're careful with when you employ different levels.

So with that kind of system in mind, it's really just about choosing when you can get away with reduced fidelity, and how much it can be reduced by.

### Closed Form

Your 'closed form' suggestion is a good way to reduce fidelity (ignoring player edits), but I imagine you'll find it very hard to implement. AI and simulation are notoriously finicky even without this constraint.

### Absence Makes the Simulation Grow ... Lower-fidelity

IMil's suggestion to think in terms of a 'state + time' mutation function is good, and I think you could find decent success by "binning" that mutation step into different fidelities, by duration.

E.g.:

* Recently visited chunk: high-fidelity update
* Absent a couple hours? "middle-fidelity" update
* Absent a couple days? low-fidelity update
* Weeks? Very low fidelity (or essentially re-randomized/placed in a 'wild' state)

### Chunk 'Warmth'

If you're trying to simulate in real time, this looks a bit like a 'warmed cache' question: The chunk gets 'colder' when it's visited less frequently. As this happens, it gradually shifts to lower and lower fidelity/update frequency, and is eventually unloaded. Reload when the player approaches to catch up on the simulation.

### Importance of Edits/Changes

It's worth considering how important the player's edits are, both to the simulation, and to the player.

A player spending weeks carefully tweaking a chunk is more likely to notice weird simulation there. So, weight your "chunk warmth" by time spent there by the player. Ditto if they take screenshots in the chunk. :)

### Chunk Purity

If you do develop a closed-form (or 'more-closed' form) of your sim, then you can significantly reduce the burden by marking chunks as 'pure' (unedited by the player).

E.g., player passes through a chunk and punches a tree over. If they pass back through two weeks later, will they remember it clearly enough to know whether you just reset the state to being wild?

Another way to 'purify' your chunks is to add entropic forces to your world. E.g., an earthquake could significantly change a landscape, thus wiping out or masking the player's changes there.

Similarly, chaotic AI behavior can make player prediction less effective (at the cost of your world making less sense).

### Statistical Simulation / Simplifications

Similar to the 'closed form', this is level-of-detail applied to your simulation mechanics.

E.g. instead of evaluating stats like hit, crit, dodge... Just compare the health and DPS of the combatants directly. (HP/DPS = time to kill, whoever takes longer to die is the winner).

If you want slightly higher fidelity, maybe you introduce an 'HPS' factor (heal per second) to represent all the ways a character can reduce/repair their damage intake.

There are many other approaches, but hopefully something here is useful.

# Answer
> 0 votes
A more reasonable function signature would be

> getNewState(initialState, timePassed)

E.g. if your sector has a couple beavers and a river, then if you leave it for a month, there will be a dam and a lake. But if you kill the beavers before leaving the sector, the river stays the same.

Obviously, it's easier said than done. You could either deduce the long-term effects of your AI actors yourself, or use ML techniques to predict the long-term effects of their actions.

# Answer
> 0 votes
What you want is a stateless "simulation", ie that is for any input state and a time variable, you get an ouput state. So that when the player come back you don't have to simulate every step to the output. The simplest example is tree growth, if you plant a seed, you can compute the age based on the state, and from the age you derive the size. It's obviously limited and extremely local.

In order to model complex interaction, you need to design system in an hierachical fashion, for example, it's easy to have a stateless simulation of a planet orbit, to get the position of the moon, which depend on the state of earth, you have to get earth state first.

Instead of earth it can be any abstract model. Consider a character, where the character will be a time t? Well if it's night he might be sleeping but at day maybe he is working. That mean that time can be segmented into chunk too, not just space, and just like procedural space, you can attach unique seed for each time chunk (and time block). Using a time table and the character innate state (like personality etc ..) you can derive what a character do at any moment with a probability time table, at night a thief might try to steal house.

Now instead of just generating character activity based on time chunk, try to set a high level time table for any active agent. Then think about how they overlap at high level, and you then access to simulated interaction in similar way. Now you can use the last trick, **correlation**. In order to achieve stateless simulation, you can't use "cause", because you would have to generate all intermediate step, which is costly.

Correlation allows you to side step things, ie you find a state then find why AFTER, tune your simulation that it generate the right plausible coincidence, for example, it's hard to find a river for a given topology, therefore the river first, it follow the slope of the topology, and therefore define it. You empire is declining, therefore you generate war, famine, whatever plausible excuse you can from the state. There is a new house, therefore you need new habitant and make one birth, possibly that house is actually built in the future, so it's not visible yet, let the kid grows first.

Now all you need is a starting state, everytime the player modify a store state, it's easy to advance time to another plausible state.

---
Tags: procedural-generation
---


# Question
Title: Why does setting a static member value in MonoBehaviour child class constructor have no effect?
I am following a tutorial for Unity. I don't know C# but I know other similar languages.

I got the tutorial to work. Here is the script I used.

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

public class PlayerMove : MonoBehaviour {

    private Rigidbody rb;
    public float speed;

    // Use this for initialization
    void Start () {
        speed = 3.5f;
        rb = GetComponent <Rigidbody> ();
    }

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

        float fx = Input.GetAxis ("Horizontal");
        float fz = Input.GetAxis ("Vertical");

        rb.AddForce (new Vector3 (fx, 0, fz) * speed);
    }
}

```

This goes slightly against my C++ instincts, which are to put initialization values in a constructor.

```
    public PlayerMove ()
    {
        speed = 3.5f;
    }

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

```

This doesn't work. In Unity, the `speed` field has an initial value of 0.

Why does setting the initial value in a constructor not work?

# Answer
> 0 votes
When you attach a component to an object in a Unity scene, or to a saved prefab object, unity serializes the values of its public (or serializable) members into the scene / prefab file.

When you next open or run that scene or spawn an instance of that prefab, Unity creates an instance of the component with the default constructor, then overwrites its members with those serialized values.

Normally this is a good thing: I set speed to 5 in the inspector when editing my scene / assets, I still see the value of 5 the next time I open the editor, and I get a value of 5 at runtime in the game.

But since this deserialization happens after the constructor has run, it can stomp or override values set by the constructor. In this case, you may have created the object in the editor with the initial default value of 0, which got saved into your scene file, before adding the 3.5 value to your constructor. The constructor value can't override what's saved in the scene.

For reasons like this, it's recommended not to use constructors for MonoBehaviours. Instead, use the Awake, OnEnable, or Start methods if you want to do additional initialization after the component has been deserialized.

If you want to set up a default value that the developer can override in the Unity editor's inspector, a field initializer suffices, eg..

```
 public float speed = 3.5f;

```

---
Tags: unity
---


title: anticheat architecture

text:
# Question
Title: anticheat architecture
I have online game for which I wrote a simple external anticheat in c#, it checks my game's process modules and handles for suspicious activity. And so it works like this:

* player starts launcher (anticheat) which then starts the game with its pid as parameter
* actual game (upon starting) reads that pid, locates anticheat path using this pid and fetches md5 hash of my anticheat
* If it doesn't match the game closes. Also if you close anticheat the game closes too.

So theoretically there's no way user could exit anticheat without exiting the game except he could for instance suspend anticheat process and then its of no use. What simple thing I could do to prevent this from happening? I was thinking - make a thread in the game that would check in a loop if anticheat process is suspended and exit if it is. Would that be a correct approach?

Is my architecture flawed or is it ok?

# Answer
It's flawed. All online games have the same problem. Only way to keep em secure, is to shut it down, disconnect internet, seal in cement and send to space and never ever mention that you created a online game.

Problem is, that you have to give code to the client and you should always expect, that client sees all the code and is willing to create harm.

No matter how many processes you start, how often you check and compare, there is still just one boolean that needs to be flipped. Somewhere in your code, there is an `if (externalMD5 == internalMD5)`. That if can be changed to return always true.

Custom launcher can be made, that starts the game with the wanted PID and after that your check means nothing.

Your first problem is to get players for your game. Design your game from start to end with cheating in mind and don't trust the client. Users will do what ever they can to break the game, with full intentions and by accidents.

Secure your networking, only ask input from user, do not allow client to create, move, edit or interact with anything directly. Always have server issuing commands.

Valve, blizzard, Epic, ubisoft, EA. Everyone fails with this. Only reason you see some games banning someone, is because users use public hacks. Private, closed circle cheating is so easy, that you really should not focus on that.

Don't send anything to client, that he absolutely should not know. If that information gives edge to the player, you should assume he knows it.

TL;DR; Forget anticheat, never trust the client
> 1 votes

---
Tags: c#, anti-cheat
---


# Question
Title: Blurry UI when using Screen Space Camera
I am using Screen-Space Camera as a render mode on canvas but the Textmeshpro text and other UI elements are looking blurry around edges. I think it might be due to canvas scaler setting. After changing plane distance or making canvas child of camera problem still exist.Following is the result I am getting in unity and Canvas settings.

# Answer
> 1 votes
After playing with different settings finally, I solved it after disabling Allow HDR on camera setting.

---
Tags: unity, gui
---


# Question
Title: GLSL Shader compiles, but source is empty
I'm trying to compile a GLSL shader, to which I use the following code.

Initialization

```
SDL_Window* boringInitStuff(){
    SDL_Init(SDL_INIT_VIDEO);
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );

    Uint32 windowFlags = SDL_WINDOW_OPENGL;
    SDL_Window* sdlWindow = SDL_CreateWindow("Boooring", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 400, 400, windowFlags);

    SDL_GL_CreateContext(sdlWindow);

    glewExperimental = GL_TRUE;
    glewInit();

    return sdlWindow;
}

```

File parser

```
void readFile(std::string path, std::string& data){
    std::ifstream f(path.c_str(), std::ios::binary);
    data.assign((std::istreambuf_iterator<char>(f)),
                (std::istreambuf_iterator<char>()));
}

```

Main

```
int main(int argv, char** args) {
    SDL_Window* sdlWindow = boringInitStuff();

    std::string buffer;
    readFile("./compile_test.vert", buffer);
    const char* cBuffer = buffer.c_str();

    GLuint shaderID = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(shaderID, 1, &cBuffer, nullptr);
    glCompileShader(shaderID);

    while(!SDL_QuitRequested()){
        SDL_GL_SwapWindow(sdlWindow);
    }

    return 0;
}

```

But when I try to inspect the source code in gDEBugger, the source code is gone. Linking of course doesn't work aswell. The weird thing is, that the compilation error checking works. **EDIT:** When I copy & paste the main part into another opengl project, it works.

# Answer
> 1 votes
Creating a new Project in CLion and just copy-pasting the source code fixed the problem. Sadly I still don't exactly know why the error was there in the first place.

**EDIT:**

Apparently the name I give the project makes the difference. When I give the Project the Name `OpenGLTestbed`, it does not work, the shaders won't compile correctly. But if I rename the project to anything else, in my case `Testbed`, it compiles the shaders correctly.

I'm working in CLion with MinGW.

---
Tags: opengl, shaders, glsl
---


# Question
Title: Object reference not set to an instance of the object;
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {

    public CharacterController2D controller;

    public float runSpeed = 40f;

    private float horizontalMove = 0f;

    // Update is called once per frame
    void Update () {
        horizontalMove = Input.GetAxisRaw("Horizontal")*runSpeed;
    }

    void FixedUpdate(){
        controller.Move(horizontalMove*Time.fixedDeltaTime,false,false);//error is somewhere here
    }
}

```

Though all the classes are defines it throws the error please help!!!!!

# Answer
Ensure you've assigned a valid component into your `controller` field in the inspector before running your game.

If you've looked and you're sure it's there, then you might accidentally have another instance of this `PlayerMovement` script somewhere else in your scene. Add a `Debug.Log` to print out the name of the object in `Start()` to help track down the spare, uninitialized instance.

Also, note that capturing horizontal input in `Update()`, saving it to a variable then using it in the next `FixedUpdate()` will add at least one unnecessary frame of latency to your input, since `Update()` runs after `FixedUpdate()` in a frame. Instead, you can read and use your axis input in `FixedUpdate()` directly to get the latest info "hot off the presses." ;)

I've seen advice claiming that the latest input isn't available until `Update()`, but experimentally this is not true for any version of Unity I've tested. It might be superstition left over from an older version, or an over-application of the rule to not naively handle *instantaneous* inputs (eg. button down events that happen for only one frame) in `FixedUpdate()` since it can miss or double-handle them. This is easy to work around though, so lag is usually unnecessary there too.
> 1 votes

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


# Question
Title: Is there a simple way to stop enemies standing in the same spot?
So: top-down game, my enemies chase the player, when they get within a certain distance they stand still and fire. If they're all coming from the same direction they all end up standing in the same spot (i.e. standing "within" each other), as I'm not currently doing collision detection between enemies - they are free to pass over each other.

What's a simple way around this? Either some form of collision detection or some ai?

# Answer
You don't need collision detection, but you will need to give your enemies a bit of intelligence, and have them avoid running in to each other. Collision detection without that will just make your enemies look stupid anyway - people avoid each other, they don't generally collide.

Look up "flocking" for some simple behaviours.

The basic idea is that things should head towards the player, but away from a close obstacle (each other, walls, that kind of thing).
> 18 votes

# Answer
You could inspire yourself on flocking behaviours, such as Boids.

These tend to consist on 3-4 very simple rules that, applied correctly, result on very satisfying and "complex-looking" behaviours.

In your case, you could try something like this:

* Separation (minimun radii between enemies)
* Cohesion (so they travel in groups)
* Alignment (so they tend to move on the same direction)
* Targetted (they should tend to move towards the player)
> 12 votes

# Answer
What you're asking about in general is dynamic avoidance between actors. You could take a look at velocity obstacles: http://gamma.cs.unc.edu/RVO/
> 4 votes

# Answer
You may want to check out **collaborative diffusion** (great animations here) or some other kind of **antiobject** pattern for movement. While the diffusion algorithm in and of itself may not stop enemies from crossing over, you can add additional constraints to make it unlikely or impossible.
> 3 votes

# Answer
What if you disallow moving through other units? It seems to me you will need it sooner or later. Whenever the current path is blocked by a unit, adjust the path to move around that.
> 2 votes

# Answer
There's some reference for steering and flocking behaviours at Craig Reynold's website. They're relatively simple to implement but can produce some lovely emergent behaviour.
> 2 votes

# Answer
All the other answers produce a better result, but the cheapest(?) way to avoid complete grouping is to just add a random vector that is perhaps 25% of the original calculated movement vector so that objects bounce around a bit in a general blob group. It won't keep things completely off of each other, but depending on what you are trying to achieve, I have found this can be adequate. Objects can still group with this method if you run circles around them, but over time they tend to diffuse.

Here is a small game-let I made several years ago that demonstrates this method: http://deleter.phatcode.net/index.php?page=projects&p=4
> 1 votes

# Answer
People always bring up boids because that gives very good results, but implementing boids may be overkill for your specific purpose. In the past I've gotten very good results by simply randomizing the target position within a small circle.

For example, for a demo I built in Unity I used its command Random.insideUnitSphere to do flocking puffballs
> 1 votes

# Answer
I was facing the same probelm when I using NevMeshAgent as enemy, enemeis are penetrating in eachother so i increase the

**NavMeshAgent's radius**

Thanks to **gameDevAnswer**
> 0 votes

---
Tags: ai, collision-detection
---


# Question
Title: Help needed with syncing animation speed of a player in a Networked game (Unity)
Follow-up with new code, as per below answer. Unfornutely i still have it wrong and now the character doesn't animate at all (it seems to stay at 0.00 of the clip for ever or constantly resets to 0.00 in each frame). The code looks a bit lengthy but there's really not that much too it. I appreciate any of you expert folk taking a closer look and would happily buy you a coffee or two via paypal if you can help me out with this mind-boggling problem :S :\]

nb. The object has always had an Animator and NetworkAnimator on the parent object. It also has NetworkIdentity and NetworkTransform. The Identity of the player (the object in question) is set to 'Local Player Authority'

new code (not working still!):

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

public class Player_mp : NetworkBehaviour {
public float walkSpeed, sideSpeed, turnSpeed, aimSpeed;
Vector3 inputInWorldSpace;
public Gun currentGun;
public Transform headLookTransform, gunShoulderRestTransform;
public string walkAnim, walkBackAnim, strafeLeftAnim, strafeRightAnim, turnLeftAnim, turnrightAnim, jumpAnim, runAnim, runBackAnim;
public GameObject bulletPrefab;

[SyncVar(hook = "OnAnimChangeSpeed")] float animationSpeed;
[SyncVar(hook = "OnAnimChangeString")] string animationString;
Vector3 velLocalised;

private void Update()
{
    if (!isLocalPlayer)
    {
        return;
    }
    // QUESTION:: Is this meant to also be a SyncVar????
    velLocalised = transform.InverseTransformVector(GetComponent<CharacterController>().velocity);
}

void FixedUpdate () {
    if (!isLocalPlayer)
    {
        return;
    }

    float mouseX = Input.GetAxis("Mouse X");
    float mouseY = Input.GetAxis("Mouse Y");
    transform.SetPositionAndRotation(transform.position, Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y + (mouseX * turnSpeed * Time.deltaTime), transform.eulerAngles.z));

    if (Input.GetMouseButtonDown(0))
    {
        CmdFireBullet(); // NOTE::: Note this Command has always worked as I expected to shoot bullets
    }
    Vector3 inputs = new Vector3(Input.GetAxis("Horizontal") * walkSpeed * Time.deltaTime, 0, Input.GetAxis("Vertical") * sideSpeed * Time.deltaTime);
    inputInWorldSpace = transform.TransformVector(inputs);

    gunShoulderRestTransform.eulerAngles = new Vector3(gunShoulderRestTransform.eulerAngles.x, transform.eulerAngles.y, transform.eulerAngles.z);
    gunShoulderRestTransform.Rotate(mouseY, 0, 0);

    if (inputs.z > 0)
    {
        animationSpeed = velLocalised.z;

    }
    else if (inputs.z < 0)
    {
        animationSpeed = velLocalised.z;
        CmdChangeAnimString(walkBackAnim);
    }
    else if (inputs.x > 0)
    {
        animationSpeed = velLocalised.x;
        CmdChangeAnimString(strafeRightAnim);
    }
    else if (inputs.x < 0)
    {
        animationSpeed = velLocalised.x;
        CmdChangeAnimString(strafeLeftAnim);
    }
    else
    {
        animationSpeed = velLocalised.z;
    }
    OnAnimChangeSpeed(animationSpeed);
    OnAnimChangeString(animationString);

}

private void LateUpdate()
{
    if (!isLocalPlayer)
    {
        return;
    }

    GetComponent<CharacterController>().Move(inputInWorldSpace);

}

[Command] // Handles Firing Bullets..
void CmdFireBullet()
{
    GameObject bullet = Instantiate(bulletPrefab);
    NetworkServer.Spawn(bullet);
    Vector3 bulletForce = currentGun.transform.forward * currentGun.bulletForce;
    bullet.GetComponent<Bullet>().Fire(currentGun.bulletSpawn.transform.position, currentGun.bulletSpawn.transform.eulerAngles, bulletForce);

}

// Functions to change animation speed per client as per it's character controllers velocity....
void OnAnimChangeSpeed(float speed)
{
    Debug.Log("anim speed change detected");
    CmdChangeAnimSpeed(speed);
}
[Command]
void CmdChangeAnimSpeed(float animSpeed)
{
    RpcChangeAnimSpeed(animSpeed);
}
[ClientRpc]
void RpcChangeAnimSpeed(float animSpeed)
{
    animSpeed = Mathf.Abs(animSpeed);
    Debug.Log("animspeed ABS = " + animSpeed);
    GetComponent<Animator>().speed = animSpeed;
    Debug.Log("actual animator speed = " + GetComponent<Animator>().speed);
}

// These functions will change the string of the current animation and use it to call anim.Play(string) when called upon.
void OnAnimChangeString(string animName)
{
    CmdChangeAnimString(animName);
}
[Command]
void CmdChangeAnimString(string clipName)
{
    SwitchCurrentAnimation(clipName);
}
void SwitchCurrentAnimation(string clipName)
{
    RpcChangeAnimString(clipName);
}
[ClientRpc]
void RpcChangeAnimString(string clipName)
{
    // QUESTION::: Does 'anim' need to be a SyncVar?????
    GetComponent<Animator>().Play(clipName);

}

//  This is purely for the Hand to Gun IK (working already) it makes hands hold gun correctly....
private void OnAnimatorIK(int layerIndex)
{
    GetComponent<Animator>().SetIKPosition(AvatarIKGoal.LeftHand, currentGun.leftGrip.position);
    GetComponent<Animator>().SetIKPositionWeight(AvatarIKGoal.LeftHand, 1.0f);

    GetComponent<Animator>().SetIKPosition(AvatarIKGoal.RightHand, currentGun.rightGrip.position);
    GetComponent<Animator>().SetIKPositionWeight(AvatarIKGoal.RightHand, 1.0f);

    GetComponent<Animator>().SetLookAtPosition(headLookTransform.position);
    GetComponent<Animator>().SetLookAtWeight(1.0f, 0f);
}
}

```

ORIGINAL QUESTION:

Hello again I am attempting to make a very basic multiplayer networked game using Unity. Right now to keep it fairly simple I just want to be able to have multiple players join the world and be able to walk around.

My problem arises because I am using the velocity of the player to adjust the animation speed. So if the player isn't moving the animation speed is 0, etc.

At one point i thought i had it working with ClientRPC calls, but I have since written more code (I added side stepping as well as forward backwards animations) and it seems to not work again.

The current code seems to be working great for the local client but not at all changing the animation speed on the remote clients, it just stays at 1.0f.

I'd be very grateful if someone can look at this code and tell me what I've done wrong. I've made this error and been stuck at this very point on other projects I've worked on. Heres the code. Thanks!

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

public class Player_mp : NetworkBehaviour {
CharacterController characterCont;
Animator anim;
public float walkSpeed, sideSpeed, turnSpeed, aimSpeed;
Vector3 inputInWorldSpace;
public Gun currentGun;
public Transform headLookTransform, gunShoulderRestTransform;
public string walkAnim, walkBackAnim, strafeLeftAnim, strafeRightAnim, turnLeftAnim, turnrightAnim, jumpAnim, runAnim, runBackAnim;
public GameObject bulletPrefab;

float animationSpeed;
Vector3 velLocalised;

public override void OnStartClient()
{
    characterCont = GetComponent<CharacterController>();
    anim = GetComponent<Animator>();
}

void FixedUpdate () {
    if (!isLocalPlayer)
    {
        return;
    }

    float mouseX = Input.GetAxis("Mouse X");
    float mouseY = Input.GetAxis("Mouse Y");
    transform.SetPositionAndRotation(transform.position, Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y + (mouseX * turnSpeed * Time.deltaTime), transform.eulerAngles.z));

    if (Input.GetMouseButtonDown(0))
    {
        CmdFireBullet();
    }

    Vector3 inputs = new Vector3(Input.GetAxis("Horizontal") * walkSpeed * Time.deltaTime, 0, Input.GetAxis("Vertical") * sideSpeed * Time.deltaTime);
    inputInWorldSpace = transform.TransformVector(inputs);

    gunShoulderRestTransform.eulerAngles = new Vector3(gunShoulderRestTransform.eulerAngles.x, transform.eulerAngles.y, transform.eulerAngles.z);
    gunShoulderRestTransform.Rotate(mouseY, 0, 0);

    velLocalised = transform.InverseTransformVector(characterCont.velocity);

    if (isServer)
    {

        // select current clip depending on input (would rather do it by the velocity if i could get it to work!):
        if (inputs.z > 0)
        {
            animationSpeed = velLocalised.z;
            RpcSetAnimClip(walkAnim);
        }
        else if (inputs.z < 0)
        {
            animationSpeed = velLocalised.z;
            RpcSetAnimClip(walkBackAnim);
        }
        else if (inputs.x > 0)
        {
            animationSpeed = velLocalised.x;
            RpcSetAnimClip(strafeRightAnim);
        }
        else if (inputs.x < 0)
        {
            animationSpeed = velLocalised.x;
            RpcSetAnimClip(strafeLeftAnim);
        }
        else
        {
            animationSpeed = velLocalised.z;
        }
        RpcSetAnimSpeed(animationSpeed);
    }
}

private void LateUpdate()
{
    if (!isLocalPlayer)
    {
        return;
    }

    characterCont.Move(inputInWorldSpace);

}

[Command]
void CmdFireBullet()
{
    GameObject bullet = Instantiate(bulletPrefab);
    NetworkServer.Spawn(bullet);
    Vector3 bulletForce = currentGun.transform.forward * currentGun.bulletForce;
    bullet.GetComponent<Bullet>().Fire(currentGun.bulletSpawn.transform.position, currentGun.bulletSpawn.transform.eulerAngles, bulletForce);

}

[ClientRpc]
void RpcSetAnimSpeed(float animSpeed)
{
    if (animSpeed < 0)
    {
        animSpeed *= -1;
    }
    anim.speed = animSpeed;
}
[ClientRpc]
void RpcSetAnimClip(string clipName)
{
    anim.Play(clipName);
}
[ClientRpc]
void RpcSetAnimSpeedAndClip(float animSpeed, string clipName)
{
    if (animSpeed < 0)
    {
        animSpeed *= -1;
    }
    anim.speed = animSpeed;

    anim.Play(clipName);
}

private void OnAnimatorIK(int layerIndex)
{
    anim.SetIKPosition(AvatarIKGoal.LeftHand, currentGun.leftGrip.position);
    anim.SetIKPositionWeight(AvatarIKGoal.LeftHand, 1.0f);

    anim.SetIKPosition(AvatarIKGoal.RightHand, currentGun.rightGrip.position);
    anim.SetIKPositionWeight(AvatarIKGoal.RightHand, 1.0f);

    anim.SetLookAtPosition(headLookTransform.position);
    anim.SetLookAtWeight(1.0f, 0f);
}
}

```

# Answer
> 1 votes
If your intent is to create a basic multiplayer networked game, I raccomend following this tutorial series

In the past, I had the same problem with some of my variables that I was not synchronizing. Try to add the `[SyncVar]` attribute to your `animSpeed` variable in order to synchronize it correctly. You should also test the animation speed in a new empty project, just to make sure everything works properly.

> To make your animation speed system network aware and working under Server authority, you need to use State Synchronization and a special member variable on networked objects called SyncVars. Network synchronized variables, or SyncVars, are indicated with the attribute \[SyncVar\]. For more information on SyncVars, please see the page on State

Your script is quite long so I decided to give you a basic solution to your problem:

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

public class Test : NetworkBehaviour
{
    public Animator anim;

    //Detects when a animation speed change happens and calls the appropriate function
    [SyncVar(hook = "OnChangeSpeed")]
    public float animSpeed = 1;

    private void Update() {
    if(islocalPlayer){//if player is mine
        animSpeed = GetComponent<Rigidbody>().velocity.magnitude;
    }
    }

    void OnChangeSpeed(float speed){
    if(islocalPlayer){//if player is mine
        CmdSetAnimSpeed(animSpeed);
    }
    }

    //This is a Network command, so the animation speed is done to the relevant GameObject
    [Command]
    void CmdSetAnimSpeed(float animSpeed)
    {
        //Apply animSpeed
        RpcSetAnimSpeed(animSpeed);
    }

    [ClientRpc]
    void RpcSetAnimSpeed(float animSpeed)
    {
        //Instead of multiplying -1 use Absolution
        // if (animSpeed < 0)
        // {
        //     animSpeed *= -1;
        // }
        animSpeed = Mathf.Abs(animSpeed);
        anim.speed = animSpeed;
    }
}

```

---
Tags: unity, multiplayer, unet
---


# Question
Title: Fps shoots up when sdl2 window is not on top
I am learning sdl2 with C++ from Lazy Foo Productions' tutorials. I am using a 5 year old retina mac book pro and xcode.

When reading this entry on calculating frame rate I noticed that when runing the application it would tend to 60 fps and the cpu and energy impact were very low, 2% and Low respectively, but when placing another window over it the fps would shoot up to 5000 along with cpu and energy impact, to 93% and High respectively.

Why is this happening? Is it because sdl2 just stops rendering all together when it is not on top of other windows? Or is it because the OS stops it from rendering?

# Answer
This is actually a complicated question to answer. There could be multiple possible explanations, including SDL2, the OS, and your graphics driver.

Either way, it sounds like Vsync is on which is intentionally limiting your frame rate which is limiting the executions of your core loop per second which is limiting your CPU usage. When rendering is turned off nothing restricts your core loop from executing as fast as it can and so your CPU usage spikes up.

If you want to experiment with turning off Vsync you can choose not to pass the `SDL_RENDERER_PRESENTVSYNC` flag into SDL\_CreateRenderer or (if you are using SDL2 with OpenGL) using SDL\_GL\_SetSwapInterval. If Vsync is still on it might be your graphics driver enforcing it, in which case you would have to configure your driver (this occurs in my case on Windows with SDL2 and the most recent Nvidia drivers for my card), but either way keeping Vsync on is probably good in general.

If you want your CPU usage to not spike whenever rendering is turned off, you could look into trying to inspect window events or check your window status using SDL\_GetWindowFlags. Most likely a flag like `SDL_WINDOW_SHOWN` is on whenever SDL is rendering and a flag like `SDL_WINDOW_HIDDEN` is on whenever it isn't. Every frame, if the 'is-not-displaying' flag is on, you could do something like `SDL_Delay(16)` to limit the frame rate at ~60fps when rendering is off.
> 1 votes

---
Tags: c++, sdl2
---


# Question
Title: How can I recreate the camera used in Swordigo game?
What sort of camera does the Android game (2.5D) Swordigo uses? Is it an orthogrpahic camera? I think it is an angled orthographic projection.

How can I recreate that sort of camera in Unity?

# Answer
This appears to be a perspective camera looking at the scene from the side. You can tell it's perspective because it shows the platforms from a slightly different angle depending on their position. The camera appears to be angled a slight bit downwards to better show off the top surfaces of the platforms.

An orthographic camera would render all plaforms in the exact same perspective (assuming they are all axis-aligned)
> 2 votes

---
Tags: unity, camera
---


title: Unity transform.position question

text:
# Question
Title: Unity transform.position question
Looking at example code for mesh deformation in unity

https://answers.unity.com/questions/746673/sine-wave-mesh-deform-with-different-directions.html

And i see theyve used

```
 public Transform Target1;
 public Transform Target2;

 void CalculateWaves ()
 {
     waves[0].Direction = Target1.position - transform.position;
     waves[1].Direction = Target2.position - transform.position;

```

And i dont understand the difference between Target1.position and transform.position without any reference to an instance.

Arent they the same thing. And how does transform.position function without a reference.

# Answer
The keyword 'transform' by itself is equivalent to writing 'this.transform'. In other words, it's the transform of the object that the script is on.
> 1 votes

---
Tags: unity, transformation
---


title: Rotating a Quad in Shader

text:
# Question
Title: Rotating a Quad in Shader
I'm working Opengles2 and I have a just a texture ID and a quad from an SDK and its shader, and I can not access their code, just the vertex and pixel shader.

The quad from the SDK is rotated and flipped. Is it possible to rotate the quad and flip its sides in shader ?

I don't have also the MVP matrix.

# Answer
> 0 votes
multiply the quad's vertex positions by a rotation matrix that will give you the orientation you want

# Answer
> 0 votes
For flipping and rotating the sides I would only change the texture coordinates.

Let's say that `(s, t)` are the texture coordinates, then assuming the texture covers the whole quad:

* change it to `(t, s)` for flipping the quad over its diagonal.
* change it to `(1 - t, s)` for flipping the quad over the `s` axis.
* change it to `(t, 1 - s)` for flipping the quad over the `t` axis.
* compse these for other results.

Read about symmetry group for a more philosophical view.

---
Tags: glsl, opengl-es
---


title: Split the camera into sections?

text:
# Question
Title: Split the camera into sections?
I have a layout for my game similar to this:

Where the light gray area is reserved for HUD elements and the dark gray area is reserved for the actual game. One function I want to offer in the dark gray area is the ability to zoom and move around, which works independently from the light gray area, meaning that no matter how far I zoom in/out or how far I move, the light gray area remains unaffected.

How can I do this without always taking the offset center into account? How can I completely separate the game play part and the HUD?

# Answer
> 1 votes
You can set your UI Canvas to render in ScreenSpace - Overlay, so it's mapped to the screen/window, layered on top of everything at the end of the rendering passes, independent of any camera.

You can configure your camera to render to only the bottom-right section of the screen/window by configuring its viewport rect in the inspector or via script.

For example, to render the camera's view to only the bottom-right 80% of the screen/windows's width & height, you'd configure the viewport rect to:

```
x: 0.2   width: 0.8
y: 0.0   height: 0.8

```

---
Tags: unity
---


# Question
Title: Variable Problem when coding the Player Movement in GameMaker Studio 1.4.9999
In oGirlTest object I have a Create and Step event.

Create:

```
///PLAYER OBJECT CREATE EVENT

//Maximum speed
spd = 4;

//Current movement speed
hspd = 0;
vspd = 0;

//Initialize basic properties
sprite_index = sPlayerDown;
image_speed = 0.5;

//Initialize basic movement state
state = move_state;

/*

Directions for top-down spritework.

0 = down
1 = left
2 = up
3 = right

*/

dir = 0;

```

Step:

```
///PLAYER OBJECT STEP EVENT

//Get input (keyboard/controller)
get_input();

//Execute the state (in the basic case, this calls the move_state script)
script_execute(state);

```

And 3 scripts that I've found and which I'm trying to understand in order to replicate the Undertale movement

get\_input

```
///get_input()

left = keyboard_check(vk_left);
right = keyboard_check(vk_right);
up = keyboard_check(vk_up);
down = keyboard_check(vk_down);

```

move\_state

```
///move_state

//Set animation speed for movement

image_speed = 1;

//Set default speed if there is no input

hspd = 0;
vspd = 0;

//Set speed to the direction you are pressing as long as there isn't a wall there
//Left and up take precedence

if(right && !place_meeting(x+1,y,Solid)) hspd = spd;

if(left && !place_meeting(x-1,y,Solid)) hspd = -spd;

if(down && !place_meeting(x,y+1,Solid)) vspd = spd;

if(up && !place_meeting(x,y-1,Solid)) vspd = -spd;

//Prevent stuttering if against a wall pressing opposite directional buttons

/*

SPECIAL NOTE: The following two lines of uncommented code deviate from Undertale.
In Undertale if you hold both UP & DOWN at the same time and run into a wall,
your character will stutter against it. Also if you hold LEFT & RIGHT and run into a wall,
your character will stop in its tracks. I fixed those issues in the next two lines of uncommented code.
if you truly wanted an exact replica of Undertale, replace them with this instead:

if(left && right && place_meeting(x-1,y,Solid))
{
hspd = 0;
vspd = 0;
}

This will replicate the stuttering effect and the freeze effect you encounter in Undertale.

*/

if(left && right && place_meeting(x-1,y,Solid)) hspd = 0;

if(up && down && place_meeting(x,y-1,Solid)) vspd = 0;

//Set the sprite to the appropriate direction

if(hspd < 0) sprite_index = sPlayerLeft;

if(hspd > 0) sprite_index = sPlayerRight;

if(vspd < 0) sprite_index = sPlayerUp;

if(vspd > 0) sprite_index = sPlayerDown;

//Sprite direction correction in special cases of multiple button press combinations

if((right && down && left && !up) || (right && down && !left && !up && dir == 1) || (left && down && !right && !up && dir == 3)) dir = 0;

if((down && left && up && !right) || (down && left && !up && !right && dir == 2) || (up && left && !right && !down && dir == 0)) dir = 1;

if((left && up && right && !down) || (left && up && !right && !down && dir == 3) || (right && up && !down && !left && dir == 1)) dir = 2;

if((up && right && down && !left) || (up && right && !down && !left && dir == 0) || (down && right && !up && !left && dir == 2)) dir = 3;

//Maintain sprite momentum by checking the previous sprite direction

if(hspd < 0 && dir == 1 && left) sprite_index = sPlayerLeft;

if(hspd > 0 && dir == 3 && right) sprite_index = sPlayerRight;

if(vspd < 0 && dir = 2 && up) sprite_index = sPlayerUp;

if(vspd > 0 && dir = 0 && down) sprite_index = sPlayerDown;

//Special checks when you're up against a wall trying to move against or along it

if(sprite_index == sPlayerLeft)
{
    if(place_meeting(x-1,y,Solid))
{
   if(vspd > 0 && !place_meeting(x,y+1,Solid))
   {
       sprite_index = sPlayerDown;
       dir = 3;
   }
   else if(vspd < 0 && !place_meeting(x,y-1,Solid))
   {
       sprite_index = sPlayerUp;
       dir = 1;
   }
   else
   {
       hspd = 0;
       vspd = 0;
   }
}
     else dir = 1;
}

    if(sprite_index == sPlayerRight)
    {
    if(place_meeting(x+1,y,Solid))
    {
        if(vspd > 0 && !place_meeting(x,y+1,Solid))
    {
        sprite_index = sPlayerDown;
       dir = 3;
    }
       else if(vspd < 0 && !place_meeting(x,y-1,Solid))
   {
       sprite_index = sPlayerUp;
       dir = 1;
   }
   else
   {
       hspd = 0;
       vspd = 0;
   }
 }
else dir = 3;
}

    if(sprite_index == sPlayerUp)
 {
    if(place_meeting(x,y-1,Solid))
 {
   if(hspd > 0 && !place_meeting(x+1,y,Solid))
   {
       sprite_index = sPlayerRight;
       dir = 3;
   }
   else if(hspd < 0 && !place_meeting(x-1,y,Solid))
   {
       sprite_index = sPlayerLeft;
       dir = 1;
   }
   else
   {
       hspd = 0;
       vspd = 0;
   }
 }
else dir = 2;
    }

    if(sprite_index == sPlayerDown)
    {
 if(place_meeting(x,y+1,Solid))
 {
   if(hspd > 0 && !place_meeting(x+1,y,Solid))
   {
       sprite_index = sPlayerRight;
       dir = 3;
   }
   else if(hspd < 0 && !place_meeting(x-1,y,Solid))
   {
       sprite_index = sPlayerLeft;
       dir = 1;
   }
   else
   {
       hspd = 0;
       vspd = 0;
   }
 }
else dir = 0;
}

//If there is no input, default to the idle state

if(hspd == 0 && vspd == 0)
{
sprite_index = sPlayerDown;
image_speed = 0.5;
}

//Actually move the player

move(Solid);

```

move

```
///move(collision_object)

var collision_object = argument0;

//Horizontal collisions

if(place_meeting(x+hspd,y,collision_object))
{
  while(!place_meeting(x+sign(hspd),y,collision_object))
 {
    x += sign(hspd);
 }
hspd = 0;
}

x += hspd;

//Vertical collisions

if(place_meeting(x,y+vspd,collision_object))
{
while(!place_meeting(x,y+sign(vspd),collision_object))
{
       y += sign(vspd);
}
  vspd = 0;
}

y += vspd;

```

And I'm getting the following error, for another person this script worked so I'm not sure what I'm doing wrong, I apologize for the wall of text, just trying to understand.

```
___________________________________________
############################################################################################
FATAL ERROR in
action number 1
of  Step Event0
for object oGirlTest:

Variable oGirlTest.Solid(100008, -2147483648) not set before reading it.
at gml_Script_move_state (line 150) -      if(place_meeting(x,y+1,Solid))
############################################################################################
--------------------------------------------------------------------------------------------
stack frame is
gml_Script_move_state (line 150)
called from - gml_Object_oGirlTest_StepNormalEvent_1 (line 7) -     script_execute(state);

```

# Answer
> 2 votes
`Place_meeting` is used to reach a different instance, so `Solid` should be the name of that instance it's colliding with. Your Gamemaker cannot recognise an instance named `Solid`(it's Case-sensitive), so it assumes that `Solid` is a custom variable from oGirlTest.

So you need to create (or rename) an instance that's called `Solid`, and use that as the walls you're colliding with. Once it can recognise an instance correctly, the text should be turn dark red.

---
Tags: animation, game-maker
---


# Question
Title: How do I rotate finger joints using controller input?
Suppose I have an index finger composed of 3 cubes which all contain Rigidbody which have `isKinematic` set to `true`. In a hierarchy they are the parent and children like this `cube1 -> cube2 -> cube3`

I want to control how my finger curls using the controller which outputs strength in range `0-1`, e.g. the ArrowUp button. Put simply, if I hold the up button, all the cubes would rotate around Z for 60 degrees. And if I release the button, it would rotate back to 0 degrees. (All degrees in between `0-60` are valid when the up strength is between `0-1`)

**How do I rotate the finger while also making it collide with other objects? For example, you could use the finger to kick a ball.**

If I don't care about the collision, I can just use `transform.Rotate(0, 0, buttonUpStrength)` in the `Update()` function and attach this script to all the cubes. But I care about collision and `rigidbody.MoveRotation()` is not enough because the position of each child will stay at the same absolute position when I use it. So I need to use `rigidbody.MovePosition()` to move the children relative to the parent also. But it's still not enough, the animation is not smooth, I want the animation to be smooth so I'm thinking that `AddTorque()` might be a better way out, but I don't know how to use it as `isKinematic=true` objects cannot be used with `AddTorque()`.

**What is a smarter, simpler way of making the finger kick a ball, without the finger being pushed back by the ball?**

This is how my finger looks like, it's just a cube.

This is my script, that I attach to all cubes, in the inspector, I set `cube1`'s angle to be 60. The children will just copy the angle of the parent:

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

public class TestJointRotation : MonoBehaviour
{
    public float angle;
    private Rigidbody rb, rbParent;
    private Vector3 originalPos;
    private Quaternion originalRot;

    void Start()
    {
        rb = GetComponent<Collider>().attachedRigidbody;
        if (transform.parent != null)
        {
            rbParent = transform.parent.GetComponent<Collider>().attachedRigidbody;
        }

        originalPos = transform.localPosition;
        originalRot = transform.localRotation;
    }

    void Update()
    {
        if (rbParent)
        {
            angle = rbParent.GetComponent<TestJointRotation>().angle;
        }

        var rotation = Quaternion.identity;
        if (rbParent)
            rotation *= rbParent.rotation;
        rotation *= originalRot;
        rotation *= Quaternion.Euler(0, 0, Input.GetAxis("Vertical") * angle);
        rb.MoveRotation(rotation);
        if (rbParent)
            rb.MovePosition(transform.parent.TransformPoint(originalPos));
    }
}

```

# Answer
I honestly think your approach is not good to solve this problem. For instance, one simple solution would be to just create a mesh, animate it in a 3d animation/modeling software and import it in Unity. You could then add colliders to the objects that compose the finger, play the animation that curls the finger and thus, kick the ball.

If you want to do this using Cubes, i guess the best way would be to create an origin point foreach cube to which its children can rotate around.

You would end up with something like this: `cube1->origin1->cube2->origin2->cube3`.
Now you can choose to animate the whole thing directly with Unity animation system or just attach a script that rotates the `origin1/origin2` game objects. Again, i would personally choose the first approach, but it depends on what you are planning on doing.
> 0 votes

---
Tags: unity, rotation, rigidbody, angles
---


# Question
Title: Optimization of animation for large quantity of objects
I have run into a problem where I need to animate plenty of circles just scaling up and down.

When I use animator, it needs 16ms per frame for 10000 circles. It drops fps significantly from 1000 to 30.

If I use scripts to scale the object, the result would be probably the same or worse, 10000 coroutines changing `localScale`.

What is the approach to this kind of problem? In agar io for example, they have done this without decreasing fps significantly, the game runs in a browser.

What are the optimizations that can be made?

Use of shaders? Chunks of objects animating as group at the same frame in animation?

# Answer
> 1 votes
The key to this problem is not rendering and animating something, that's not on the screen.

If the scaling happens based on a formula, then you could even stop changin their animation states, and only focus on the visible stuff.

Agario has an additional advantage, the server doesn't habe to render anything and the client doesn't have to calculate anything

# Answer
> 1 votes
When you use classic Unity game objects, then Unity is far better at processing a few complex game objects than a large number of simple game objects.

When your game needs the latter, then the new Unity Entity-Component-System architecture could help you. It requires to restructure your whole software architecture in ways which are too complex to adequately describe them in just one answer. But if you do it, then Unity will be able to process your game objects in a much more efficient way.

---
Tags: unity, animation, optimization
---


# Question
Title: Any way to merge plugins in RPG maker XP?
So I'm trying to merge together 2 mods into one game. One is Tankentai's SBS and the other is Cocoa's UMS.

I'm trying to merge the 2 into one game that includes the battle system from SBS, but the text boxes and whatnot from UMS. Is there any easy way to do this other than combing through all the script lines and copying them one at a time? I've tried to use this but it doesn't seem to do quite what I need it to do.

# Answer
> 1 votes
omg I just figured it out by pure luck. So I was trying to take the battle system and add it to the text system, which was complex. But then I thought to do it in *reverse order* and wow, now I feel stupid. So to do it in reverse order, go into the scripts file of the UMS, and copy the script subfile (idk what to call it) that is named UMS. Then go into the other game with the SBS, go into the scripts file, and paste the UMS subscript at the bottom of the subscripts list. Then copy the graphics from the UMS game into the graphics folder for the SBS game, and everything works perfectly!

---
Tags: rpg-maker-xp
---


# Question
Title: Is this bad design to have a static class which plays sound effects?
I am trying to make a audio manager. I want this audio manager to setup itself and be accessible from everywhere. So I made a static class that creates the audio sources when you need them. Is this bad design?

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

public static class AudioManager {

    private static bool musicIsSetup;
    private static AudioSource musicSource;
    private static bool sfxIsSetup;
    private static AudioSource sfxSource;

    public static void ManualSetup()
    {
        SetupSFXSystem();
        SetupMusicSystem();
    }

    public static void PlaySFX(AudioClip clip)
    {
        if (!sfxIsSetup) SetupSFXSystem();
        sfxSource.PlayOneShot(clip);
    }

    public static void PlayMusic(AudioClip clip)
    {
        if (!musicIsSetup) SetupMusicSystem();
        musicSource.clip = clip;
        if (!musicSource.isPlaying) musicSource.Play();
    }

    private static void SetupMusicSystem()
    {
        musicIsSetup = true;
        GameObject MusicHandler = new GameObject("MusicHandler");
        musicSource = MusicHandler.AddComponent<AudioSource>();
    }

    private static void SetupSFXSystem()
    {
        sfxIsSetup = true;
        GameObject SFXHandler = new GameObject("SFXHandler");
        sfxSource = SFXHandler.AddComponent<AudioSource>();
    }
}

```

# Answer
> 2 votes
The main limitation I see with this class is that it can not handle positional audio. It creates two audio sources at unspecified coordinates, which means they will get spawned at 0:0:0. The audio listener in the scene, however (unless you change that) is attached to the main camera. So depending on the position of the camera, sound effects will become louder, quieter and change their stereo panning.

If all the sound effects you play through this class are meant to be non-diegetic (the sound is made by the user interface, not a particular object in the game world), then you should make the audio handlers children of the main camera (or whichever objects has your audio listener). If you want a sound effect to be diegetic, then they should be played through an audio source attached to the object which makes the sound.

If your main intention of the class is that you don't want to deal with audio sources, then it might be useful to add a method `PlaySFX(AudioClip clip, GameObject source)`. The method should check if the source already has an AudioSource component, and when it has not, it adds one to it. It then plays the clip through the AudioSource of the game object. Your standard `PlaySFX(AudioClip clip)` method could then just call `PlaySFX(clip, Camera.current.gameObject);` to play a non-diegetic sound effect.

Another useful overload could be `PlaySFX(AudioClip clip, Vector3 position)` which creates an ephemeral game object with an AudioSource component at the given world-position which plays the clip and then self-destructs.

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


# Question
Title: How to blend biomes with procedural terrain
I'm working on a terrain generator. Through multiple noise functions, I'm able to create many kinds of terrain I like, but I'm having a bit of difficulty joining them together in a seamless fashion.

My first thought was to use a single noise call (calling it the mask) and then I could simply say things like:

```
if (returnVal < .1) GenerateBiome1();
if (returnVal < .2) GenerateBiome2();
if (returnVal < .3) GenerateBiome3();

```

and so on...

The issue here is that the height of the terrain doesn't blend together when doing this. If biome 1 was more mountainous and biome 2 was flat land, it's a drastic switch from one to the other and it looks atrocious.

My next thought was to attempt blending by giving a 'strength' to each biome based on what my mask noise returns. In C# code, it looks something like this at the moment:

```
static public float GetHeight(float X, float Z)
{
    float fRollingHills_Location = .25f, fRollingHills_Impact = .5f, fRollingHills = 0;
    float fMountains_Location = .75f, fMountains_Impact = .5f, fMountains = 0;

    float fMask = Game1.GetNoise2(0, X, Z, .01f);
    float fRollingHills_Strength = (fRollingHills_Impact - Math.Abs(fMask - fRollingHills_Location)) / fRollingHills_Impact;
    float fMountains_Strength = (fMountains_Impact - Math.Abs(fMask - fMountains_Location)) / fMountains_Impact;

    if (fRollingHills_Strength > 0) fRollingHills = fRollingHills_Strength * (Game1.GetNoise2(0, X, Z, .02f) * 10f + 10f);
    if (fMountains_Strength > 0) fMountains = fMountains_Strength * (Game1.GetNoise2(0, X, Z, .05f) * 25f + 10f);

    return fRollingHills + fMountains;
}

```

The issue I have here is that even for only two biomes, it's pretty important for me to manually choose the "location" and "impact" values to ensure I'm getting some combination of strengths to total 100% by the time it returns a value (if not, I get things like giant cliffs making the borders from one biome to another ugly and obvious).

I don't know if I can give a good true question here other than, **how should I actually be going about this?** While I've managed a few good looking maps, I feel like I'm going about this in an overly complicated way that still doesn't give me all the customization I'm looking for.

# Answer
3D Graphic with XNA Game Studio 4.0 has a chapter dedicated to this topic. It includes a complete process for generating the terrain and layering it with a variety of textures.

As luck would have it, that chapter is the sample provided by Packt on the book's page:

> In this chapter, we will focus on building a full 3D environment. We will start by creating a class that builds a terrain from a 2D image called a heightmap . We will make a number of improvements to the basic version of this class, allowing multiple textures across its surface through multitexturing and extra detail at close distances to its surface through a "detail texture". We will look at a technique called region growing to add plants and trees to the terrain's surface, and ﬁ nish by combining the terrain with our sky box, water, and billboarding effects to create a mountain scene..."

Sample chapter 7 pdf

Here's a summary of how they do it:

First, an image is used to generate a height map. Judging from the image, it looks like some sort of coherent noise function (Perlin noise, Simplex noise, value noise, etc) was used to generate the input image:

Next, they apply a technique they call multitexturing, which uses the red, green & blue channels of an input texture to draw additional textures onto the height map. In their example they use red for sand, blue for snow and green for rock. The remainder of the image is textured with a default such as grass:

At this point, the terrain looks okay at a distance, but if the camera gets too close the textures will blur. Increase the number of times the texture tiles will result in strobing where the high resolution texture flickers when scaled down & viewed at a distance. They solve these problems by applying a detail texture. The detail texture is essentially noise that is blended (multiplied in the pixel shader) to the terrain near the camera to fake the appearance of a higher resolution texture. Here's the noise texture they used:

Their final step is to add vegitation. Trees are added by randomly selecting locations & evaluating the slope. If the slope is too sttep, the site is rejected. Otherwise the location is used to add a tree billboard texture. Tufts of grass are added using a probablity map. Basically a random locations is selected & a random value is generated. If that random value is greater than the corresponding value in the probablity map, the site is reject. Otherwise a tuft of grass is added at that location.
> 3 votes

# Answer
While this is an old question, I feel like I have something useful to contribute.

The world generator I'm currently building uses two functions for each biome \\$i\\$:

1. The classical heightmap-function \\$biome\_i(x, y)\\$
2. A weight-function called \\$weight\_i(x, y)\\$.

To get the actual height of a biome the results of those functions are multiplied together: \\$elevation\_i(x, y) = biome\_i(x, y) \times weight\_i(x, y)\\$

The weight function (or strength, as the asker calls it), can be obtained by whatever means, some suggestions:

* Another noise function
* Distance from manually placed "biome control points"
* Results of some geological simulations like plate tectonics or whatever.

Simply adding all of the biome's height functions obtained this way results in the effects the asker mentioned. At coordinates where multiple biomes have big weights the terrain is extremely elevated.

The trick to solve this is to divide the final elevation by the sum of all heights.

The final heightmap function is $$ elevation(x, y)=\frac{\sum\_{i=0}^n (weight\_i(x, y)\*biome\_i(x, y))}{\sum\_{i=0}^n weight\_i(x, y)}$$.

This ensures a "real" weight sum of exactly 1 (100%) and results in the following properties:

1. For all coordinates \\$x\\$,\\$y\\$, \\$height(x, y)\\$ ist never higher than the highest \\$biome\_i(x, y)\\$
2. For all coordinates \\$x\\$,\\$y\\$, \\$height(x, y)\\$ ist never lower than the lowest \\$biome\_i(x, y)\\$
3. If all functions \\$biome\_i(x, y)\\$ and \\$weight\_i(x, y)\\$ are continuous, so is \\$height(x, y)\\$

For heightmaps, this means the final elevation will always be between the highest and lowest possible elevation of each of the individual biomes, and there will **never be discontinuities**.

In the question's example, this may look like this:

```
static public float GetHeight(float X, float Z)
{
    float fRollingHills_Location = .25f, fRollingHills_Impact = .5f, fRollingHills = 0;
    float fMountains_Location = .75f, fMountains_Impact = .5f, fMountains = 0;

    float fMask = Game1.GetNoise2(0, X, Z, .01f);
    float fRollingHills_Strength = (fRollingHills_Impact - Math.Abs(fMask - fRollingHills_Location)) / fRollingHills_Impact;
    float fMountains_Strength = (fMountains_Impact - Math.Abs(fMask - fMountains_Location)) / fMountains_Impact;

    if (fRollingHills_Strength > 0) fRollingHills = fRollingHills_Strength * (Game1.GetNoise2(0, X, Z, .02f) * 10f + 10f);
    if (fMountains_Strength > 0) fMountains = fMountains_Strength * (Game1.GetNoise2(0, X, Z, .05f) * 25f + 10f);

    return (fRollingHills + fMountains)/(fRollingHills_Strength + fMountains_Strength);
}

```
> 3 votes

---
Tags: c#, procedural-generation, terrain, perlin-noise
---


# Question
Title: Logic at a low framerate with interpolated rendering at higher framerate
It takes too much processing power to do game logic on every rendered frame (60fps), so what if I made my game save frames?

It would actually calculate important stuff 20 times a second, and the render loop just interpolates the 2 frames in-between to make it look like 60fps.

Is this a good idea for improving game performance?

# Answer
**Yes**. Some games do just that.

Even more, they run at constant (e.g. 10) fps for game logic and render at whatever fps they can. Solves whole bunch of problems between machines with different processing powers.
> 2 votes

---
Tags: 3d, optimization, frame-rate, fixed-timestep
---