# Question
Title: How can I replace an object with a prefab so the prefab will be at the same position of the gameobject?
I have some doors in the scene, each door at another position. I took one of the doors added to it a light and made a prefab of the door.

Now I want to replace all the other doors with the prefab.

Example of the door with the light I added and this door is also a prefab:

And this is example of another door that is not yet replaced by the prefab door with the light:

I want to replace this door with the prefab door with the light at the first screenshot. The question is if there is a easy way to do the replace ?

I have more doors that I want to replace.

# Answer
Is there already an prefab for your door without the light? Then you simply have to add the light to this prefab in the scene and click on apply at the right top inside the inspector. This would normally update all objects inside your scene. If you don't have a prefab, add a light to the door without a light with the attributes you want, drag and drop the door into your prefab folder.

Take each door, that doesn't have light, click on the small symbol inside the inspector at the tansform component and choose 'copy component values' (its right at the top at each component, looks like a small gear symbol). Drag and drop your prefab with the light inside the scene and click on the symbol inside the inspector once again but this time, click on 'paste component values'. This should put the prefab exacty at the position where your 'old' door is located. Delete the door without the lighting of course afterwards.

If you also want doors without the lighting, make sure to have a prefab for this as well, otherwise if you change something inside the prefab (deleting the light for example), all prefab copies inside your scene will lose the lighting as well!

Greetings!
> 3 votes

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


# Question
Title: OpenGL vector rotation matrix to a given point
I have a sphere with a radius of .5

The sphere is centred at 0,0,0

I am now trying to place items around my sphere based on a given x,y,z on the surface of the sphere.

My items have been draw/created in such a way that they are positioned on the surface when translated to 0,0,0 because their centre offset has been positioned at the centre of the sphere.

What I need is some help with the calculation needed to get the correct glRotate values so that my icons will show at the correct x,y,z on the surface.

To help explain what I mean, here is a picture:

So you can see 0,0,0 at the centre, and also rotating around the same point is the blue line, This represents the rotation of my object. The green part is the visible part of my item, and so will draw on the surface of the sphere.

I have everything ready to go for this, in that I can already draw my items in this manner, however I am not able to correctly calculate the rotation.

With the default rotation of Identity my items will draw on the bottom of the sphere.

In summary I am looking for something like this:

glRotate = GetRotationForSurface(X,Y,Z);

I hope that's clear, this is a bit tricky to explain.

Thanks,

# Answer
Got it, thanks to euclideanspace

This is how its done:

```
//Representing the centre vector of my sphere
V1.X = 0;
V1.Y = -1;
V1.Z = 0;

//Representing where we want to rotate to
V2.X = SurfaceTargetX
V2.Y = SurfaceTargetY
V2.Z = SurfaceTargetZ

//Normalise both
//V1.Normalize(); Already normalised
V2.Normalize();

//Angle
angle = acos(V1.dotProduct(V2));

//Axis
axis = (V1.crossProduct(V2)).normalize();

//OpenGL Rotation (Note the angle needs to be in degrees)
glRotatef(angle * (180.0f / 3.14f), axis.x, axis.y, axis.z);

```

And your done, only 1 rotation needed.
> 1 votes

---
Tags: opengl, rotation, vector, matrix
---


title: Native C++ console screen buffer

text:
# Question
Title: Native C++ console screen buffer
I'm trying to display a game in the console window using a screen buffer but cannot compile it.

I have this simple code:

```
#include <Windows.h>
#include <iostream>
#include <thread>

int main() {
  const int width = 120, height = 40;

  wchar_t* screen = new wchar_t[width * height];
  HANDLE console = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
  SetConsoleActiveScreenBuffer(console);
  DWORD bytesWritten = 0;

  while (true) {
    for (int i = 0; i < width * height; i++) screen[i] = L' ';
    wsprintf(&screen[width + 5], L"Testing");

    WriteConsoleOutputCharacter(console, screen, width * height, {0, 0}, &bytesWritten);
    Sleep(1000 / 30);
  }

  return 0;
}

```

It won't compile, getting two errors:

> test.cpp:16:44: error: cannot convert 'wchar\_t\*' to 'LPSTR {aka char\*}' for argument '1' to 'int wsprintfA(LPSTR, LPCSTR, ...)'

and

> test.cpp:18:87: error: cannot convert 'wchar\_t\*' to 'LPCSTR {aka const char\*}' for argument '2' to 'BOOL WriteConsoleOutputCharacterA(HANDLE, LPCSTR, DWORD, COORD, PDWORD)'

How can I get this working and how to do it even better?

I'm using g++ 6.3.0 to compile.

Thanks!

# Answer
> 0 votes
Changed `WriteConsoleOutputCharacter()` to `WriteConsoleOutputCharacterA()`, ditched `wsprintf()`, changed `screen[]` type from `wchar_t*` to `char*` and made my own helper function for displaying on the screen and now it works perfectly!

```
void toScreen(char*& screen, const int index, const char* text) {
  for (int i = 0; i < strlen(text); i++)
    screen[index + i] = text[i];
}

```

---
Tags: c++, text-based
---


# Question
Title: Quaternion based camera pitch freaking out, and Z-axis drift
This is the code I use to control my (first person) camera's movement and rotation. Translation successfully keeps orientation in mind, so that up and left and such are always in the expected directions, and 'mouselook' controlling rotation around the Y (yaw) and X (pitch) axes starts out working fine as well.

My problems are two-fold;

First, rotating around the Y and X axes slowly builds up rotational drift around the Z axis. Now what I think I need to do to correct this is to keep track of an additional 'up' vector, and to rotate the quaternion so that the camera's up direction always coincides with this up vector (which would only change when intended, instead of by drift). But I have no idea how to go about doing this.

The second problem is more clearly a bug. When rotating around the Y (yaw) axis, the rotation around the X (pitch) axis starts to freak out. At Y 180 degrees, the up and down motion of the camera's pitching are precisely inverted. And at 90 degree Y angles from the starting orientation, it's as if pitch has become roll instead, rotating around the Z axis.

So, how do I 'roll up', and what's going on with the pitching?

```
glm::quat mOrientationQuaternion;
glm::vec3 mPositionVector;
glm::mat4 mViewMatrix;

/*
 *  Takes a translation value for each axis, turns it into a vector, then
 *  rotates that vector by the current orientation in the quaternion, before
 *  adding the result to the position vector.
 */
void Camera::translate(float x, float y, float z)
{
    glm::vec3 translation(x, y, z);
    translation = translation * mOrientationQuaternion;
    mPositionVector += translation;
}

/*
 *  Takes three angles in degrees, and creates a quaternion via an
 *  intermediate vector to represent their rotations. Then the orientation
 *  quaternion is multiplied by this new rotation quaternion to get the new
 *  orientation.
 */
void Camera::rotate(float x, float y, float z)
{
    glm::vec3 angles(glm::radians(-x), glm::radians(y), glm::radians(z));
    glm::quat rotation(angles);
    mOrientationQuaternion = glm::normalize(mOrientationQuaternion * rotation);
}

/*
 *  Creates the view matrix from the orientation quaternion, then translates
 *  it by the position vector.
 */
void Camera::buildViewMatrix()
{
    mViewMatrix = glm::mat4_cast(mOrientationQuaternion);
    mViewMatrix = glm::translate(mViewMatrix, mPositionVector);
}

```

# Answer
> 2 votes
Firstly, I would recommend working in radians, not degrees. Whilst the GLM library can work with degrees, it was designed with radians in minds(this is a very minor issue though, so work with what you feel comfortable in).

Secondly, If you wish to use quaternions to store data as *orientation*, then you must understand conceptually, what a quaternion is. Forget about the mathematics for a moment, because that is less important at this point, and to be honest, if you're using glm, you only need to know how to use it, and not how it works under the hood.

A quaternion represents a rotation around an axis, in three dimensions. I wouldn't recommend trying to use it for anything else, such as for translation, as that will just confuse the issue, and make your code difficult to understand six months from now.

Consider the following code:

```
glm::vec3 mPositionVector;
glm::quat mOrientation;
glm::vec3 mAngularVelocityRadS; //this is actually a set of Euler angles

```

This has all the information you will ever need to compute a stable view matrix.

If you wish to rotate the camera in any direction, simply do this:

```
glm::quat rotateCam(glm::quat orientation, glm::quat angularVelocityS, float deltaTime) {
    //first we compute the new orientation after 1 second.
    glm::quat rot1s = angularVelocityS * orientation;
    // Now we know what the rotation would be after 1 second
    // We can now perform spherical linear interpolation
    // to compute something in between.
    return glm::normalize(glm::mix(orientation, rot1s, deltaTime));
}

```

We now have a very nice general function for rotations, but how do we use that?

```
void camera::update(float dt) {
    glm::quat rotation = glm::quat(mAngularVelocityRadS);
    mOrientation = rotateCam(mOrientation, mAngularVelocityRadS, dt);
    // Now we have our orientation, we can compute the view matrix
    mViewMatrix = glm::mat4_cast(glm::inverse(mOrientationQuaternion));
    mViewMatrix = glm::translate(mViewMatrix, mPositionVector);
}

```

if you wish to rotate the camera by a fixed amount, then just multiply the orientation by the rotation, without slerp needed:

```
mOrientation = rotation * mOrientation;

```

If you want to reset the orientation:

```
mOrientation = glm::quat(glm::vec3(.0f,.0f,.0f));

```

# Answer
> 0 votes
I've managed to fix the pitch-freakout issue, but at this point this is pretty much 'Programming by Coincidence', as I don't understand the math well enough to know -why- my changes fix the problem.

First, I get the quaternion's inverse before turning it into a view matrix. Now intuitively I'd guess this has to do with the difference between 'rotating the camera' (which doesn't actually exist), and 'rotating the entire world in the opposite direction', but I might be completely off-base here;

```
void Camera::buildViewMatrix()
{
    mViewMatrix = glm::mat4_cast(glm::inverse(mOrientationQuaternion));
    mViewMatrix = glm::translate(mViewMatrix, mPositionVector);
}

```

Doing so messes up translation, so next I change translation to translate by the inverse of the orientation quaternion. At this point I'm completely lost as to the mathematical how-and-why;

```
void Camera::translate(float x, float y, float z)
{
    glm::vec3 translation(x, y, z);
    translation = translation * glm::inverse(mOrientationQuaternion);
    mPositionVector += translation;
}

```

And finally I had to flip the x and y axes' signs during rotation;

```
void Camera::rotate(float x, float y, float z)
{
    glm::vec3 angles(glm::radians(x), glm::radians(-y), glm::radians(z));
    glm::quat rotation(angles);
    mOrientationQuaternion = glm::normalize(mOrientationQuaternion * rotation);
}

```

The final result is a camera that pitches and yaws by mouse motion, and that translates in all directions intuitively.

Because of how much guesswork and experimentation this has been, I have no idea how efficient this code is, so it might be doing incredibly wasteful things that'd make any mathematician groan. Any comments on whether taking the inverse twice (or normalizing after every rotation) is a good or bad idea would be most welcome. :-)

Having fixed one issue, I still need to figure out how to get rid of the axial drift. For now I still assume this is something I can handle with a dedicated Up vector and a corrective z rotation back to Up after every rotation around the other axes.

---
Tags: c++, 3d, mathematics, quaternion, glm
---


title: Getting ip address of connected network

text:
# Question
Title: Getting ip address of connected network
I have two scripts, a server script and a client script. I built two parts of the app, one with the client script and another one with the server script. I put both apps on devices, connected two devices with the local network and run the server. First I wrote this line in the client to get the IP of the server device:

```
NetworkManager.singleton.networkAddress

```

But it gives me the IP of the client device. Do you have any solution to this problem?

Thanks.

# Answer
You cannot simply get the server's IP from the client. There is no way to do that without using some kind of service discovery system.

That is why we have server browsers in most games. They provides a list of IPs of servers to the clients with some info about them. Now how do the server browser have the IPs of all the running servers ? Well, servers register themselves to the server browser when they start. The server browser being accessible by a domain name or a fixed IP.

Server discovery system in a local area network :

* The server listens to a specific port (say 25000) for incoming UDP packets.
* The clients broadcasts a UDP packet to port 25000 asking for servers addresses.
* Every server that receive that UDP packet will answer with their own IP address (though the IP address can be retrieved in the packet header) and some additionnal information if necessary.
* The client then receives the IP of all available servers on the same LAN.
* If the client has not received any answers after a certain amount of time (60 sec for example) it concludes no server is available on the LAN.

This solution has flaws :

* UPD is not reliable (but you can build a reliable system on top of UDP)
* It only works if everybody is on the same LAN
* It only works if UDP broadcast is possible (some networks may disable broadcasts)
* It is not secure (man in the middle, packet forgery, etc...)

Best luck with your project.
> 1 votes

# Answer
The normal way to find servers is via DNS. Servers have well-known names such as "gamedev.stackexchange.com", and by the process of name lookup you find the an IPv4 or IPv6 address for them.

If you need more than a single server, there are a few options. There are DNS-based solutions (google.com isn't a single server, you get varying IP addresses when looking it up in DNS). Alternatively, you can have a single top-level server that keeps track of the "player lobby" and redirects gamers to game servers with spare capacity.
> 0 votes

---
Tags: unity-networking
---


# Question
Title: How can i collide two bodies without filtering(collision filtering)?
I have two bodies with fixtures. One is platform or ground and other is the player itself.I want to collide the player to the platform without bit filtering.How can i do that?I can see the rectangular ghost layer(like a rectangular box) and the box2d falling through it.I want the box2d to collide.

create player

# Answer
set`fdef.isSensor = false;`
and `fixdef.isSensor = false;`

> A sensor shape collects contact information but never generates a collision response.

See FixtureDef documentation:
https://libgdx.badlogicgames.com/ci/nightlies/docs/api/com/badlogic/gdx/physics/box2d/FixtureDef.html#isSensor

You can use `.isSensor = true;` for an attack range of monster or a poisoned area
> 3 votes

---
Tags: java, libgdx, collision-detection, box2d, platformer
---


# Question
Title: Using Lerp to zoom in on an object inside an if statement
I'm trying to zoom in on an object once the raycast hits it in the Update method, I am using the Lerp method to make the camera movement smoother but it's not working properly. The object only lerps for a single frame.

I also tried using a coroutine but the result is still the same. I can't simply just place it outside the if statement because I only need to change the field of view once the raycast hits an object.

Here's a sample of my code :

```
if (Input.GetMouseButtonDown(0))
        {
            ray = mainCam.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {

                if (hit.collider.tag.Equals("Building"))
                {

                    SetTarget(hit);
                    mainCam.fieldOfView = Mathf.Lerp(mainCam.fieldOfView, newFOV, Time.deltaTime * smooth);
                }
            }
         }

```

# Answer
This solution seemed to work for me; I used lerp outside the `if (Input.GetMouseButtonDown(0))` statement and created a variable "shouldLerp" that tracks when the camera is in the new position (ie the field of view property has changed).
> 0 votes

# Answer
Your problem is very similar to this previous question "Why is Vector3.MoveTowards only working on a single frame?"

Like this other user, you're testing for a fleeting event: `GetMouseButtonDown(0)` is true only for one frame when the mouse button is pressed. If the mouse button is held down or released, it will be false on subsequent frames, so the outermost `if` block will be skipped entirely.

Inside this fleeting event response, you're calling on a math function as though you were kicking off a fire-and-forget tweening library - assuming that once you've called `Lerp` once, it will somehow remember to keep calling itself every frame afterward until the transition you're trying to complete is done.

But `Lerp` is not a coroutine that says "continue modifying this variable a little each frame until the destination value is reached" - it's just a math expression, like `+` or `*`, that says "blend these two numbers by this amount." It has no knowledge of transitions or frames. Every time you want to get new numbers out of it, you need to call it again.

But, we can easily use it to *make* the fire-and-forget tweening function you seem to want, like so:

```
// Store a reference to our coroutine so we can interrupt it if needed.
Coroutine _zooming;

// "IEnumerator" marks this as a routine that can pause & automatically
// resume at a later time (say, advancing a little each frame)
IEnumerator ZoomTo(float newFov, float duration) {

    // Remember where we started from, so we can smoothly control the curve.
    float originalFov = mainCam.fieldOfView;
    float speed = 1f/duration;
    float t = 1.0f;

    // Loop multiple times until we've used up our full duration.
    do {
       // Blend one more step toward our destination value.
       t = Mathf.Clamp01(t - speed * Time.deltaTime);
       mainCam.fieldOfView = Mathf.Lerp(newFov, originalFov, t*t);

       // Return control to the main game thread for one frame,
       // then resume next frame.
       yield return null;
    } while(t > 0f);

    // We've finished our work, so clear the stored coroutine to signal this.
    _zooming = null;
}

```

You'll note I'm doing something a little funny here and lerping from a weight of 1 down to 0, instead of 0 to 1. That's because I noticed you were using a formula that gives an ease-out blend, where the change starts fast and slows down toward the end (although your formula was implemented incorrectly - see here for how to fix that). So here I've mimicked that by using `t*t` as the blending weight, which levels off as it approaches zero.

Now when you want to kick off your zoom, you can write:

```
if(_zooming == null)
    _zooming = StartCoroutine(ZoomTo(newFov, zoomDuration));

```

The `if` above ensures the previous zoom has to finish before you can start a new one. Or, if you want to interrupt a zoom-in-progress instead, you can write

```
if(_zooming != null)
    StopCoroutine(_zooming);
_zooming = StartCoroutine(ZoomTo(newFov, zoomDuration));

```
> 3 votes

# Answer
The problem in your method is that lerp interpolates a value between 0 and 1 as a third parameter. In your method, Mathf.lerp, your third parameter is "constant" (it is not but close to constant). And because of that, your zoom only lerps one time. You need a time counter that goes from 0 to 1 to properly work.

```
if (Input.GetMouseButtonDown(0))
    {
        ray = mainCam.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {

            if (hit.collider.tag.Equals("Building"))
            {

                SetTarget(hit);
                mainCam.fieldOfView = Mathf.Lerp(mainCam.fieldOfView, newFOV, timeCounter);
                timeCounter += Time.deltaTime*smooth; //<-- Declare and initialize this variable
            }
        }
     }

```

You will need to add some logic and play with the smooth variable to achieve some other effects. (Sorry about my english, i don't usually write :D)
> 0 votes

---
Tags: unity, camera, lerp
---


# Question
Title: How can I add a glow effect around a pair of wings in Unity without post processing?
Basically I want to use post processing and then I found a tutorial to achieve my goal. However, the artist want a pure shader to achieve this, without any C# script hanging in the main camera. Any idea to implement?

# Answer
You don't normally would do something like this with post processing, as post processing is only able to render the whole scene. But you want a specific object/objects to be rendered with a glowing shader.

This would normally only work with C#, but Unity lately updated the engine and added a Graph Shader Editor.

Here's a tutorial that goes into the direction in what you try to achieve:

Click

EDIT:

Like mentioned in my comment, you either update to Unity2018, which is something i would definitely do, considering all the new features that are coming with it. Migration works just fine, just make sure to have a copy of your original project.

It comes with the Graph Shader Editor, ProBuilder and much more. The only way to achieve a outside glowing is by using a shader that calculates the outside and make it appear to glow. If you want certain parts to be emissive inside your mesh (for example a panel with a monitor and you want to add a glowing effect to the monitor) you need to cut out these parts for the UV map and drop them inside the emission input. This way you will have full control over this area and can literally do almost anything, from special shaders to simple emission effects. Read more about emission here

If you want the glowing effect around a character/object, you have to do it by either buying a shader or making one by yourself, which isnt that hard with the new Graph Editor.

GreetingS!
> -1 votes

# Answer
You can achieve this with an edge shader, if you google about you will find some code for sure. If you are in Unity2018 you can use shader graph editor if you are afraid of coding shader code.
> -1 votes

---
Tags: unity, shaders
---


title: SDL2 only renders a single image

text:
# Question
Title: SDL2 only renders a single image
As an attempt to learn SDL on C, I decided to try and create a simple Pong program using it. My problem now is that of the textures I've given it, two paddles and a ball, only the ball is rendered. It fails to render anything else even if it is the only thing I give. I have no idea why this happens. I've spend more than an hour trying to fix this, scanning each line of code line by line multiple times. I even went as far as renaming a paddle image to ball, and only then did it render. I think there is a deep and most likely stupid flaw to how I implemented it, so I attached some of the code below:

```
texRacquet1 = SDL_CreateTextureFromSurface(rend, racquet1);
SDL_FreeSurface(racquet1);
texRacquet2 = SDL_CreateTextureFromSurface(rend, racquet2);
SDL_FreeSurface(racquet2);
texBall = SDL_CreateTextureFromSurface(rend, ball);
SDL_FreeSurface(ball);

```

This creates textures from the images and sets them to the pointers I defined.

```
SDL_Rect sracquet1;
SDL_Rect sracquet2;
SDL_Rect sball;

//Gets scale and dimensions of textures
SDL_QueryTexture(texRacquet1, NULL, NULL, &sracquet1.w, &sracquet1.h);
sracquet1.w * 6;
sracquet1.h * 6;
SDL_QueryTexture(texRacquet2, NULL, NULL, &sracquet2.w, &sracquet2.h);
sracquet2.w * 6;
sracquet2.h * 6;
SDL_QueryTexture(texBall, NULL, NULL, &sball.w, &sball.h);
sball.w * 6;
sball.h * 6;

```

This queries the textures and finds the dimensions of the shape, adding them to their respective structure members from the rectangle structures set for each texture. It also dilates it by 6 so it can be seen.

```
    //Copies textures to buffer and presents them to screen
    SDL_RenderCopy(rend, texRacquet1, NULL, &sracquet1);
    SDL_RenderCopy(rend, texRacquet2, NULL, &sracquet2);
    SDL_RenderCopy(rend, texBall, NULL, &sball);
    SDL_RenderPresent(rend);

```

Finally, this draws the textures and presents them to the screen. Or it should. It only renders the ball, and if I remove that line, it just does nothing.

Full code:

```
//Speed of ball in pixels per second
const int SPEED = 300;
const int WINDOW_WIDTH = 640;
const int WINDOW_HEIGHT = 480;

int main(int argc, char* argv[])
{
    //Creates pointers to various game elements
    const char *window1_title = "Pong";

    Uint32 render_flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC;

    SDL_Window  *window1 = NULL;
    SDL_Renderer*rend = NULL;
    SDL_Surface *racquet1 = NULL;
    SDL_Surface *racquet2 = NULL;
    SDL_Surface *ball = NULL;
    SDL_Texture *texRacquet1 = NULL;
    SDL_Texture *texRacquet2 = NULL;
    SDL_Texture *texBall = NULL;
    int request_quit = 0;

    //Initializes SDL
    SDL_Init(SDL_INIT_EVERYTHING);

    //Prints error message if SDL fails to initalize
    if(SDL_Init(SDL_INIT_EVERYTHING) != 0)
    {
        printf("Failed to initialize SDL: %s\n", SDL_GetError());

        //Quits SDL
        SDL_Quit();
        return 1;
    }
    /*
    Creates centered window with the window title pointer, width, height, and
    no flags
    */
    window1 = SDL_CreateWindow(window1_title, SDL_WINDOWPOS_CENTERED,
                                              SDL_WINDOWPOS_CENTERED,
                                      WINDOW_WIDTH, WINDOW_HEIGHT, 0);

    //Prints error message if SDL failed to create window1
    if(!window1)
    {
        printf("Failed to initalize window: %s\n", SDL_GetError());
        SDL_Quit();
        return 1;
    }

    //Initializes renderer
    rend = SDL_CreateRenderer(window1, -1, render_flags);
    if(!rend)
    {
        printf("Failed to initialize renderer: %s\n", SDL_GetError());

        //Destroys window
        SDL_DestroyWindow(window1);
        SDL_Quit();
        return 1;
    }

    SDL_SetRenderDrawColor(rend, 255, 255, 255, 255);

    //Loads images
    racquet1 = IMG_Load("resources/raquet1.png");
    racquet2 = IMG_Load("resources/raquet2.png");
    ball = IMG_Load("resources/ball.png");

    //Tests if an image didn't load
    if(!racquet1 && !racquet2 && !ball)
    {
        printf("Failed to load images\n");

        //Destroys initalized components and quits
        SDL_DestroyRenderer(rend);
        SDL_DestroyWindow(window1);
        SDL_Quit();
        return 1;
    }

    //Texturizes loaded images

    texRacquet1 = SDL_CreateTextureFromSurface(rend, racquet1);
    SDL_FreeSurface(racquet1);

    texRacquet2 = SDL_CreateTextureFromSurface(rend, racquet2);
    SDL_FreeSurface(racquet2);

    texBall = SDL_CreateTextureFromSurface(rend, ball);
    SDL_FreeSurface(ball);

    // Errors if sprites fail to texturize
    if(!texRacquet1 && !texRacquet2 && !texBall)
    {
        printf("Failed to texturize images\n");
        SDL_DestroyRenderer(rend);
        SDL_DestroyWindow(window1);
        SDL_Quit();
        return 1;
    }

    // Structs to hold coordinate positions
    SDL_Rect xracquet1 = {0, 0, 0, 0};
    SDL_Rect xracquet2 = {0, 0, 0, 0};
    SDL_Rect xball = {0, 0, 0, 0};

    //Gets scale and dimensions of textures
    SDL_QueryTexture(texRacquet1, NULL, NULL, &xracquet1.w, &xracquet1.h);
    SDL_QueryTexture(texRacquet2, NULL, NULL, &xracquet2.w, &xracquet2.h);
    SDL_QueryTexture(texBall, NULL, NULL, &xball.w, &xball.h);

    // Set ball to the middle of the window
    xball.x = (WINDOW_WIDTH - xball.w) / 2;
    xball.y = (WINDOW_HEIGHT - xball.h) / 2;

    // Set racquet 1 to the left side of the window
    xracquet1.x = 0;
    xracquet1.y = (WINDOW_HEIGHT - xracquet1.h) / 2;

    // Set racquet 2 to the right side of the window
    xracquet2.x = (WINDOW_WIDTH - xracquet2.w);
    xracquet2.y = (WINDOW_HEIGHT - xracquet2.h) / 2;

    //Initializes game loop
    while(!request_quit)
    {
        //Processes events
        SDL_Event event;
        while(SDL_PollEvent(&event))
        {
            switch(event.type)
            {
                case SDL_QUIT:
                    request_quit = 1;
                    break;
            }
        }

        //Clears screen for renderer
        SDL_RenderClear(rend);

        //Copies textures to buffer and presents them to screen
        SDL_RenderCopy(rend, texRacquet1, NULL, &xracquet1);
        SDL_RenderCopy(rend, texRacquet2, NULL, &xracquet2);
        SDL_RenderCopy(rend, texBall, NULL, &xball);
        SDL_RenderPresent(rend);

        //Waits 1/60th of a second for a 60 fps lock
        SDL_Delay(1000 / 60);
    }
    SDL_DestroyTexture(texRacquet1);
    SDL_DestroyRenderer(rend);
    SDL_DestroyWindow(window1);
    SDL_Quit();
    return 0;
}

```

# Answer
The problem was that the SDL\_Rect objects that's supposed to hold position and size data for the textures were receiving incorrect data. Because of this, the textures were rendered outside the window borders (with incorrect sizes) and were therefore not visible at the execution of the program.

Code below has been tested and fully works.

If the error remains, check with other image file(s), re-download SDL, SDL\_Image etc.

```
#include <SDL.h>
#include <SDL_image.h>

#include <iostream>

//Speed of ball in pixels per second
const int SPEED = 300;
const int WINDOW_WIDTH = 640;
const int WINDOW_HEIGHT = 480;

int main(int argc, char* argv[])
{
    //Creates pointers to various game elements
    const char *window1_title = "Pong";

    Uint32 render_flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC;

    SDL_Window  *window1 = nullptr;
    SDL_Renderer*rend = nullptr;
    SDL_Surface *racquet1 = nullptr;
    SDL_Surface *racquet2 = nullptr;
    SDL_Surface *ball = nullptr;
    SDL_Texture *texRacquet1 = nullptr;
    SDL_Texture *texRacquet2 = nullptr;
    SDL_Texture *texBall = nullptr;
    int request_quit = 0;

    //Initializes SDL
    SDL_Init(SDL_INIT_EVERYTHING);

    //Prints error message if SDL fails to initalize
    if(SDL_Init(SDL_INIT_EVERYTHING) != 0)
    {
        printf("Failed to initialize SDL: %s\n", SDL_GetError());

        //Quits SDL
        SDL_Quit();
        return 1;
    }
    /*
    Creates centered window with the window title pointer, width, height, and
    no flags
    */
    window1 = SDL_CreateWindow(window1_title, SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        WINDOW_WIDTH, WINDOW_HEIGHT, 0);

    //Prints error message if SDL failed to create window1
    if(!window1)
    {
        printf("Failed to initalize window: %s\n", SDL_GetError());
        SDL_Quit();
        return 1;
    }

    //Initializes renderer
    rend = SDL_CreateRenderer(window1, -1, render_flags);
    if(!rend)
    {
        printf("Failed to initialize renderer: %s\n", SDL_GetError());

        //Destroys window
        SDL_DestroyWindow(window1);
        SDL_Quit();
        return 1;
    }

    SDL_SetRenderDrawColor(rend, 255, 255, 255, 255);

    //Loads images
    racquet1 = IMG_Load("resources/raquet1.png");
    racquet2 = IMG_Load("resources/raquet2.png");
    ball = IMG_Load("resources/ball.png");

    //Tests if an image didn't load
    if(!racquet1 && !racquet2 && !ball)
    {
        printf("Failed to load images\n");

        //Destroys initalized components and quits
        SDL_DestroyRenderer(rend);
        SDL_DestroyWindow(window1);
        SDL_Quit();
        return 1;
    }

    //Texturizes loaded images

    texRacquet1 = SDL_CreateTextureFromSurface(rend, racquet1);
    SDL_FreeSurface(racquet1);

    texRacquet2 = SDL_CreateTextureFromSurface(rend, racquet2);
    SDL_FreeSurface(racquet2);

    texBall = SDL_CreateTextureFromSurface(rend, ball);
    SDL_FreeSurface(ball);

    // Errors if sprites fail to texturize
    if(!texRacquet1 && !texRacquet2 && !texBall)
    {
        printf("Failed to texturize images\n");
        SDL_DestroyRenderer(rend);
        SDL_DestroyWindow(window1);
        SDL_Quit();
        return 1;
    }

    // Structs to hold coordinate positions
    SDL_Rect xracquet1 = {0, 0, 0, 0};
    SDL_Rect xracquet2 = {0, 0, 0, 0};
    SDL_Rect xball = {0, 0, 0, 0};

    //Gets scale and dimensions of textures
    SDL_QueryTexture(texRacquet1, NULL, NULL, &xracquet1.w, &xracquet1.h);
    SDL_QueryTexture(texRacquet2, NULL, NULL, &xracquet2.w, &xracquet2.h);
    SDL_QueryTexture(texBall, NULL, NULL, &xball.w, &xball.h);

    // Set ball to the middle of the window
    xball.x = (WINDOW_WIDTH - xball.w) / 2;
    xball.y = (WINDOW_HEIGHT - xball.h) / 2;

    // Set racket 1 to the left side of the window
    xracquet1.x = 0;
    xracquet1.y = (WINDOW_HEIGHT - xracquet1.h) / 2;
    xracquet1.w = xracquet1.w;
    xracquet1.h = xracquet1.h;

    // Set racket 2 to the right side of the window
    xracquet2.x = (WINDOW_WIDTH - xracquet2.w);
    xracquet2.y = (WINDOW_HEIGHT - xracquet2.h) / 2;
    xracquet2.w = xracquet2.w;
    xracquet2.h = xracquet2.h;

    //Initializes game loop
    while(!request_quit)
    {
        //Processes events
        SDL_Event event;
        while(SDL_PollEvent(&event))
        {
            switch(event.type)
            {
            case SDL_QUIT:
                request_quit = 1;
                break;
            }
        }

        //Clears screen for renderer
        SDL_RenderClear(rend);

        //Copies textures to buffer and presents them to screen
        SDL_RenderCopy(rend, texRacquet1, NULL, &xracquet1);
        SDL_RenderCopy(rend, texRacquet2, NULL, &xracquet2);
        SDL_RenderCopy(rend, texBall, NULL, &xball);
        SDL_RenderPresent(rend);

        //Waits 1/60th of a second for a 60 fps lock
        SDL_Delay(1000 / 60);
    }
    SDL_DestroyTexture(texRacquet1);
    SDL_DestroyRenderer(rend);
    SDL_DestroyWindow(window1);
    SDL_Quit();
    return 0;
}

```
> 2 votes

# Answer
After careful examination, the (extremely stupid) answer to my problem was a simple misspelling.

```
racquet1 = IMG_Load("resources/raquet1.png");

```

Should've been:

```
racquet1 = IMG_Load("resources/racquet1.png");

```

Everything works now. Thank you @Naith for helping me figure this out.
> 0 votes

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


# Question
Title: How to create "border" around tilemap in Unity
I'm setting up a 2D arena game, and I'm trying to implement an ability for tilemaps to be highlighted (on hover). I've already managed to get a Vector3 of the hovered tile using rays and WorldToCell, but I don't know how to actually "highlight" the tilemap by creating a border around it. Is this possible or am I going to need some other sprite that has a highlighted version of the tile? Here's my layout now:

I need it to look something like this:

# Answer
Create an sprite object that is the highlight. Make sure the location of the object corresponds to the center of the object. Then set its position as CellToWorld, using the WorldToCell result you already have.

This is the easiest way to do this. There would be another way using tiles themselves, but that is more complicated and honestly, you don't really need anything more complicated than this, since only one tile will be highlighted at a time.
> 2 votes

---
Tags: unity, tilemap
---


# Question
Title: Screen blending from Photoshop in Unity 2D
I want to use "Screen blending" from Photoshop in my Unity 2D game, I want to use that for exported lights from 3D Max that we want to use in our game, Now for a sample, I have my sprite that I want to mask it :

And I also have a mask for it :

Now my question is how to make this in Unity like this :

Can make this happen by Sprite mask?

# Answer
My original answer to this (check the edit history if you're curious) said that this couldn't be done in a single pass due to the way GPUs' semi-programmable blending stage works, and offered a more complicated work-around with multiple drawing passes, as well as similar-looking alternatives with non-screen blend modes.

But apparently I overlooked the fact that the formula for screen blending can be rearranged into a format that fits the GPU just fine!

$$\begin{align} & 1 - (1 - \text{source}) \cdot (1 - \text{destination})\\ =& 1 + (\text{source} - 1) \cdot (1 - \text{destination})\\ =& 1 + (\text{source} - \text{source} \cdot \text{destination} - 1 + \text{destination} )\\ =& \text{source} - \text{source} \cdot \text{destination} + \text{destination}\\ =& \text{source} \cdot (1 -\text{destination}) + \text{destination}\\ \end{align}$$

So, we can write this in Unity ShaderLab as:

```
Blend OneMinusDstColor One

```

(`OneMinusDstColor` is the \\$(1 -\text{destination})\\$ term, implicitly multiplied by the source colour since it's in the first slot. The `One` gets multiplied by the destination colour since it's in the second slot, and the two results get added together)

So with that, here's a full Unity shader that implements screen blending in one pass, without my previous over-engineering:

```
Shader "Unlit/ScreenBlend"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Transparent" "Queue"="Transparent"}
        LOD 100

        Blend OneMinusDstColor One
        Zwrite Off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);

                col.rgb *= col.a;
                return col;
            }
            ENDCG
        }
    }
}

```

(I've shown this applied to a basic Unlit shader, but you can make a copy of the standard Unity Sprite shader and replace the blend formula with the one above to achieve the same effect, while also getting all the features you're used to with sprites)

---

In the original answer, I also shared a few other options, compared with OP's images here:

* On the left is a correct Screen blend mode
* Second from the left is standard alpha/layer blending, using the flare image from the question as a greyscale texture, with alpha from greyscale.

Note the slight dark fringing around the edges: these are spots where the white of the flare blends partway to black in the colour channels, so we blend the resulting grey onto the background.

What we have here is effectively a pre-multiplied alpha image being blended with a non-premultiplied-alpha shader. You could fix this by making the shader use a correct pre-multiplied blend function (`Blend One OneMinusSrcAlpha`), or...
* The next image shows a way to correct this while using standard blending. I've used the lens flare image as the alpha channel of an image, and filled the colour channels with pure white. This way, we're always blending pure white with varying degrees of transparency, rather than darker greys.

You can see the falloff isn't too different than the Screen blending, it's just a bit brighter overall, so applying a levels or curves adjustment to the alpha channel might be all you need for a screen-like effect in this case, with no custom shader.
* Lastly, on the right, is additive blending. This tends to look quite good for light/glow effects, though it does exaggerate colours as you can see here in the bright blue halo it gets over a blue background.
> 4 votes

---
Tags: unity, sprites
---


title: Point inside Oriented Bounding Box?

text:
# Question
Title: Point inside Oriented Bounding Box?
I have an OBB2D class based on SAT.

This is my point in OBB method:

```
public boolean pointInside(float x, float y)
{
    float newy = (float) (Math.sin(angle) * (y - center.y) + Math.cos(angle) *
            (x - center.x));
    float newx = (float) (Math.cos(angle) * (x - center.x) - Math.sin(angle) *
            (y - center.y));
    return (newy > center.y - (getHeight() / 2)) &&
            (newy < center.y + (getHeight() / 2))
            && (newx > center.x - (getWidth() / 2)) &&
            (newx < center.x + (getWidth() / 2));
}

public boolean pointInside(Vector2D v)
{
    return pointInside(v.x,v.y);
}

```

Here is the rest of the class; the parts that pertain:

```
public class OBB2D
{
   private Vector2D projVec = new Vector2D();
   private static Vector2D projAVec = new Vector2D();
   private static Vector2D projBVec = new Vector2D();
   private static Vector2D tempNormal = new Vector2D();
   private Vector2D deltaVec = new Vector2D();
   private ArrayList<Vector2D> collisionPoints = new ArrayList<Vector2D>();

// Corners of the box, where 0 is the lower left.
   private  Vector2D corner[] = new Vector2D[4];

   private Vector2D center = new Vector2D();
   private Vector2D extents = new Vector2D();

   private RectF boundingRect = new RectF();
   private float angle;

    //Two edges of the box extended away from corner[0].
   private  Vector2D axis[] = new Vector2D[2];

   private double origin[] = new double[2];

   public OBB2D(float centerx, float centery, float w, float h, float angle)
    {
       for(int i = 0; i < corner.length; ++i)
       {
           corner[i] = new Vector2D();
       }
       for(int i = 0; i < axis.length; ++i)
       {
           axis[i] = new Vector2D();
       }
       set(centerx,centery,w,h,angle);
    }

   public OBB2D(float left, float top, float width, float height)
  {
       for(int i = 0; i < corner.length; ++i)
       {
           corner[i] = new Vector2D();
       }
       for(int i = 0; i < axis.length; ++i)
       {
           axis[i] = new Vector2D();
       }
       set(left + (width / 2), top + (height / 2),width,height,0.0f);
   }

   public void set(float centerx,float centery,float w, float h,float angle)
   {
       float vxx = (float)Math.cos(angle);
       float vxy = (float)Math.sin(angle);
       float vyx = (float)-Math.sin(angle);
       float vyy = (float)Math.cos(angle);

           vxx *= w / 2;
           vxy *= (w / 2);
           vyx *= (h / 2);
           vyy *= (h / 2);

           corner[0].x = centerx - vxx - vyx;
           corner[0].y = centery - vxy - vyy;
           corner[1].x = centerx + vxx - vyx;
           corner[1].y = centery + vxy - vyy;
           corner[2].x = centerx + vxx + vyx;
           corner[2].y = centery + vxy + vyy;
           corner[3].x = centerx - vxx + vyx;
           corner[3].y = centery - vxy + vyy;

           this.center.x = centerx;
           this.center.y = centery;
           this.angle = angle;
           computeAxes();
           extents.x = w / 2;
           extents.y = h / 2;

           computeBoundingRect();
   }

   //Updates the axes after the corners move.  Assumes the
   //corners actually form a rectangle.
   private void computeAxes()
   {
       axis[0].x = corner[1].x - corner[0].x;
       axis[0].y = corner[1].y - corner[0].y;
       axis[1].x = corner[3].x - corner[0].x;
       axis[1].y = corner[3].y - corner[0].y;

       // Make the length of each axis 1/edge length so we know any
       // dot product must be less than 1 to fall within the edge.

       for (int a = 0; a < axis.length; ++a)
       {
        float l = axis[a].length();
        float ll = l * l;
        axis[a].x = axis[a].x / ll;
        axis[a].y = axis[a].y / ll;
           origin[a] = corner[0].dot(axis[a]);
       }
   }

   public void computeBoundingRect()
   {
       boundingRect.left = JMath.min(JMath.min(corner[0].x, corner[3].x), JMath.min(corner[1].x, corner[2].x));
       boundingRect.top = JMath.min(JMath.min(corner[0].y, corner[1].y),JMath.min(corner[2].y, corner[3].y));
       boundingRect.right = JMath.max(JMath.max(corner[1].x, corner[2].x), JMath.max(corner[0].x, corner[3].x));
       boundingRect.bottom = JMath.max(JMath.max(corner[2].y, corner[3].y),JMath.max(corner[0].y, corner[1].y));
   }

   public void set(RectF rect)
   {
       set(rect.centerX(),rect.centerY(),rect.width(),rect.height(),0.0f);
   }

    // Returns true if other overlaps one dimension of this.
    private boolean overlaps1Way(OBB2D other)
    {
        for (int a = 0; a < axis.length; ++a) {

            double t = other.corner[0].dot(axis[a]);

            // Find the extent of box 2 on axis a
            double tMin = t;
            double tMax = t;

            for (int c = 1; c < corner.length; ++c) {
                t = other.corner[c].dot(axis[a]);

                if (t < tMin) {
                    tMin = t;
                } else if (t > tMax) {
                    tMax = t;
                }
            }

            // We have to subtract off the origin

            // See if [tMin, tMax] intersects [0, 1]
            if ((tMin > 1 + origin[a]) || (tMax < origin[a])) {
                // There was no intersection along this dimension;
                // the boxes cannot possibly overlap.
                return false;
            }
        }

        // There was no dimension along which there is no intersection.
        // Therefore the boxes overlap.
        return true;
    }

    public void moveTo(float centerx, float centery)
    {
        float cx,cy;

        cx = center.x;
        cy = center.y;

        deltaVec.x = centerx - cx;
        deltaVec.y  = centery - cy;

        for (int c = 0; c < 4; ++c)
        {
            corner[c].x += deltaVec.x;
            corner[c].y += deltaVec.y;
        }

        boundingRect.left += deltaVec.x;
        boundingRect.top += deltaVec.y;
        boundingRect.right += deltaVec.x;
        boundingRect.bottom += deltaVec.y;

        this.center.x = centerx;
        this.center.y = centery;
        computeAxes();
    }

    // Returns true if the intersection of the boxes is non-empty.
    public boolean overlaps(OBB2D other)
    {
        if(right() < other.left())
        {
            return false;
        }

        if(bottom() < other.top())
        {
            return false;
        }

        if(left() > other.right())
        {
            return false;
        }

        if(top() > other.bottom())
        {
            return false;
        }

        if(other.getAngle() == 0.0f && getAngle() == 0.0f)
        {
            return true;
        }

        return overlaps1Way(other) && other.overlaps1Way(this);
    }

    public Vector2D getCenter()
    {
        return center;
    }

    public float getWidth()
    {
        return extents.x * 2;
    }

    public float getHeight()
    {
        return extents.y * 2;
    }

    public void setAngle(float angle)
    {
        set(center.x,center.y,getWidth(),getHeight(),angle);
    }

    public float getAngle()
    {
        return angle;
    }

    public void setSize(float w,float h)
    {
        set(center.x,center.y,w,h,angle);
    }

    public float left()
    {
        return boundingRect.left;
    }

    public float right()
    {
        return boundingRect.right;
    }

    public float bottom()
    {
        return boundingRect.bottom;
    }

    public float top()
    {
        return boundingRect.top;
    }

    public RectF getBoundingRect()
    {
        return boundingRect;
    }

    public boolean overlaps(float left, float top, float right, float bottom)
    {
        if(right() < left)
        {
            return false;
        }

        if(bottom() < top)
        {
            return false;
        }

        if(left() > right)
        {
            return false;
        }

        if(top() > bottom)
        {
            return false;
        }

        return true;
    }

    public static float distance(float ax, float ay,float bx, float by)
    {
      if (ax < bx)
        return bx - ay;
      else
        return ax - by;
    }

    public Vector2D project(float ax, float ay)
    {
        projVec.x = Float.MAX_VALUE;
        projVec.y = Float.MIN_VALUE;

      for (int i = 0; i < corner.length; ++i)
      {
        float dot = Vector2D.dot(corner[i].x,corner[i].y,ax,ay);

        projVec.x = JMath.min(dot, projVec.x);
        projVec.y = JMath.max(dot, projVec.y);
      }

      return projVec;
    }

    public Vector2D getCorner(int c)
    {
        return corner[c];
    }

    public int getNumCorners()
    {
        return corner.length;
    }

    public boolean pointInside(float x, float y)
    {
        float newy = (float) (Math.sin(angle) * (y - center.y) + Math.cos(angle) *
                (x - center.x));
        float newx = (float) (Math.cos(angle) * (x - center.x) - Math.sin(angle) *
                (y - center.y));
        return (newy > center.y - (getHeight() / 2)) &&
                (newy < center.y + (getHeight() / 2))
                && (newx > center.x - (getWidth() / 2)) &&
                (newx < center.x + (getWidth() / 2));
    }

    public boolean pointInside(Vector2D v)
    {
        return pointInside(v.x,v.y);
    }

    public ArrayList<Vector2D> getCollsionPoints(OBB2D b)
    {

        collisionPoints.clear();
        for(int i = 0; i < corner.length; ++i)
        {
            if(b.pointInside(corner[i]))
            {
                collisionPoints.add(corner[i]);
            }
        }

        for(int i = 0; i < b.corner.length; ++i)
        {
            if(pointInside(b.corner[i]))
            {
                collisionPoints.add(b.corner[i]);
            }
        }
        return collisionPoints;
    }
};

```

What could be wrong? When I getCollisionPoints for 2 OBBs I know are penetrating, it returns no points.

Thanks

```
public boolean pointInside(float x, float y)
{
    float xx = (x - center.x);
    float yy =  (y - center.y);
    float newx = (float) (xx * Math.cos(angle) - yy * Math.sin(angle));
    float newy = (float) (xx * Math.sin(angle) + yy * Math.cos(angle));
    return (newy > center.y - (getHeight() / 2)) &&
            (newy < center.y + (getHeight() / 2))
            && (newx > center.x - (getWidth() / 2)) &&
            (newx < center.x + (getWidth() / 2));
}

```

# Answer
> 2 votes
You need to swap sin & cos in the assignment of newy.

```
rx = x * cos(angle) - y * sin(angle)
ry = x * sin(angle) + y * cos(angle)

```

# Answer
> 0 votes
Maybe this can help, this works for me (unit tested). C++ but should be transferable.

```
bool point_inside( T x, T y ) const {
  vector2<T> center( ( _left + _right ) / 2, ( _top + _bottom ) / 2 );
  vector2<T> extents( center._x - _left, center._y - _bottom );
  vector2<T> center_to_point( x - center._x, y - center._y );
  vector2<T> right_dir( wc::cos( _angle ), wc::sin( _angle ) );
  T          horizontal_projection = right_dir.dot( center_to_point );
  if ( horizontal_projection < -extents._x || horizontal_projection > extents._x ) {
    return false;
  }

  vector2<T> up_dir( -right_dir._y, right_dir._x );
  T          vertical_projection = up_dir.dot( center_to_point );
  if ( vertical_projection < -extents._y || vertical_projection > extents._y ) {
    return false;
  }

  return true;
}

```

---
Tags: 2d, java, mathematics, physics
---


title: TCP For RTS Game?

text:
# Question
Title: TCP For RTS Game?
My RTS game abides by the lockstep system so keeping everyone up to date is import and guaranteeing the safe arrival of packets would make my life a lot easier. With that said, I still need decent speed so players won't have to wait too long before commands are registered, preferably under 300ms. Basically, my system is set up like this: 10 packets are sent out every second by the server which will be based upon for players' simulations. Every time a player makes a command, a packet is sent to the server as well so a player with 180 apm would send 3 packets a second. I plan to have 16 player games. Is it plausible to have a player-hosted server send out 10 packets and take in 3 using TCP and have the round trip times for most players be under 300ms?

I think the 10p/s out for each player seems kind of harsh so this could use UDP but is it at least possible for players to send their commands using TCP and get responses in reasonable times?

To sum up my concerns over using TCP, if a client has 200ms RTT using UDP, how much will his RTT be using TCP? In addition, how much more bandwidth will it use?

# Answer
TCP guarantees delivery, and when there are problems that aspect will cause hangups as the whole thing stops to make sure everything got through. If it's going to be just a few dropped packets here and there, UDP will keep your speed up.

Here's a detailed explanation of why TCP should not be used: https://gafferongames.com/post/udp\_vs\_tcp/

It also links to information on how to use UDP properly. Here's small bit to get you started:

> Firstly, TCP is a stream protocol, so you just write bytes to a stream, and TCP makes sure that they get across to the other side. Since IP is built on packets, and TCP is built on top of IP, TCP must therefore break your stream of data up into packets. So, some internal TCP code queues up the data you send, then when enough data is pending the queue, it sends a packet to the other machine.
>
> This can be a problem for multiplayer games if you are sending very small packets. What can happen here is that TCP may decide it’s not going to send data until you have buffered up enough data to make a reasonably sized packet to send over the network.
> 1 votes

# Answer
If you have a lock-step game, that means that every packet MUST be delivered, intact and executed in order. Otherwise lockstep can not continue. This means that even if you go for UDP, you will still have to reinvent the wheel of TCP by yourself (guaranteed sequence, guaranteed delivery, etc.). I would not want to spend my time on this instead of coding the actual game.

Better go for TCP and keep your code simpler. Let the proven technology take care of deliveries. (and turn off packet batching, which is on by default in many implementations. E.g. in Overbyte that is achieved by setting `[wsoTcpNoDelay] // Send packets ASAP (disables Nagle's algorithm)`)

As for mitigating lag - do the client-side confirmation of players commands immediately (so player has feedback) and do the actual command once other peers accept it - that lag won't be very noticeable.

P.S. Above said based on our own RTS experience with up to 12 players on a map, running up to 30 ticks/second.
> 0 votes

---
Tags: multiplayer, server, rts, udp
---


# Question
Title: Monogame Move objects while having a moving 2D camera
I am writing my first game. In this game, I have a `heroEntity` object, which has fields:

```
float X {get; set;}
float Y {get; set;}
Monogame.Extended.Camera2D Camera {get; set;}

```

Since I have some background, I use `Camera.Move()` instead of moving my `heroEntity` object (which I put at the center of the `Camera.BoundingRectangle` after each frame)

Now, I also a `List<BulletEntity> Bullets` (those bullets also have **X** and **Y** properties) and they should also **move independently** of the `heroEntity.Camera` object. When I simply implement movement of the camera and bullets independently, there is an impression that my bullets are kind of *shaking*.

How can I fix that?

# Answer
Problem was solved by just changing the FPS from 30 to 60

In your Initialize() method

```
TargetElapsedTime = TimeSpan.FromSeconds(1d / 60d)

```

Also, don’t forget to set the `IsFixedTimeStep` property to `true`
> 0 votes

# Answer
I am not familiar with monogame, but if you have to code the Input manager yourself, then you might run into polling issues.
That is, if the bullets only shake when the hero moves.
I forgot why that issue occurs, but i am sure it has to do with code that is processed in between events. --\> first poll all keyboard data and then simulate. Not both in between.
Of course there is also the possibility that your framerate is kind of out of sync.
If you can, i suggest implementing a sleep every frame for about 0.5 or 1 sec and observe the jitter closer.
> 0 votes

---
Tags: c#, camera, movement, monogame, monogame-extended
---


# Question
Title: how to avoid Z- axis gravity from affecting my mobile game?
I am making a mobile car game, and as it is a serious game for upper limb rehabilitation. The mobile is attached to the forearm of the patient, hence the forearm movement will move and rotate the car. All i need is to prevent earth gravity from moving my object, I tried to subtract 1g from the acceleromete's reading in z- axis, but the movement did not go rightly. Any help?

# Answer
> 1 votes
You got close to one of the possible solutions. However, there are may possible solutions to your problem. I've described two of them. I hope you'll find at least one of them satisfactory.

1. Subtracting from the z-axis only works when the phone is aligned perfectly to the world (perpendicular to gravity) since the accelerator is measuring Z relative to the phone, not the world. You'll need to figure out the orientation of the phone relative to the earth's gravity.

Example:

```
acceleration = [ax, ay, ay]  // accelerometer reading

q                            // quaternion corresponding to the orientation

gravity = [0, 0, -9.81]      // gravity on Earth in m/s^2

a_rotated = rotate(acceleration, q) // rotate the measured acceleration into
                                    // the Earth frame of reference

user_acceleration = a_rotated - gravity

```

Source: https://stackoverflow.com/questions/18252692/gravity-compensation-in-accelerometer-data

2. However, you could also solve this issue in the game itself. If the car is driving on a flat surface, you could use a physics engine to push the car back onto the driving surface, or calculate at what height you should place the car at every point on the surface and then align the car to the angle of the surface (calculated by rotating the car to align with the surface normal).

---
Tags: unity, c#, mobile, accelerometer, serious-games
---


# Question
Title: Unity tilemap spacing between imported sprites
What am I missing here? Is Unity's tilemap limited to size 32x32?

I am trying to understand why my sprites in my Unity tilemap are spaced apart from one another such that if I paint them into the scene the tiles are centered in the grid's cells in an undesirable way.

I want my grid to be size 8x8 pixels and I want my sprite sheet to be imported in with `pixels per unit` set to 32 so that it matches the pixel size of my character and the rest of my art.

I've tried adjusting the import size setting and that did nothing. I've tried changing the scaling of the grid, but that results in a smaller grid with smaller sprites still centered in the cells.

The only thing I've found that "fixes" this is to re-slice my sprite sheet at 32x32, but that results in tiles that are larger than what I am aiming for.

# Answer
I am not sure why the padding in those cells appears, but I found the necessary steps to achieve the results I wanted. Evidently the default size of the tilemap is based on a size of 32 pixels.

Steps to setting up your tilemap.

1) **import** the sprite sheet using **the same** `pixels per unit` that you intend on using when slicing your sprite sheet. For me, I import in at size 8 and sliced at size 8.

2) create your tilemap pallete using that same size again or "automatic" sizing. For me, size 8.

3) drag your sliced sheet into your newly created pallete so that the tiles are created.

4) The default size of the Unity tilemap is 32 pixels by 32 pixels. I never set this, so I am assuming that it the default size. Since that is the default size, scale your tilegrid gameobject by a ratio equal to `your desired size / 32`. For me, that meant scaling to 0.25 using the Transform.

5) your tile sizes should now fit the cell size and the pixel size should be correct.
> 1 votes

---
Tags: unity, sprites, tilemap, import
---


# Question
Title: Javascript-How to create a moving bullet animation from canvas
the bullet cant see to move at all

```
function bullet() {
    this.x=playerx;
    this.y=playery;
    this.init=function(){
        this.x+=5;
        draw(this.x,this.y,10,10,"blue");
        console.log(this.x)
    }
}

```

in another function

```
if(k.keyCode==17){
    bullets=new bullet();
    bullets.init();
}

```

# Answer
> 1 votes
You need to update the bullet's position each frame. So you should add an `update` function to the bullet constructor. And in it, update the `x` property so that the bullet moves in the direction the player is facing.

Here a working example:

```
// Get the canvas and stuff
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

var width = canvas.width;
var height = canvas.height;

// The secret woobler
var shouldWooble = false;
var woobler = document.querySelector('button');
woobler.addEventListener('click', function() {
  if (shouldWooble) {
    shouldWooble = false;
    woobler.innerHTML = "Turn on Wooble";
  } else {
    shouldWooble = true;
    woobler.innerHTML = "Turn off Wooble";
  }
});

// This way when we draw the bullet it's always blue
ctx.fillStyle = "blue";

// Our sprites container
var sprites = [];

function bullet() {
  this.x = 0;
  this.y = height / 2;
  this.alive = true;
  this.init = function() {
    // Update position
    this.x += 5;
    sprites.push(this);
  };
  this.render = function() {
    if (this.alive) {
      // Render only if the bullet is alive (aka on screen)
      ctx.fillRect(this.x, this.y, 10, 10);
    }
  };
  this.update = function() {
    if (this.alive) {
      // update the x value only if the object is alive
      this.x += 7;
      if (shouldWooble) {
        this.y = (Math.sin(this.x) * 34) + (height / 2);
      }

      // Check if the bullet is on screen
      if (this.x > width) {
        this.alive = false;
      }
    }
  };
}

function createBullet() {
  bullets = new bullet();
  bullets.init();
}

document.addEventListener('keyup', function(event) {
  // If space bar is pressed
  if (event.keyCode == 32) {
    createBullet();
  }
  event.preventDefault();
});

document.addEventListener('click', function() {
  createBullet();
});

function loop() {
  // Very simple and naive game loop
  update();
  render();
  requestAnimationFrame(loop);
}

function update() {
  // Here we update all the sprites
  // THe reverse for loop is faster
  for (var ix = sprites.length; ix--;) {
    sprites[ix].update();
  }
}

function render() {
  // Here we render all the sprites after clearing the screen
  ctx.clearRect(0, 0, width, height);
  for (var ix = sprites.length; ix--;) {
    sprites[ix].render();
  }
}

// Start the game
requestAnimationFrame(loop);
```

```
canvas {
  border: 1px solid black;
}
```

```
<p>Click on the canvas below, or press spacebar</p>
<canvas width="340" height="340"></canvas>
<button type="button">Turn on Wooble</button>
```

---
Tags: javascript, html5
---


title: Draw the HUD just once on the canvas

text:
# Question
Title: Draw the HUD just once on the canvas
I am not able to draw only one HUD of my game on a separate canvas, so I do not have to redraw it to each frame, I have four functions, **init()**, **render()**, **loop()** and **drawHUD()**:

init() is my function that I call when starting the game, right at the end of the script.

**render()** is my rendering function

**loop()** is my game loop function (do not notice it, I've simplified it with minimal to leave the code cleaner for reading)

**drawHUD()** is my function to draw HUD on Canvas **HUD\_CANVAS**

The problem is that the code below does not work, the screen remains blank, but if I put **drawHUD()** inside the render() before `CTX.drawImage (HUD_CANVAS, 0, 0);` then it works and I can see the image on the screen, however I wish I could draw only once, not every frame, since my HUD will not always be updating.

What am I doing wrong?

> *index.html*

```
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Test</title>

    <style type="text/css" media="screen">
        canvas {
            padding: 0;
            margin: auto;
            display: block;
            width: 640px;
            height: 480px;
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            border: 1px solid #999;
        }
    </style>

</head>

<body>

    <canvas id="canvas" style="z-index: 0;" width="640" height="480"></canvas>
    <canvas id="hud-canvas" style="z-index: 1;" width="640" height="480"></canvas>

    <script>
    const CANVAS = document.getElementById('canvas');
    const CTX = CANVAS.getContext('2d');
    const HUD_CANVAS = document.getElementById('hud-canvas');
    const HUD_CTX = HUD_CANVAS.getContext('2d');

    function drawHUD() {
        const imgHUD = new Image();
        imgHUD.src = './hand_hud_maya.png';
        HUD_CTX.drawImage(imgHUD, 0, 0, 96, 96, 0, 0, 96, 96);
    }

    function init() {
        drawHUD();
        loop();
    }

    function render() {
        CTX.drawImage(HUD_CANVAS, 0, 0);
    }

    function loop() {
        render();
        requestAnimationFrame(loop);
    }

    init();

    </script>

</body>
</html>

```

Example:

https://jsfiddle.net/twkq0sn6/

> Up1:

Change that part of the function, I can see the red rectangle on the screen, so I think the problem is with the drawImage() function, but I do not know what it can be, I already tested several images, I do not think it's the image.

```
 function drawHUD() {
     HUD_CTX.fillStyle = "red";
     HUD_CTX.fillRect(50, 50, 50, 50);
 }

```

the image is loaded properly, I can see in the chrome network tab the preview of it, all OK. I do not get any errors, it's hard to figure out where I'm going wrong.

# Answer
Building on your answer, you definitely need to preload all your resources before even starting the game. So your process would be

preload\_assets ==\> Start\_game

Here's an extract from this great article on asset loading in HTML5 games:

```
function loadImages(names, callback) {
  var n,name,
      result = {},
      count  = names.length,
      onload = function() { if (--count == 0) callback(result); };

  for(n = 0 ; n < names.length ; n++) {
    name = names[n];
    result[name] = document.createElement('img');
    result[name].addEventListener('load', onload);
    result[name].src = "images/" + name + ".png";
  }

}

```

Now to run the game you pretty much do something like `loadImages([...], startGameLoop);`

**EDIT: Always set the `onload` event** *before* **you set the `src` attribute.**

Otherwise, you image could finish loading before your onload event fires which means you never get the image drawn on screen.
> 1 votes

# Answer
I found the error, the image was being called in **drawImage()** before it was loaded, unfortunately I did not receive any error that could inform me of this. But I did work by changing the function to:

```
function drawHUD() {
    const imgHUD = new Image();
    imgHUD.src = './my_hud_image.png';
    imgHUD.onload = function(){
        HUD_CTX.drawImage(imgHUD, 0, 0, 256, 256, 0, 0, 256, 256);
    };
    imgHUD.onerror = function(){
        alert("Image error.");
    };
}

```

I think it will be interesting to load all the images and hunting for their possible errors in a separate script called *resources.js* by example, where I load everything that is necessary for the game to run, before it starts.

to read more about Image:

https://developer.mozilla.org/en-US/docs/Web/API/Canvas\_API/Tutorial/Using\_images
> 1 votes

# Answer
```
const CANVAS = document.getElementById('canvas');
const CTX = canvas.getContext('2d');
const HUD_CANVAS = document.getElementById('hud-canvas');
const HUD_CTX = canvas.getContext('2d');

```

Did you mean to get your HUD context from the HUD canvas, instead of from the same canvas used for the main game context?

```
const HUD_CTX = HUD_CANVAS.getContext('2d');

```
> 0 votes

---
Tags: 2d, javascript, rendering, html5, html-canvas
---


# Question
Title: Words to describe stat stacking behavior?
A character has a series of attributes.

```
Char {
    BaseStrength 1
    BaseHealth 100
    BaseLuck = 50
    BaseCharm = 20
}

```

and items will grant them modifiers

```
item0 {
  Modifier {
    Charm: + 1
  }
}

itemA {
  Modifier {
    Strength: ++ 1
  }
}

itemB {
  Modifier {
    Health: * 2
  }
}

itemC {
  Modifier {
    Luck: ** 1
  }
}

```

The way I was planning the operations + ++ * \** to work was if a player has 2 of each type of item. it would stack as follows.

finalCharm = BaseCharm + item0.Charm (no stacking)

finalStrength = BaseStrength + itemA.Strength + itemA.Strength

finalLuck = BaseLuck + BaseLuck\*(itemC.Luck + itemC.Luck)

finalHealth = BaseHealth + (BaseHealth * itemB.Health) + (BaseHealth * itemB.Health)

All except charm could be considered 'stacking' buffs.

itemA stacks additively, items B & C stack multiplicative.

How can I describe the stacking behavior differences between B & C to the player using words?

# Answer
> 6 votes
The way most RPG games work is this:

1. An item/spell etc increases a base stat by a fixed amount: eg +1 strength to base. This is your most basic stat increment. An example of this(which we will re-use) would be base strength of 10, +1. Adding another would be:

`100 + (+10) + (+10) = 120`
2. An item increases *total* strength by 1. This is post additive boosting, but as it is also additive, it is simple:

`(100 + (+10) + (+10)) +10 = 130`
3. Now we come to multiplicative effects (where things get complex), in this example, we are performing *pre* additive increases:

`(100 * 0.1) +10 = 120` (+10% to base strength)
4. *Post* additive effects (multiplier to *total* strength):

`(100 +10) * 0.1 = 121`

To put it in simple terms: you have two effects that modify base stats, and two which modify the post base stat modification. In each "stage" of performing stat modifications, you should add up the stat increase values, e.g. all base stat multipliers should be added together and applied as one:

`base * (mod1 + mod2)`

So the final equation looks like:

`final = (((base * base_mul_total) + base_add_total) * final_mul_total) + final_add_total`

This is what is known as **additive** stat increases.

**Multiplicative** stat increases work more like:

`((base * (1 + mod1)) * (1 + mod2)) * (1 + mod3)`

In terms of identification for the player, I wouldn't worry too much about it. An easy way I have seen done is to clearly specify whether is it *total* strength, or *base* strength that is being modified.

Most rpg theory-crafters know precisely what that means, and will work it out for themselves when min/maxing their characters. The rest of the players won't care what you call it, so long as it improves their character.

As an aside:

In general(for balance/progression), effects that modify final stat values tend to be powerful, and thus good for the end-game, whilst additive effects are your bread and butter effects, which you will accrue whilst levelling and getting better and better gear. Once your stats are high in the end game, multiplicative effects become very powerful and thus, very desirable (and more difficult to balance).

---
Tags: statistics
---


# Question
Title: How to incorporate (agile) user stories with specs into game development?
It seems some features/changes lend themselves to user stories: "as a user, I want to be prompted to exit or retry the battle after the hero dies, since these are the only two common navigations". But other features wouldn't be a good fit for stories, like a detailed description of which game elements appear during an event.

How are these detailed specs incorporated into the agile task system? Certainly the umbrella task could be written as an epic, but the specs seem not to fit as stories. (They are not about direct user motivation or benefit, because these specs often make the game harder, like "boss health should refill at 100% per 90 seconds".)

Note: we're using Jira to track bugs and tasks.

# Answer
I suggest you purchase Agile Game Development by Clinton Keith.

Yes, it is absolutely encouraged to draft user stories for various interaction scenarios.

Like most things Agile, you and your team will soon enough get a feel for what is detailed enough vs. too detailed, in terms of these stories. That all depends on your own processes & dynamics.

P.S. Personally, I prefer the way Pivotal Tracker, Phabricator or similar handles user stories. Jira just feels a bit clunky to me, but whatever works for you.
> 2 votes

---
Tags: game-design, project-management
---


# Question
Title: Moving a camera without rolling (tumble not arcball rotation)
I'm trying to move my camera around using mouse+keyboard. I'm looking for specific camera behaviour however, and I cant figure out how to get it right. What I've found, is that to get a **maya/tumble** style camera, I need to multiply my xrotation in world space then my yrotation. Reversing the order it looks like this:

```
view = cam_move * //wasd in cam_space, this works correctly
       yrot * //before = world to camera space
       view*
       xrot; //after = model to world space

```

This means my xrot(world) doesn't interfere with my yrot(eye), which avoids **unwanted roll** induced by regular cam-space x-rotation.

My problem however, is that I want the xrotation to happen around a point (as if done in eye space) but without creating unwanted roll. I do not know how to get that result.

According to my sources It should be as easy as translating inversely before xrotating, then translating back after, but its just not working. Perhaps someone knows how I can get my cam to spin (yaw) around a point, without causing the unwanted roll?

**SOLUTION:**

Keeping track of pitch/yaw (mouse\_move.xy) seperately, as well as the camera location, and making sure to multiply the yaw before the pitch. Pitching will create unwanted roll, but yawing wont create unwanted pitch, so its a matter of which you do first here.

To move the camera in eye space, I do this:

```
//make a mat3 rotation matrix and multiply it with current movement
if (keys['A'] - keys['D'] || keys['W'] - keys['S']){
    camlocation += //rotated then moved
        (glm::normalize(vec3(keys['A'] - keys['D'], 0, keys['W'] - keys['S']))*move_speed)*
        mat3(glm::rotate(mat4(1.0f), pitch, vec3(1, 0, 0)))*
        mat3(glm::rotate(mat4(1.0f), yaw, vec3(0, 1, 0)));
} //which will be a value to add in world space

```

Then under camera update, or where I build the view matrix, I do this:

```
view =
    glm::rotate(mat4(1.0f), pitch, vec3(1, 0, 0))* //pitch radian float
    glm::rotate(mat4(1.0f), yaw, vec3(0, 1, 0))* //yaw also in radian
    glm::translate(mat4(1.0f), camlocation);

```

Just remember that in OpenGL/GLM the matrix transformations are reverse order, due to how OpenGL does column/row matrix computations. (Compared to directx it saves a transpose operation in the shader (apparently))

Making sure to **yaw before pitching**, and both after translating (reversed on paper) **avoids the unwanted roll**, wich yields the desired tumble/maya effect!

# Answer
> 1 votes
In general, avoid the approach where you take current camera orientation, modify it and store as the new one - you will accumulate computation errors and it can easily break after a while.

Instead, define you **center point** for rotation.

Define your **distance** from this center (can be modified by e.g. mouse wheel).

Define **Yaw** and **Pitch** values.

Do you math that will compute **camera matrix** from those data.

In your UI you'll change Yaw/Pitch/distance/center and compute new camera matrix.

This way you have some base params that you modify, it's easier to do more complex UI around it and your camera matrix is always correct.

Here you have some explanation why do you get an unexpected Roll: https://gamedev.stackexchange.com/a/37242/18381

# Answer
> 0 votes
Welcome to computer graphics, and game development :)

Sorry, I'm writing from a phone...

Yaw Pitch Roll is cool, let me call it Euler angles.

Euler angles can be used for rotating object in 3D space, but this approach can be hard to implement.

With Euler angles you can't simply compose all components of your final rotation, you must do it with "correct" for your model order. In code it is a quest.

Look at quaternion. It harder to understand, but using it you does not deal with problems of Euler angles.

If components of rotations of your model represented with quaternions it can be simply multiplied in any order to get resulting rotation.

---
Tags: opengl, c++, camera
---


# Question
Title: Character getting slow when reached to speific path point
I have manually placed some cube on the floor and aim to walk my character on those cube as they are appearing in the hirarchey and here is the walk code.

```
 if (Vector3.Distance(pathPositions[pathIndex], walkingCharacter.transform.position) > 0.5f)
        {
            Vector3 newPosition = pathPositions[pathIndex] - walkingCharacter.transform.position;
            walkingCharacter.transform.position += newPosition * Time.deltaTime * walkingSpeed;
            walkingCharacter.transform.rotation = Quaternion.LookRotation(newPosition);
        }
        else {
            pathIndex++;
        }

```

I have walk in place animation which is working fine and the above code moving my character to specific points but not smoothly. As my character approach to specific path point it get slow then suddenly move towards next point. What i am doing wrong. Here is the **video** of the problem maybe it will helpful to understand the problem.

# Answer
> 2 votes
The code you've written is an exponential ease-out, which is why it slows down over time.

First, the `newPosition` vector isn't really a position but a target offset.

```
Vector3 newPosition = pathPositions[pathIndex] - walkingCharacter.transform.position;

```

It's measured from the character's position to their next waypoint, which means as the character approaches the waypoint, this offset vector gets shorter and shorter. You can imagine in the limiting case, if the character were allowed to reach a distance of zero away from the target, this vector would have no length at all.

Next, you increment the position by a multiple of this vector (here `walkingSpeed` isn't really a set speed at all, but an amplification factor on distance):

```
walkingCharacter.transform.position += newPosition * Time.deltaTime * walkingSpeed;

```

So as the offset gets smaller and smaller, so does the multiplied increment. So you approach the target in a manner like Xeno's paradox, taking smaller and smaller steps the closer you get.

To see this concretely, let's look at what happens if we have a `walkingSpeed` of 2 and a steady `1/30` `deltaTime`:

```
Frame    Offset to Target    Movement Increment
  1           30.00                2.00 <-- At this rate, we should reach
  2           28.00                1.87     the goal in 15 frames!
  3           26.13                1.74
  4           24.39                1.63
  5           22.77                1.52
  6           21.25                1.42
  7           19.83                1.32
  8           18.51                1.23
  9           17.27                1.15
 10           16.12                1.07
 11           15.05                1.00
 12           14.05                0.94
 13           13.11                0.87
 14           12.23                0.82
 15           11.42                0.76
 16           10.66                0.71 <-- 15 frames later, we've only covered
                                            2/3rds of the distance, and we've
                                            lost 2/3rds of our speed. :(

```

Instead, it looks like you want MoveTowards:

```
walkingCharacter.transform.position = Vector3.MoveTowards(
    walkingCharacter.transform.position,
    pathPositions[pathIndex],
    walkingSpeed * Time.deltaTime
);

```

This keeps a constant movement speed of `walkingSpeed` throughout the travel.

Under the hood, it would look a bit like this (my re-implementation, not Unity's code):

```
public Vector3 MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta) {
    float offset = target - current;

    // Avoiding square roots until they become necessary later.
    float lengthSquared = offset.sqrMagnitude;

    // If we're within our allowed movement range, we reach the endpoint and stop.
    if(lengthSquared <= maxDistanceDelta * maxDistanceDelta)
        return target;

    // Normalize the offset vector and scale it to the length of maxDistanceDelta.
    offset *= maxDistanceDelta / Mathf.Sqrt(lengthSquared);

    return target + offset;
}

```

---
Tags: unity, c#, animation, character
---


title: Smoothness texture map in unity

text:
# Question
Title: Smoothness texture map in unity
I shall submit a 3d asset to the Unity asset store. Their submission guidelines say,"... must include at least an albedo,normal,metallic (or specular) and smoothness texture map."

1. My query is how do I **get the smoothness map** and where do I put it ? There is just one slot by the smoothness slider where I put the metallic map.
2. Is it really necessary to put a smoothness texture map if I already have a metallic map attached to the material?

It's my first attempt to submit an asset to the asset store.

# Answer
> 2 votes
This appears to be covered in the official Unity documentation on Metallic Parameters.

> By default, with no texture assigned, the Metallic and Smoothness parameters are controlled by a slider each. This is enough for some materials. However if your model’s surface has areas with a mixture of surface types in the albedo texture, you can use a texture map to control how the metallic and smoothness levels vary across the surface of the material. ...
>
> With a texture assigned to the Metallic parameter, both the Metallic and Smoothness sliders will disappear. Instead, the Metallic levels for the material are controlled by the values in the Red channel of the texture, and the Smoothness levels for the material are controlled by the Alpha channel of the texture. (This means the Green and Blue channels are ignored). This means you have a single texture which can define areas as being rough or smooth, and metallic or non-metallic ...

Based on that, if you've assigned a texture for the metallic parameter, you shouldn't need an additional texture for smoothness - one file functions as both the metallic texture map and the smoothness map simultaneously.

This was taken for the most recent version at the time it was posted (2018.2) for past versions, change the documentation version as shown here:

---
Tags: unity, textures
---


title: Timer as part of a condition

text:
# Question
Title: Timer as part of a condition
I am using a sensor as the input to my game.

When a certain level of force is exerted on the sensor, for a certain amount of time, I want the next level to be reached.

How would I do this?

I have attached both the timer code and the game code, but I don't know how to use them together.

Timer code:

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

public class Timer : MonoBehaviour
{
    public int timeLeft = 5;
    public Text countdownText;

    // Use this for initialization
    void Start()
    {
        StartCoroutine("LoseTime");
    }

    // Update is called once per frame
    void Update()
    {
        countdownText.text = ("Time Left = " + timeLeft);

        if (timeLeft <= 0)
        {
            StopCoroutine("LoseTime");
            countdownText.text = "Times Up!";
        }
        //Invoke("ChangeLevel", 0.1f);
    }

    IEnumerator LoseTime()
    {
        while (true)
        {
            yield return new WaitForSeconds(1);
            timeLeft--;
        }
    }
    void ChangeLevel()
    {

        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
    }
}

```

Game code:

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

public class arduino : MonoBehaviour {

    SerialPort sp = new SerialPort("\\\\.\\COM6", 9600);// Com port and the baud rate of the arduino
    Material m_Material;
    GameObject Sphere;

    void Awake(){
        Sphere = GameObject.FindWithTag ("Player");
        m_Material = GameObject.FindWithTag ("Player").GetComponent<Renderer > ().material ;
    }
    void Start ()
    {
        if (!sp.IsOpen)
        { // If the serial port is not open
            sp.Open(); // Open
        }
        sp.ReadTimeout = 250; // Timeout for reading
     }
    // Update is called once per frame
    void Update () {
        if (sp.IsOpen) { // Check to see if the serial port is open
            try
            {

                string portreading = sp.ReadLine(); // get the string output of the serial port
                float amount = int.Parse(portreading);

                if ((amount > 10f) && (amount < 100f))
                {
                    m_Material.color = Color.grey;
                   // Sphere.transform.position = (new Vector3(0f, amount * 0.1f, 0f));

                }

                if ((amount > 101f) && (amount < 150f))
                {
                    m_Material.color = Color.blue;
                    //Sphere.transform.position = (new Vector3(0f, amount * 0.1f, 0f));
                }

                if ((amount > 151f) && (amount < 201f))
                {
                    m_Material.color = Color.yellow;
                    //Sphere.transform.position = (new Vector3(0f, amount * 0.1f, 0f));
                }
                if ((amount > 201f))
                {
                    m_Material.color = Color.red;
                   // Sphere.transform.position = (new Vector3(0f, amount * 0.1f, 0f));

                }
            }
            catch (System.Exception)
            {

            }
        }
    }
}

```

# Answer
Myself, I'd recommend separating the jobs of reading from the sensor, running your timer, and coordinating your scene transitions. This way each script can do one simple job, so you don't end up with an uberscript that's trying to do everything in your scene.

We can use Unity Events to communicate between the scripts. This way, if you decide that instead of immediately loading the next scene, your timer should set off some fireworks and play some music, you can do that just by rewiring a few events, rather than gutting logic that's dependent on scene transitions out of your timer script.

This first script is responsible for reading from your sensor & reporting its values. Since you already have the sensor reading parts working, I'll elide those details here and just show the parts needed to communicate with other scripts:

```
public class SensorReader : MonoBehaviour {
    // Define a pattern for any methods that want to listen to the sensor:
    [System.Serializable]
    public class SensorEvent : UnityEvent<float> {}

    // Expose an event in the Inspector that you can use to wire up events.
    public SensorEvent onValueChanged;

    // Track the sensor value so it's easy to check on demand,
    // and cache a previous value so you know when it's changed.
    public float sensorValue;
    float _previousSensorValue;

    void Update() {
        // I'll elide the details of reading from the sensor, since you've got that.
        sensorValue = ReadSensorValue();

        // You can add a tolerance range here to notify only on large changes,
        // if you find you're getting to much spam from small flickers.
        if(sensorValue != _previousSensorValue && onValueChanged != null) {
            onValueChanged.Invoke(sensorValue);
            _previousSensorValue = sensorValue;
        }
    }
}

```

This second script listens to a value source (hook up its `OnValueChanged` method to your sensor's `onValueChanged` event), and when the value is within a particular range, it runs a timer. When that timer runs out, it fires an event of its own.

```
public class RangeCountdown : MonoBehaviour {
    public float duration = 5;

    public float minValue = 50;
    public float maxValue = 100;

    // Setting this > 0 gives a little wiggle room once the timer starts,
    // so it doesn't flicker on-off-on-off when the value hovers near the threshold.
    public float hysteresis = 0.1f;

    // Expose an event in the Inspector you can use to wire up events.
    public UnityEvent onTimerComplete;

    public Text timerText;

    Coroutine _countdown;

    public void OnValueChanged(float value) {
        // If the countdown isn't active, check if we're in range to start counting.
        if (_countdown == null) {
            if (value < minValue || value > maxValue)
                return;
            _countdown = StartCoroutine(Countdown(duration));
        // Otherwise, check if we've gone out of range & need to reset.
        } else {
            if (value < maxValue + hysteresis && value > minValue - hysteresis)
                return;
            StopCoroutine(_countdown);
            _countdown = null;
            timerText.gameObject.SetActive(false);
        }
    }

    IEnumerator Countdown(float remainingDuration) {
        timerText.gameObject.SetActive(true);

        while (remainingDuration > 0f) {
            timerText.text = "Time Left = " + Mathf.CeilToInt(remainingDuration);

            // Wait one frame.
            yield return null;
            remainingDuration -= Time.deltaTime;
        }

        // Let everyone who cares know that the timer completed successfully.
        if (onTimerComplete != null)
            onTimerComplete.Invoke();

        // End the timer & hide the timer text.
        timerText.gameObject.SetActive(false);
        _countdown = null;
    }
}

```

Lastly, you can have a scene loader script, that you wire up to listen to the timer's completion event. (Or, as you build on your project, you might have a little success fanfare first, and then the success fanfare later triggers the scene load - the events let you mix this up as needed)

```
public class SceneLoader : MonoBehaviour {

    public void LoadNextScene() {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
    }
}

```
> 3 votes

# Answer
If i understood you correctly, after force or *amount \> 0* we need to subtract some number from TimeLeft, and after 5 seconds pass, we level up, so move this sphere up. Correct me if i didn't get your question. Also I simplified your IF statements using 2 arrays.

**Pseudo Code**

So, no need for IEnumerators. I would Use **deltaTime.**

```
//ps: This is inside same Update void where we check for colors.

 public float totalTimePressed = 0;
 public float TimeToLevel = 5;

 void Update(){
   float amount = int.Parse(portreading);

   if(amount > 0) totalTimePressed += Time.deltaTime;
   else totalTimePressed = 0; //reset

   for(int i = 0; i < Limits.Length-1; i++){
       if(totalTimePressed >= TimeToLevel){
          int index = Limits.Find(Closer(amount, Limits[i], Limits[i+1]));
          Color color = Colors[index];
          m_Material.color = color;
          Sphere.transform.position = (new Vector3(0f, amount * 0.1f, 0f));

          break;
       }
   }

 }
    //returns value that is closest to compareValue
    public static int Closer(int compareValue, int a, int b)
    {

       long calcA = Math.Abs((long)a - compareValue);
       long calcB = Math.Abs((long)b - compareValue);

       if (calcA == calcB) return 0;
       if (calcA < calcB) return a;

       return b;
    }

```

Docs Time.deltaTime: https://docs.unity3d.com/ScriptReference/Time-deltaTime.html

*PS: reply to this answer if you really will need non-pseudo code from me :p*
> 1 votes

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


# Question
Title: Create dynamic cities of perspective angle x with least amount of tiles
I found you can create unique building sizes with perspective with six tiles using parallel projection, whose angles are always 45 degrees... this allows you to connect to the next tile without issue:

The issue with that is you're stuck to a 45 degree angle... I feel like a 75 degree angle better matches my game's overall perspective...

But doing anything other than 45 degrees limits how deep my building is (how far back the building top goes)... so this seems to force me to create additional buildings if I want to make the top reach back further... Which adds complexity

**Question**:

Is there a way to achieve what I'm doing for any angle I choose such that I can create one building tileset (of 6 tiles) and create dynamic cities?

Or, do I have to sacrifice the angle of my choosing and go with the simple 45 degrees?

Thanks

# Answer
> 3 votes
Sure. Make non-square tiles.

For 75 degrees, you want a tile that's tan(75) = 3.732 times as tall as it is wide.

(edit: You might want to use shorter tiles on the 'middle' area between ground and roof, so as to enable buildings of various heights.)

# Answer
> 0 votes
You can extend it as far as you want, but you will need tiles with different diagonal pieces (like a puzzle) if you don't use a 45 deg angle.

You can use an angle that lets the tiles repeat after 2,3,...,n tiles.

For example. 63.435 deg will require 2 diagonal tiles, but you can extend buildings by alternating between them like this:

\[tile 1\]

oxxx

xoxx

\[tile 2\]

xxox

xxxo

\[together\]

oxxx

xoxx

xxox

xxxo

\____oxxx

\____xoxx

the larger the angle the more complexity. here is a list of a few angles given by atan(n).

1 tile repeat, 45 deg

2 tile repeat, 63.435 deg

3 tile repeat, 71.57 deg

4 tile repeat, 75.96 deg

---
Tags: tilemap, tiles
---