# Question
Title: Do I need to build my scripts every time I go back into Unity from my script editor?
I saw a few Unity YouTubers who do not build their scripts when they are working.

But I always do it.

Do I have to?

# Answer
No you dont need to build your code from Visual Studio for example. Unity does that for you when it detects changes in relevant code.
> 1 votes

---
Tags: unity, build-process
---


# Question
Title: Implement delay using polling or threads?
I'm making a real-time risk-like game in Python. Players can move armies from one region to another. I want army movement to take time proportional to the distance between the two regions, therefore I need to keep a new timer every time an army moves from one region to another (until the army arrives).

I've thought of 2 ways to do this:

One way is to have a list of moving troops and do a for loop through this list every iteration of the main server loop to check if the time is up for each unit.

Another way is to create a new thread for each moving troop and have the run() method of the thread continuously check whether the time is up yet for the unit.

Which way is better?

# Answer
Handle it in the main update loop if you can.

The first rule of multithreading is: Don't use multithreading unless you have to. "X and Y should happen simultaneously from the perspective of the user" is not an appropriate reason. You can handle that much better with an update-loop. The only reasons to ever use threads are performance and response time. The reason is that multithreading makes your program much harder to debug and that it introduces extremely difficult to reproduce problems due to thread timing ("race conditions").
> 1 votes

---
Tags: python, multithreading, timer, timing
---


# Question
Title: Sorting a vector using array version of quick sort
I'm coding a simple rendering engine using OpengGL and I wrote a class that manages a particle system. The class creates the particles and pushes them into a vector to be used by a renderer to draw them on screen. I need to order the particles from the farthest to the nearest to the camera (in order to solve problems with alpha blending and depth, having disabled depth testing for transparency), so I tried with the following code:

```
void ParticleRenderer::render()
{
    // prepare renderer
    .....
    // update particle state (position,ecc..) and remove it if necessary
    // update returns a bool indicating if particle is still alive
    while (it != mParticles.end())
    {
        if (!(*it)->update())
        {
            delete *it;
            it = mParticles.erase(it);
            if (it == mParticles.end())
                break;
            else
                continue;
        }
        it++;
    }
    if (mParticles.size() > 0)
        sortParticles(&mParticles[0], 0, mParticles.size() - 1);
    for (Particle *particle : mParticles)
    {
        .....
        // render particle
        .....
        std::cout << getCameraDistance(particle) << std::endl;
    }
    std::cout << "*************************************" << std::endl;
    mShader.unuse();
    glDisable(GL_BLEND);
}

void ParticleRenderer::sortParticles(Particle **particles, int low, int high)
{
    if (low >= high)
        return;
    Particle *temp = particles[low];
    while (true)
    {
        while (compareParticles(temp, particles[high]) >= 0 && low < high)
            high--;
        if (low == high)
            break;
        else
            particles[low++] = particles[high];
        while (compareParticles(temp, particles[low]) < 0 && low < high)
            low++;
        if (low == high)
            break;
        else
            particles[high--] = particles[low];
    }
    particles[high] = temp;
    int middle = high;
    sortParticles(particles, low, middle - 1);
    sortParticles(particles, middle + 1, high);
}

double ParticleRenderer::compareParticles(Particle *particle1, Particle *particle2)
{
    return  getCameraDistance(particle1) - getCameraDistance(particle2);
}

double ParticleRenderer::getCameraDistance(Particle *particle)
{
    glm::vec3 distance = mCamera.getPosition() - particle->getPosition();
    return glm::length(distance);
}

```

but what I get on the console are all unsorted particles (the cout statement) and of course I have problems when the particles are rendered on screen. Am I missing something?

I know I could use std::sort and the STL algorithms, but since I'm learning I would like to know what I am doing wrong.

# Answer
> 1 votes
Actually my recursive quicksort was wrong. While testing with a vector of ints I used a slightly different version, in wich the partitioning of the array was performed in another function. This version is flawed since I'm passing to the recursive quicksort (divide and conquer I understand..) the same high and low indices that are used in the algorithm...so I'm passing the same index...hence no sorting.

---
Tags: opengl, c++, vector, particles
---


title: _BitScanReverse identifier not found

text:
# Question
Title: _BitScanReverse identifier not found
I'm developing some additional options for a game (which means I don't have knowledge about whole game's methods, classes etc.).

Anyway, I have been trying to build the project for codes I've developed to test them. I've encountered some DirectX, Windows SDK Version, Compiler problems but managed to solve them. But now I'm encountering some BitScanReverse error.

It says: C3861 '\_BitScanReverse': identifier not found

Here is whole code for the error I'm encountering:

```
#pragma once

#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include <initializer_list>
#include <functional>
#include <iterator>

    #ifdef _MSC_VER // BitScanReverse ERROR 1
        _BitScanReverse(&n, ~code);
    #else
        n = sizeof(long) * 8 - 1 - __builtin_clzl(~code);
    #endif

    code &= ~(-1 << n);
    n = 6 - n;
    ptr++;

    #ifdef _MSC_VER // BitScanReverse ERROR 2
        _BitScanReverse(&n, ucode);
    #else
        n = sizeof(long) * 8 - 1 - __builtin_clzl(ucode);
    #endif

```

I've downladed source codes through SVN, so whole project is actually working. I just couldn't manage to build it in my local laptop or desktop computer.

By the way, I've tried to build it with Visual Studio 2015 Enterprise (with other errors), Visual Studio 2017 Proffesional and Community Edition (with same errors). And actually this project was developed with Visual Studio 2013 and 2015.

I'm not even good C++ coder so I couldn't figured out the problem. Does anyone have an idea?

# Answer
> 1 votes
According to the docs here `_BitScanReverse` is in the header file \<intrin.h\>. Try adding `#include <intrin.h>` to your file.

---
Tags: c++, gui, visual-studio
---


# Question
Title: Play two different audio sources depended on code behind
How can I play two different audio clips in Unity depended on the code behind? Into my object I've added two audio sources namely 'Player GunShot' and 'outOfAmmo'.

Into the same object I've also added a C# script whit this code:

```
public currentBullets = 1;

private AudioSource gunAudio;
private AudioSource outOfAmmo;

void Awake()
{
    gunAudio = GetComponent<AudioSource>();
    outOfAmmo = GetComponent<AudioSource>();
}

void Update()
{
    if (currentBullets == 0)
    {
        outOfAmmo.Play();
    }
    else
    {
        gunAudio.Play();
    }
}

```

Can this code give any problems because in the `Awake` methode? I've not defined with audio source the variable must be. So which source go he take to play?

# Answer
Try something like this (use only one AudioSource):

```
public currentBullets = 1;

private AudioSource gunAudio;
public AudioClip gunshot; //set this in ispector with audiofile
public AudioClip outofammo; //set this in ispector with audiofile

void Awake()
{
    gunAudio = GetComponent<AudioSource>();

}

void Update()
{
    if (currentBullets == 0)
    {
       gunAudio.clip = outofammo;
    }
    else
    {
       gunAudio.clip = gunshot;
    }
   gunAudio.Play();
}

```

Reference : here
> 2 votes

# Answer
Have public variables which you assign the sound files to in the script, then change the audioclip of audio source using the variables the sound clips were assigned to.

Look at the code given in the answer to this question for how to write your script: http://answers.unity3d.com/questions/347657/play-audioclip-once-and-switching-clips.html
> 1 votes

# Answer
# Public fields

```
 public AudioSource  aud_jump;
 public AudioClip  clip_jump;

 public string SourceNormalPlatJump = " set path in inspecter like "Sounds/jump_11" in resource folder ";
 public string SourceDestroyPltJump = "set path in inspecter like "Sounds/jump_11" in resource folder";

Start()
{
    aud_jump = GetComponent<AudioSource>();
}

```

# Conditions

```
private void OnTriggerEnter2D(Collider2D hitPlatform)
    {

            if ((hitPlatform.gameObject.tag == "Platform" ) && rigidbody2DPlayer.velocity.y <= 0.2)
            {
               clip_jump = (AudioClip)Resources.Load(SourceNormalPlatJump);
                aud_jump.clip = clip_jump;
                aud_jump.Play();

               }

            // player hits Desroy paltform
            if (hitPlatform.gameObject.tag == "DestroyPlatform" && rigidbody2DPlayer.velocity.y <= 1)
            {
                clip_jump = (AudioClip)Resources.Load(SourceDestroyPltJump);
                aud_jump.clip = clip_jump;
                aud_jump.Play();
             }
  }

```
> -1 votes

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


# Question
Title: Why is the camera tilting around the z axis when I only specified x and y?
My goal is to program a camera to point towards the mouse cursor. I attached the following script to the Main Camera.

```
using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

    public float sensitivity;

    // Update is called once per frame
    void Update () {
        transform.Rotate (Input.GetAxis ("Mouse Y") * -1 * sensitivity, Input.GetAxis ("Mouse X") * sensitivity, 0);
    }
}

```

I "told" the camera to rotate around the x and y axes. Whenever it does this, the camera tilts sideways. When I checked the rotation of Main Camera, I saw that the z rotation had changed. Why is it rotating around the z axis when I left it at 0?

# Answer
Rotations are extremely order-dependent. Doubly so when you're composing rotations in local space (so the axes you're rotating around are themselves rotating from one frame to the next)

As an extreme example, imagine that you start facing z+, and in one frame you pitch (x rotation) 90 degrees up.

In the next frame, you yaw (y rotation) 90 degrees left. Since you're already looking straight up, your local y axis is pointing "back" along the world z- axis, so this leaves you looking along the x- axis, with your local y axis still pointing "back" along world z-.

This is the same as yawing 90 degrees left and then rolling (z rotation) 90 degrees left.

So: composing local x & y rotations, compounded from frame to frame, can turn into z rotations.

One way to fix this is to always pitch along your local x axis, but always yaw around the world y axis (if you always want the camera "up" vector facing up). eg:

```
void Update () {
    float pitch = Input.GetAxis ("Mouse Y") * -1f * sensitivity;
    transform.Rotate (pitch * Vector3.right, Space.Self);

    float yaw = Input.GetAxis ("Mouse X") * sensitivity;
    transform.Rotate (yaw * Vector3.up, Space.World);
}

```

Note that this still has the problem of gimbal lock common to Euler angle / yaw-pitch-roll rotation systems, and isn't suitable if you want the player to be able to point their camera straight up or straight down.
> 5 votes

# Answer
You can also lock z-rotation using:

```
float z=transform.eulerAngles.z;
transform.Rotate(0,0,-z);

```
> 0 votes

---
Tags: unity, camera, rotation
---


title: Camera not following ragdoll in unity

text:
# Question
Title: Camera not following ragdoll in unity
I have made a ragdoll and attached (as child object) the main camera to it, but the camera doesn't follow the ragdoll. Why is this happening? And how do I fix this?

# Answer
> 1 votes
Your ragdoll, being attached to another object, is moving in the local space of that parent. Thus you have to make the camera a child of your ragdoll if you want it to follow. Read here for an existing answer: In Unity, how do I make the camera follow a character?

Having said that, don't do it but use a proper script where you set the ragdoll as target to compute the new camera position from. That will give you a much better control and user experience.

# Answer
> 0 votes
For the ragdoll, add a Rigidbody component. The ragdoll is affected by physics and doesn't change its transform's position, adding rigidbody is a workaround cause it changes the transform whenever the ragdoll (parent) changes positions constantly. the ragdoll is affected by rigidbody but it is barely noticeable. Make a script or add a script that constantly changes the camera's position relative to the ragdoll (add some offset if you're doing third person or want the camera to be positioned onto the head). This should make it work.

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


# Question
Title: Using unity app how to read the asset in android SDCard?
I am trying to read one file from my android sd card from my unity application, but its not reading.

using the asset bundle i have exported my file and kept in my android device sd card and i am trying to fetch it and show into my scene.

Here is the code i have used for this:

```
public string URL;
public string URLAndroid = Application.persistentDataPath+/cube.unity3d;
public string AssetName;

private string path;

IEnumerator Start() {

    //path = System.IO.Path.Combine (Application.persistentDataPath, "/cube.unity3d");

    // Download the file from the URL. It will not be saved in the Cache
    using (WWW www = WWW.LoadFromCacheOrDownload(URLAndroid, 1)) {
        yield return www;

        if (www.error != null)
            throw new Exception("WWW download had an error:" + www.error);

        AssetBundle bundle = www.assetBundle;

        if (AssetName == "")
            Instantiate(bundle.mainAsset);
        else
            Instantiate(bundle.LoadAsset(AssetName));

        // Unload the AssetBundles compressed contents to conserve memory
        bundle.Unload(false);

    } // memory is freed from the web stream (www.Dispose() gets called implicitly)
}

```

Here i have used the URLAndroid as a normal downloading method and ihave tried to fethch the model using system.io method but its not happening. I have created the corresponding folder in my android device and kept my assets eventhough its not happening.

Plesae help me to solve this issue.

# Answer
To solve this problem I created pre-compilation script which will run before the compilation; this script will list the names of the files you want to access later in text file

```
 #if UNITY_EDITOR
 using UnityEditor.Build;
 using UnityEditor;
 using System.IO;

 public class BM_AndroidBuildPrepartion : IPreprocessBuild
 {
     public int callbackOrder { get { return 0; } }
     public void OnPreprocessBuild(BuildTarget target, string path)
     {
         // Do the preprocessing here
         string[] fileEntries = Directory.GetFiles("Assets/Resources/Prefabs/alphabet", "*.prefab");
         System.IO.Directory.CreateDirectory("Assets/StreamingAssets/");
         using (StreamWriter sw = new StreamWriter("Assets/StreamingAssets/alphabet.txt", false))
         {

         foreach (string filename in fileEntries) {
                 sw.WriteLine(Path.GetFileNameWithoutExtension(filename));
         }

         }
     }
 }
 #endif

```

then I read the text file and you can access the files in same way but you have to put them inside your project in Assets/StreamingAssets/

```
   #if UNITY_ANDROID
        string  path = "jar:file://" + Application.dataPath + "!/assets/alphabet.txt";
          WWW wwwfile = new WWW(path);
          while (!wwwfile.isDone) { }
          var filepath = string.Format("{0}/{1}", Application.persistentDataPath, "alphabet.t");
          File.WriteAllBytes(filepath, wwwfile.bytes);

          StreamReader wr = new StreamReader(filepath);
              string line;
              while ((line = wr.ReadLine()) != null)
              {
              //your code
              }
   #endif

```
> 1 votes

---
Tags: assets, unityscript, unity-networking, unity
---


title: POST & push for turn-based network?

text:
# Question
Title: POST & push for turn-based network?
Can you create a viable two player turn-based networking implementation using only REST API for outbound and push for inbound data? If a game is comprised of, on average, 30 moves, is it a bad idea to just send 15 push notifications to each user? If hosting expense is less than income for each DAU, is this perfectly acceptable, or an abuse of what push is intended for? ...Why or why not?

# Answer
Push Notifications are not ideal for this purpose as push notifications may come at long unpredictable delays, may come out of order, or may not come at all. Push notifications also encounter rate limiting at volume. In my comment to your question I said "Trust push like you trust UDP packets" that's giving push far too much credit. In most cases you'll find that sending push notifications comes with more overhead than just talking to your game client via your API.

You should probably just poll your game API from the client when the user is currently in game. If a user has not made their move and it has been some time, that may be a good opportunity to send a push.

This answer is somewhat predicated on the assumption that by turn based, you mean a pace similar to games like Hearthstone. If your game involves turns that are likely to be slow paced like a play by email game then push may not be a bad option, but it won't be a reliable option in the same way that email is.

An additional note, Apple Push Notifications for iOS are typically much less reliable in practice than Google's new Firebase Cloud Messaging for Android (Google Cloud Messages, their previous service seemed to be about the same in my experience).
> 2 votes

---
Tags: android, ios, turn-based-strategy, server-push
---


# Question
Title: Box2d collision on isometric maps built in Tiled
I am trying to add Box2d collision to a map I created in Tiled http://www.mapeditor.org/

It all worked when I was creating standard othergraphic maps but now I have changed to isometric the objects layer (Where I am creating the bodies for box2d) no longer match the rendering from the IsometricTiledMapRenderer.

I created the collision using the MapBodyBuilder class (written by someone else much smarter) Code below:

```
public class MapBodyBuilder {

// The pixels per tile. If your tiles are 16x16, this is set to 16f
private static float ppt = 0;
public static Array<Body> bodies;

public static Array<Body> buildShapes(Map map, float pixels, World world) {
    ppt = pixels;

    MapObjects objects = map.getLayers().get("Obstacles").getObjects();

    bodies = new Array<Body>();

    for(MapObject object : objects) {

        if (object instanceof TextureMapObject) {
            continue;
        }

        Shape shape;

        if (object instanceof RectangleMapObject) {
            shape = getRectangle((RectangleMapObject)object);
        }
        else if (object instanceof PolygonMapObject) {
            shape = getPolygon((PolygonMapObject)object);
        }
        else if (object instanceof PolylineMapObject) {
            shape = getPolyline((PolylineMapObject)object);
        }
        else if (object instanceof CircleMapObject) {
            shape = getCircle((CircleMapObject)object);
        }
        else {
            continue;
        }

        BodyDef bd = new BodyDef();
        bd.type = BodyDef.BodyType.StaticBody;
        Body body = world.createBody(bd);
        body.createFixture(shape, 1);

        bodies.add(body);

        shape.dispose();
    }
    return bodies;
}

private static PolygonShape getRectangle(RectangleMapObject rectangleObject) {
    Rectangle rectangle = rectangleObject.getRectangle();
    PolygonShape polygon = new PolygonShape();
    Vector2 size = new Vector2((rectangle.x + rectangle.width * 0.5f) / ppt,
            (rectangle.y + rectangle.height * 0.5f ) / ppt);
    polygon.setAsBox(rectangle.width * 0.5f / ppt,
            rectangle.height * 0.5f / ppt,
            size,
            0.0f);
    return polygon;
}

private static CircleShape getCircle(CircleMapObject circleObject) {
    Circle circle = circleObject.getCircle();
    CircleShape circleShape = new CircleShape();
    circleShape.setRadius(circle.radius / ppt);
    circleShape.setPosition(new Vector2(circle.x / ppt, circle.y / ppt));
    return circleShape;
}

private static PolygonShape getPolygon(PolygonMapObject polygonObject) {
    PolygonShape polygon = new PolygonShape();
    float[] vertices = polygonObject.getPolygon().getTransformedVertices();

    float[] worldVertices = new float[vertices.length];

    for (int i = 0; i < vertices.length; ++i) {
        System.out.println(vertices[i]);
        worldVertices[i] = vertices[i] / ppt;
    }

    polygon.set(worldVertices);
    return polygon;
}

private static ChainShape getPolyline(PolylineMapObject polylineObject) {
    float[] vertices = polylineObject.getPolyline().getTransformedVertices();
    Vector2[] worldVertices = new Vector2[vertices.length / 2];

    for (int i = 0; i < vertices.length / 2; ++i) {
        worldVertices[i] = new Vector2();
        worldVertices[i].x = vertices[i * 2] / ppt;
        worldVertices[i].y = vertices[i * 2 + 1] / ppt;
    }

    ChainShape chain = new ChainShape();
    chain.createChain(worldVertices);
    return chain;
}

```

}

Any help would be greatly appreciated.

Thanks

pps I know this has been asked before generate box2d bodies from isometric tiled map

But I cannot find an answer.

# Answer
> 1 votes
Finally figured out a way to do it.

I convert the verticies of the box2d poly from orthagraphic to isometric.

I edited the method from above to look like this. (The +320 and +175 to the co-ordinates was to compensate for a offset I had)

```
    private static ChainShape getPolyline(PolylineMapObject polylineObject) {
    float[] vertices = polylineObject.getPolyline().getTransformedVertices();
    Vector2[] worldVertices = new Vector2[vertices.length / 2];

    for (int i = 0; i < vertices.length / 2; ++i) {
        worldVertices[i] = new Vector2();
        worldVertices[i].x = vertices[i * 2] / ppt;
        worldVertices[i].y = vertices[i * 2 + 1] / ppt;

        // Set 2d verts to Iso + deal with the offset
        Vector2 vel = Iso.TwoDToIso(new Vector2(worldVertices[i].x,worldVertices[i].y ));
        worldVertices[i].x = vel.x + 320 ;
        worldVertices[i].y = vel.y+ 175;
    }

    ChainShape chain = new ChainShape();
    chain.createChain(worldVertices);
    return chain;
}

```

I call this new function to convert the verts for me

```
    public static Vector2 TwoDToIso(Vector2 point){
    Vector2 vel2 = new Vector2();

    vel2.x = point.x - point.y;
    vel2.y = -(point.x + point.y) / 2;
    return vel2;
}

```

---
Tags: libgdx, box2d, tiled
---


# Question
Title: generate box2d bodies from isometric tiled map
I followed the tutorial here to generate box2d bodies from a tiled map and that worked fine.... for orthogonal tiled maps. Unfortunately isometric maps use their own coordinate system where (0, 0) is at the leftmost corner of the map, and this causes the bodies to be in the wrong place.

I tried implementing a transformation matrix or just transforming the body but I don't think that is possible (or at least I could never find a way). How else can this be solved? Here is the relevant method that needs to be changed:

```
private Shape getPolygon(PolygonMapObject polygonObject) {
    PolygonShape polygon = new PolygonShape();

    float[] vertices = polygonObject.getPolygon().getTransformedVertices();

    float[] worldVertices = new float[vertices.length];

    for (int i = 0; i < vertices.length; ++i) {
        worldVertices[i] = vertices[i] / units;
    }

    polygon.set(worldVertices);
    return polygon;
}

```

As you can see I need a way to convert the isometric coordinates to game coordinates using just plain math or something else like a matrix. I think the only line needing to be changed is the line in the for loop.

# Answer
> 1 votes
I had the same question that I have been able to answer here Box2d collision on isometric maps built in Tiled

Get the vertices out of the polygon and transform them from orthographic space to isometric with code like this.

```
public static Vector2 TwoDToIso(Vector2 point){
   Vector2 vel2 = new Vector2();

   vel2.x = point.x - point.y;
   vel2.y = -(point.x + point.y) / 2;
   return vel2;
}

```

I had to minus the y value in my example because my object was flipped incorrectly.

I hope this helps

---
Tags: libgdx, box2d, tilemap, isometric
---


title: Bad quality of the sprite in Unity

text:
# Question
Title: Bad quality of the sprite in Unity
I need to import a few sprites (background platform and sky) into my game scene but it seems that their quality after importing into Unity is too bad (they are blurred). The original resolution of this two images is big enough (2048 X 400 for background) and they are looking very nice in standard Windows image viewer. Here are the settings for these two textures:

**maxSize = 2048 Format = truecolor TextureType = Sprite(2d)/nGUI FilterMode - point**

I am using Unity2D 4.5 Target resolution of my project is 1280\*800.

Can anyone help me to solve these problem? As you can see the grass on foreground looks very bloory (1 picture) Texture settings (2 picture) Original image (3 picture)

# Answer
If they get blurred be aware to import them in "Advanced" mode and disable "Mip Mapping" generation. Next check if any level of compression or filter is applied. Sometimes the filter tend to eat details of your image (try Point Filter or Bilinear Filter with small Anisotropic Level) Also the best result is obtained when your textures are painted "pixel perfect" in your scene. Try to import them as Truecolor without compression As a last resource try to import them in "GUI/Editor Legacy Mode"
> 1 votes

# Answer
Click on the resolution panel, in the Game section of the Editor, and then uncheck the "Low resolution" checkbox. I think they check that so the execution is faster when testing, but it blurs everything out and makes things look bad.
> 0 votes

---
Tags: unity, textures, sprites
---


title: Good Game Dev Engine?

text:
# Question
Title: Good Game Dev Engine?
I'm new to game dev, and would like to know a good engine/program to code games with. I tried C#, and generally enjoyed the experience, but found that without something like MonoGame or XNA Studio, it was too slow and CPU-reliant for game dev. i also tried Unity, but found that I don't enjoy using a graphical interface, and prefer just coding with only a bit of graphical interface, like with Visual Studio. I have also tried Java, and quite enjoyed the experience, so that might work. My question is: what is a good way to make a game with mostly writing code? Any help would be appreciated! :D

# Answer
For Java you could uses LWJGL, libgdx, or SFML (with java bindings) but as for C#, MonoGame/XNA are kinda your best options for premade engines.

You can always get OpenGL/GLEW in either Java or C# and write your own engine from scratch. If you're not familiar with certain design concepts and theory it may take (a lot) longer, but you'll know your engine inside out.

Best of luck on your game!
> 1 votes

# Answer
Normally would comment this but app won't let me so I'll provide as an answer.

There is absolutely nothing in unity that says you have to use their GUI beyond browsing your files and importing assets. You can work almost exclusively in Visual Studio in C# and still take advantage of all short cuts and pre-built functionality of Unity, not to mention the built in support for cross platform deployment.

I personally do not use Unity so this is not the Pov of a fanboy, but in the past I have used it as described. My personal choice is UE4 but if you don't like gui and don't want to work in C++ (mostly managed by engine) it's probably not for you.
> 1 votes

---
Tags: ide
---


# Question
Title: SDL2 Textures bleeding / 1px border around tile maps - SDL_RenderCopyEx taking integer arguments
https://forums.libsdl.org/viewtopic.php?t=9486 This post gives a good indication of my question.

Basically if you set SDL2 logicalScale or otherwise and render textures at native window resolution they appear fine. However, with tile maps if you resize the window in anyway, you get a bleed where an integer rounding issue creates a 1px border around certain tiles.

Is my only option to create a 1px border around all my images to stop this bleed / rounding error? Or a semi-transparent border with the main color. What are my options? Is this solved in any of the latest SDL2.X.Y ?

EDIT: A simpler method I have used is reducing my images from 64x64px to 62x62px in SDL2 (not the actual sprite) and using it's own sprite as a 1px border, and using Render Scaling to scale up that 1px, which stops bleed. It reduces the quality on background images ever so slightly, but it requires no tweaking of any code or sprites... but again wondering if there's a more elegant solution.

# Answer
> 1 votes
The option I went with is to use an SDL\_Texture as a Render Buffer created with `SDL_TEXTUREACCESS_TARGET` (But still using a logical screen size in the renderer). The Renderer can copy any number of textures onto the buffer, then after all rendering is done, change render target to the window and copy the buffer to the window.

An example can be found here: https://gist.github.com/Twinklebear/8265888

# Answer
> 1 votes
This is definitely a short-coming of the renderer implementation. There are however a few things you could try:

1. `SDL_RenderSetIntegerScale`

This restricts the logical viewport to scale with integer values, which should remove rounding errors from the rendering.
2. One option, which I used myself after giving up on this issue, is to roll your own rendering code. It's not that difficult, basically you just drop the logical scale from your code and instead calculate a scale factor yourself, and then use that to scale your destination rectangle before rendering. Of course, with this, you might have to handle some stuff a little more complicated (screenspace vs worldspace), but as a bonus, you can easily enabled or disable the scaling, and so you can for an example render your UI at full resolution, but scale the game world 4x the original size.

---
Tags: textures, rendering, sdl2
---


# Question
Title: SDL_RenderPresent is writing over the previous frame
Whenever I call `SDL_RenderPresent`, the previous frame is replaced with black before the new frame is displayed. It's almost like when I call `SDL_RenderPresent(renderer)`, it automatically calls `SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255)` and then`SDL_RenderClear(renderer)`.

I want to keep the previous frame because only 100 pixels are changed per frame. How do I prevent it from writing over the previous frame?

Here's an example:

```
// Error checking removed for clarity
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow("title", 0, 0, width, height, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);

// after some other, non-SDL related stuff, I run this code:
SDL_Rect a = {
    .x = 0,
    .y = 0,
    .w = 100,
    .h = 100
};
SDL_Rect b = {
    .x = 200,
    .y = 0,
    .w = 100,
    .h = 100
};

SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0x00);
SDL_RenderClear(renderer);

SDL_SetRenderDrawColor(renderer, 0xFF, 0x00, 0x00, 0xFF);
SDL_RenderDrawRect(renderer, &a);
SDL_RenderPresent(renderer);
// A red outline of a square is displayed on a white background
SDL_Delay(2500);

SDL_SetRenderDrawColor(renderer, 0x00, 0xFF, 0x00, 0xFF);
SDL_RenderDrawRect(renderer, &b);
SDL_RenderPresent(renderer);
// A green outline of a square is displayed on a black background.
// The red outline is gone.
SDL_Delay(2500);

```

How do I prevent SDL\_RenderPresent from painting over the previous frame with black? Why is it doing that even though I'm not telling it to clear between the presents?

# Answer
To get past this, you might be able to use a texture buffer which you render to **before** rendering to the window. This is accomplished with creating a texture with `SDL_TEXTUREACCESS_TARGET`, and using `SDL_SetRenderTarget`.

A link with an example can be found here: https://gamedev.stackexchange.com/a/143394/95877

Note: I do not know the intricacies of this, and the wording does not state this "backbuffer" only applies to a window, but since `SDL_RenderClear` only clears the current rendering target with the current color, if you do not call this on a texture, I see no reason the texture itself would ever be invalidated, as it is a texture of course.
> 3 votes

---
Tags: c++, graphics, sdl, c, sdl2
---


# Question
Title: Render to texture and then to screen cause flickering
So I have my class `vItem` which has a vector (consider elements like layers) of textures, origin rects and destination rects plus other stuff.
Basically whenever I update any of the layers in the vector I redraw everything on an internal texture which is then displayed on the screen, here's the function that draws on the texture:

```
void vItem::draw(){
    if(sprites.size() <= 0)
        return;

    // This calculates the dimensions of a rectangle big enough to contain every texture
    SDL_Point size = calculateSpriteRect();

    if(size.x <= 0 || size.y <= 0)
        return;

    // If the final texture does not exists or its dimensions are different from the new rectangle I destroy it and recreate it
    if(final_sprite == NULL || size.x != final_sprite_size.x || size.y != final_sprite_size.y){
        if(final_sprite != NULL)
            SDL_DestroyTexture(final_sprite);
        final_sprite = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, size.x, size.y);
        SDL_SetTextureBlendMode(final_sprite, SDL_BLENDMODE_BLEND);
        final_sprite_size = {size.x, size.y};
    }

    SDL_RenderPresent(renderer);
    SDL_SetRenderTarget(renderer, final_sprite);
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
    SDL_RenderClear(renderer);
    for(int i = 0; i < sprites.size(); i++){
        SDL_SetTextureAlphaMod(sprites[i].sprite, sprites[i].alpha);
        SDL_RenderCopy(renderer, sprites[i].sprite, &sprites[i].source, &sprites[i].bounds);
    }
    SDL_RenderPresent(renderer);
    SDL_SetRenderTarget(renderer, NULL);
}

```

The problem comes after this function: I have a child class of `vItem` called `vButton` where I have two layers of text (one normal and the other on for when the mouse is over the button), and when I update alpha values of the layers to hide one level and show the other one `draw()` is called. This transition causes an instant flickering (black background right before drawing).
When I removed vSync I noticed that this wasn't happening anymore, but I need vSync.

**UPDATE:**
Ok... Apparently if I remove both `SDL_RenderPresent(renderer);` the flickering is gone and everything is rendering correctly, but I can't understand why. This is the final function:

```
void vItem::draw(){
    if(sprites.size() <= 0)
        return;

    // This calculates the dimensions of a rectangle big enough to contain every texture
    SDL_Point size = calculateSpriteRect();

    if(size.x <= 0 || size.y <= 0)
        return;

    // If the final texture does not exists or its dimensions are different from the new rectangle I destroy it and recreate it
    if(final_sprite == NULL || size.x != final_sprite_size.x || size.y != final_sprite_size.y){
        if(final_sprite != NULL)
            SDL_DestroyTexture(final_sprite);
        final_sprite = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, size.x, size.y);
        SDL_SetTextureBlendMode(final_sprite, SDL_BLENDMODE_BLEND);
        final_sprite_size = {size.x, size.y};
    }

    //SDL_RenderPresent(renderer);
    SDL_SetRenderTarget(renderer, final_sprite);
    //SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
    //SDL_RenderClear(renderer);
    for(int i = 0; i < sprites.size(); i++){
        SDL_SetTextureAlphaMod(sprites[i].sprite, sprites[i].alpha);
        SDL_RenderCopy(renderer, sprites[i].sprite, &sprites[i].source, &sprites[i].bounds);
    }
    //SDL_RenderPresent(renderer);
    SDL_SetRenderTarget(renderer, NULL);
}

```

How can the renderer keep information about the texture on texture rendering and texture on screen rendering at the same time (since I have only one `SDL_RenderPresent()` left at the end of my game loop)? Is it meant to work like that?

# Answer
> 1 votes
I figured this out! So I was working on my SDL2 Rendering code using a buffer texture with `SDL_TEXTUREACCESS_TARGET` which **showed the same problem as yourself (aka did not work)** and it looked like this:

```
if(SDL_RenderClear(Global->renderer))
{
    /*  Error... omitted for readability... */
}

/* render all my textures, such as cars, ships, anything on the window... */

SDL_RenderPresent(Global->renderer);

setRendererTarget(NULL);

if(SDL_RenderCopy(Global->renderer, Global->textureBuffer, NULL, NULL))
{
    /*  Error... omitted for readability... */
}

SDL_RenderPresent(Global->renderer);

if(SDL_RenderClear(Global->renderer))
{
    /*  Error... omitted for readability... */
}

setRendererTarget(Global->textureBuffer);

```

The gist of my and yours to an extent code was:

* Render Clear
* Render all textures to screen
* Render Present
* Switch Render Target to Window
* Render Copy Texture Buffer to Window
* Render Present
* **Render Clear**
* Switch Render Target back to Texture Buffer

I've highlighted in bold the issue. We're clearing the screen AFTER a Render Present not BEFORE. But doesn't the game loop just clear at the top of the loop, rather than at the bottom?

```
while(1)
    clear?
    Render Stuff...
    clear?

```

No, because at the end of a game loop is an SDL\_Delay, which means in a 1/60th of a second, the screen is cleared, rather than AFTER the delay, which is 1 game tick and nothing is presented on the screen for "real time".

```
while(1)
    clear!
    Render Stuff...
    SDL_Delay!

```

`SDL_RenderClear` clears the target (not internal backbuffer). The implementations for this is system Dependant here: https://github.com/spurious/SDL-mirror/search?utf8=%E2%9C%93&q=RenderClear+%3D+&type=

So the actual list of operations needs to be:

* Render Clear
* Render Copy
* Render Present
* FPS Delay

For any rendering. Case closed!

---
Tags: sdl2
---


# Question
Title: In OpenGL, what does it mean to make a context current?
I have a few questions :

1 - What does it mean to make a context current? Does it mean that all subsequent OpenGL calls will apply to that context/window?

2 - With GLFW3, how to use multiple windows (say, 2)? Is it enough to create 2 windows/contexts, make the context current on the first one, draw things, then make the context current on the second window, and draw things?

3 - How does it all fit together with an OpenGL loading library (like gl3w)? When I initialize gl3w once after creating the contexts, will the OpenGL calls work on the context that is current even if I change it alot or will I have to re-initialize gl3w each time I make another context current?

# Answer
1. Yes. OpenGL is after all, a huge state machine.
2. Yes. A later edit to specify an important thing: You SHOULD NOT use 2 OpenGL contexts to draw in multiple "spaces", but use a GUI-builder for in-game windows, such as Inventory or Character Stats.
3. You do not have to re-initialize it every time. All you have to do is initialize gl3w inside the "pre-start" global function(just my preference, you can do it anywhere). After that, you can use OpenGL calls in any context. However, I recommend that you discard gl3w and use glbindings, as the latter offers C++11 support and A LOT more safety than gl3w.
> 1 votes

---
Tags: opengl, glfw
---


title: Walking over walls - Game maker studio

text:
# Question
Title: Walking over walls - Game maker studio
I am having an issue with the walls in my game. I have set them as objects and used the script:

depth = -y;

inside their create event.

However, when I walk my character in front of them, the correct depth is only kept until the character kindof goes half in front of the wall.

Like this:

These are the collision shapes

And this shows how I inherit from one door parent and add the depth = -y; script to the create event of the wall child.

My character also has depth = -y; but on its step event.

# Answer
> 1 votes
1. You should use `depth = -y;` in `Step End`, not `Step`.
2. Where is sprite's origin? It must be at bottom of the sprite (the lowest point of the sprite)(this applies to each object/sprite where used `depth = -y;`)

---
Tags: game-maker, depth
---


# Question
Title: Change alpha value of the Standard Shader
I want to edit the Standard shader provided by Unity in order to change the alpha value of a fragment (pixel) according to given parameters I pass to the shader.

For now, thanks to this link, I have been able to :

1. Retrieve the standard shader,
2. Retrieve a custom `Core.cginc` I included in the `DEFERRED` pass of the custom shader,
3. Create a custom Editor script to handle the Shader and my custom parameters,
4. Selecte `Fade` as the rendering mode of the shader to handle transparency, using the custom editor script,
5. Create a custom file replacing `UnityStandardInput.cginc` and changed the references in the `Core.cginc` file.

But now, I can't seem to figure **where** to change the alpha value of the fragment. I've tried a ton of possibilities in the `Core.cginc` file. Changing the **color** and the **map** of the Albedo works, but I can't find where the final alpha value is set.

I've browsed the files in the `CGIncludes` folder in the builtin shaders of Unity.

* `UnityStandardCore.cginc` : Already tried many possibilities (including the returned value of `Alpha` declared in `UnityStandardInput.cginc`
* `CustomInput.cginc` : `Alpha` function, no effect

Since the files are huge, I don't feel it will be useful to copy-paste them here.

Thanks for your help in advance.

# Answer
> 1 votes
I have been able to solve it myself. In the end, you will need at least 6 files :

* Shader file itself
* Core.cginc
* CoreForward.cginc
* CoreForwardSimple.cginc
* Input.cginc
* Meta.cginc

In all these files, replace all the references to the `UnityStandardXXX` by your custom files. Don't miss any !

Then, in the Core.cginc file, I've edited the `FragmentSetup` function to change the value of the `alpha` variable : `half alpha = Alpha(i_tex.xy) ;`

---
Tags: unity, shaders
---


# Question
Title: How can I create a height-based volumetric fog?
Recently, I have been looking for techniques to make volumetric fog on some Y position level of the game world. But all I have found are some fog made by using particle system or built-in engine fog that doesn't really fit what I'm looking for.

In my case, I need a fog that is both efficient and dense. It should be all over the gameworld, but obviously, for performance reasons, it can be rendered only as a part of a camera or shader and look like it's moving though it's just an illusion. I could set a particle system if it's the best choice, attach it to the camera and make it move.

So the main question still stays - how can I implement a volumetric fog that is both dense and performs efficiently?

As a particular engine I'm using, it's Unity.

As an example what I mean, here is the link to a game with the effect I'm looking for: Astromike

# Answer
I'm the creator of Astromike. :)

Actually, I'm using a pretty simple trick to make it look like fog. I'm developing Astromike using Unity, so if you use Unity, you can do the same. But I assume you can also recreate the same shader for other engines.

What I do is, I set up a plane for the fog, and add a material with Particle / Alpha Blended with a Soft Particle Factor (0.32 in my case) shader on. That's it.

Fog plane: https://i.stack.imgur.com/E5XEq.jpg

Settings: https://i.stack.imgur.com/NK02l.jpg

It works for me due to the camera angle and might not work for other people.

The rest is just post-effect stack ( Bloom, Vignette, etc.. ) Hope this helps. Cheers.
> 29 votes

---
Tags: unity, shaders, rendering, fog
---


# Question
Title: How do I prevent a Box2d dynamic body from sticking to static body walls in zero gravity?
I'm still making this air hockey game. I have it mostly there now, but the dynamic body which is the puck always sticks to the walls (static body rectangles that form the border of the table).

I read on box2d forums that there is a setting called `b2_velocityThreshold`, which needs to be set to 0 for games like billiards. I'm assuming that would help me, here, but I can't find any such setting in libgdx box2d.

Is there any setting which I can change to allow the puck to bounce off the walls? If not, how should I go about making such a game in libgdx?

# Answer
To change the velocityThreshold in libgdx you use this code

```
World.setVelocityThreshold(0f);

```
> 2 votes

---
Tags: java, libgdx, box2d, physics-engine
---


# Question
Title: SFML Animation class as a strategy or an inheritance
everybody. I need to add animations to my game. And I have a question.

I found AnimatedSprite class on SFML Github which is an inheritance, but in my project, I am using a lot of elements made with strategy pattern, for example movement behavior, jumping behavior, fighting behavior, etc. I just try to avoid inheritance because it makes class inflexible.

But this time in contrast to other classes Animation class has a lot of methods that can be used at runtime. I mean Play(), Stop(), Pause(), and more. If I use this as a strategy I would have to give access to this object.

What do you think? Maybe I just need to use another design pattern?

# Answer
> 0 votes
You should include the `AnimatedSprite` class with composition (so not inheritance). By letting the class itself handle the animations, you won't need to give exterior access to the class. For example, following the update pattern, each time the entity updates, it could check if the current state dictates that the entity should be animated, and call the Play(), Pause(), or Stop() methods accordingly. On top of this, you could provide a method in your entity to change the animation, which would let the entity swap the current animation it is drawn with (or just let the entity handle that itself in its update method). In my own game, I have implemented this by having a vector of animations, and a variable to hold the index of the one I want to draw every tick.

Hope this helps! Sorry I can't include code right now as I'm typing from my phone

---
Tags: c++, animation, sfml, strategy, inheritance
---


# Question
Title: Apply new default transform values for gameobject
I'm not sure if the title is correct. But how does one go about the following:

I imported a mesh created in blender.When i import the object it is at the desired rotation and scale, however, when i look at the properties of the transform the scale is 100 and the rotation is 89.9123xxxxxxx.

Is there any way i can rotate it to the desired rotation, scale it to the desired scale then tell unity that it should update the prefab and set this new rotation as 0,0,0 and the scale as 1,1,1.

Reason behind this, is i am tiling a few prefabs, and the rotations are being used.... after a couple of hundred tiles, there are floating point errors.

# Answer
> 1 votes
You're probably best off using a script to wrap externally created meshes. This way you can let your script handle everything automatically. I struggled a lot to handle models because of the issue you mentioned. Especially the default rotation caused some trouble.

The basic idea is to make your model a child of an empty GameObject which you instantiate yourself. So you don't drag & drop models in your scene but use a Prefab object with the following script instead:

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

using UnityEngine;

public class Model : MonoBehaviour {

    public string resourceName = "default";

    private static string resourcePrefix = "Models/";
    private GameObject _model = null;

    void Start () {
        var name = resourcePrefix + resourceName;
        var resource = Resources.Load (name);

        if (resource == null) {
            UnityEngine.Debug.LogError ("unable to load '" + name + "'");
            return;
        }

        this._model = GameObject.Instantiate (resource) as GameObject;

        if (this._model == null) {
            UnityEngine.Debug.LogError ("unable to instantiate '" + name + "'");
            return;
        }

        this._model.transform.parent = this.transform;
        this._model.transform.localRotation = Quaternion.Euler (-90f, 180f, 0f);
        this._model.transform.localPosition = Vector3.zero;
    }
}

```

This is just a basic example but you get the idea. The above rotation `Quaternion.Euler (-90f, 180f, 0f)` works with Blender so you don't have to create your models upside down and stuff like that.

Having a script take care of this gives you a lot of control. You can easily extend the logic to handle stuff like changing the model at runtime or initializing materials properly instead of using the imported ones with something like:

```
public List<Material> materials = new List<Material> ();

private void SetupMaterials () {
    if (this._model != null) {
        var renderer = this._model.GetComponent<MeshRenderer> ();
        var meshFilter = this._model.GetComponent<MeshFilter> ();

        if (renderer != null && meshFilter != null) {

            if (meshFilter.mesh.subMeshCount != materials.Count) {
                UnityEngine.Debug.LogWarning ("submesh count != materials.Count");
            }

            renderer.materials = materials.ToArray ();
        }
    }
}

```

**Note:** Just make sure to store your models somewhere in **Assets/Resources/**, otherwise `Resources.Load ()` won't find your data.

Hope this helps!

---
Tags: unity, transformation
---


# Question
Title: What's wrong with using physics engine in 2d platformer?
I started making my simple 2D runner game with a splash of physics (particularly, rope physics). It's in Love2d, project is targeting mobile platforms. Development goes fine, though I meant to ask one thing. Referencing this page: https://love2d.org/wiki/love.physics

The message at the top warns against using the physics engine for a platform game, and has an anology to heavy-lifting, but no good explanation as to what might go wrong, what exactly is so hard about it and why should I stay away from it. Because so far I have my basic idea implemented and no bad experiences here. As to good ones, I was able to abstract all the collision handling and let physics engine just do it for me.

Given that using the physics engine for my platformer seemed to work well in my initial test, why do many people consider it a bad idea? I mentioned some upsides but what are the downsides?

# Answer
> 3 votes
It's not necessarily a completely terrible idea but there are significant cons to weigh against the pros you mention. In particular, the physics in a platformer character usually isn't totally (or even very) realistic, but a physics engine handles realistic and consistent physics. You may end up fighting against the physics engine to implement things like, say, one-way platforms that you can jump through from below but collide from above.

Myself, I actually just implemented a basic 2D platformer in Unity using the built-in physics (for the upcoming second edition of my book) and it worked out pretty well, but then Unity comes with special components to help deal with platformer physics.

# Answer
> 2 votes
This is a matter of opinion.

The reference you gave seemed to arguing that depending on what you wanted, using a physics engine could be overkill. I think many of us that have used a physics engine would agree with that opinion if for instance the design of a game didn't need to deal with collision responses. And I interpret what the linked text said as just trying to say that. On the other hand, if the game has collisions that should be dealt with, a physics engine can be easier to use than reinventing all the code necessary to do it yourself.

Hope this helps.

---
Tags: physics, box2d, platformer, love2d
---


# Question
Title: How to detect collision in C# script not attached to any game object
I have public variables which I populate through the inspector. One script is attached to a single object and the other script has a gameObject array property. Please see below:

```
public class GamePlayScript : MonoBehaviour {

public BallScript ballScript;
public BrickGroupsScript brickGroupsScript;

// Use this for initialization
void Start () {

}

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

}
}

```

`BrickGroupsScript` contains an array of `bricks` which has a `isBroken` `bool` property. Also the above code is attached to an empty game object. How can I detect when the ball game object is in contact/collided with a brick with `isBroken = true`?

# Answer
As far as I know, you can't detect collision without a script implementing `OnCollisionEnter`.

You can attach the following script to **all of your bricks** which will dispatch/raise an event when something collided into it :

```
public class Brick : MonoBehaviour
{
    public event System.EventHandler OnTouched;

    void OnCollisionEnter(Collision collision)
    {
        if ( OnTouched != null )
            OnTouched( this, System.EventArgs.Empty );
    }
}

```

Then, supposing you have an array of `Brick`s, you can subscribe to the `OnTouched` event :

```
[SerializeField]
private Brick bricks ;

private void Start()
{
    for( int brickIndex = 0 ; brickIndex < bricks.Length ; ++brickIndex )
        bricks[brickIndex].OnTouched += OnBrickTouched;
}

private void OnBrickTouched( object sender, System.EventArgs e )
{
    Brick brick = (Brick) sender;
    // Do something with your brick
}

```

---

EDIT : After reading again your question, you want to detect collision on the ball. The principle is the same, check the scripts below.

```
public class BallEventArgs : EventArgs
{
    public BrickScript Brick;
    public BallEventArgs(string brick)
    {
        Brick = brick;
    }
}

public class BallScript : MonoBehaviour
{
    public event System.EventHandler<BallEventArgs> OnBrokenBrickTouched ;

    void OnCollisionEnter(Collision collision)
    {
        Brick touchedBrick = collision.collider.GetComponent<Brick>();

        if ( touchedBrick != null && touchedBrick.isBroken && OnBrokenBrickTouched != null )
            OnBrokenBrickTouched ( this, new BallEventArgs(touchedBrick) );
    }
}

// ........

public class GamePlayScript : MonoBehaviour {

    public BallScript ballScript;
    public BrickGroupsScript brickGroupsScript;

    // Use this for initialization
    void Start () {
        ballScript.OnBrokenBrickTouched += OnBrokenBrickTouched ;
    }
    private void OnBrokenBrickTouched( object sender, BallEventArgs e )
    {
        BallScript ball = (BallScript) sender;
        BrickScript brick = e.Brick;
        // Do something with your ball and your brick
    }
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: Unwanted begincontact callbacks at high velocity
I'm having some issues with jump detection due to begincontact. I have a player entity made of 2 bodies, and it looks something like this:

Note how the circle below (a body connected via a revolute joint) is not quite as wide as the rectangle. This means that when the player is up against a wall, there is no contact between the circle and the wall.

However, if the player collides with a wall at high velocity, begincontact registers a contact between the circle and the wall. Is there any way around this?

# Answer
There are a number of ways you can get around this depending on your situation.

If all the walls are vertical and it is never the intention for the circle to hit the wall then you can set up contact filtering using the `catergoryBits` and `maskBits` on the `FixtureDef.filter` to filter out any collisions between the circle and walls.

If the circle should be able to *sometimes* hit the wall except for when it hits it side-on then you can manually filter the contact in `beginContact` by measuring the delta between the center of the circle and the contact point. If this delta is small, then ignore the contact (which you can do by calling `setEnabled(false)`).

And example of the latter may look something like this (this is in Java, I don't know what language you're using but it should be trivial to port);

```
world.setContactListener(new ContactListener() {
    private Body tryGet(Body body, String bodyUserData) {
        return body.getUserData() != null && body.getUserData().equals(bodyUserData) ? body : null;
    }

    private Body tryGet(Contact contact, String bodyUserData) {
        Body body = tryGet(contact.getFixtureA().getBody(), bodyUserData);
        return body != null ? body :  tryGet(contact.getFixtureB().getBody(), bodyUserData);
    }

    @Override
    public void beginContact(Contact contact) {
        torsoCollided |= tryGet(contact, "torso") != null;

        Body feetBody = tryGet(contact, "feet");
        if  (feetBody != null) {
            WorldManifold manifold = contact.getWorldManifold();

            // Should really check numPoints here to see how many contact points
            float contactY = manifold.getPoints()[0].y;
            float bodyY = feetBody.getWorldCenter().y;

            // If difference in the vertical is small then the circle (feet) hit the wall
            // side on, which is impossible if the torso is wider and the torso can't rotate
            boolean isValidCircleContact = Math.abs(contactY - bodyY) > 0.001f;
            feetCollided |= isValidCircleContact;
            contact.setEnabled(isValidCircleContact);
        }
    }

    @Override
    public void endContact(Contact contact) {
        contact.setEnabled(true);
    }

    @Override
    public void preSolve(Contact contact, Manifold oldManifold) { }

    @Override
    public void postSolve(Contact contact, ContactImpulse impulse) { }
});

```

*The above assumes there being user data on the box set to "**torso**" and to "**feet**" on the circle, `torsoCollided` and `bodyCollided` are fields cleared to `false` before calling `world.step` on every iteration which you may or may not have any use for.*
> 1 votes

# Answer
When you get over a certain speed, you can try to increase red rectangle width proportionaly(?) to object speed. May be also usefull to define a max object speed.
> 0 votes

---
Tags: box2d
---


# Question
Title: How to instantiate a child object in UNet without it lagging behind its parent over the network?
When I use `NetworkServer.Spawn(ob)` t instantiate a game object and make it a child of a `transform.parent` after it spawns on both the server and client, it usually lags, meaning it takes some seconds to align with the `transform.parent` which is the player.

Example : Instantiating a `GameObject` containing a `ParticleSystem` which gives the parent somewhat an effect, like smoke or something. On the host client every object has smooth movement whereas on the connected client it goes very rough and slow, like every game object running at a low fps except the main client player prefab

So I was thinking of spawning the same effect on both clients so it wouldn't have to sync from the server to the client which uses it, instead it only would have to sync inside the client's game. It might not have the same particle movements, but it wouldn't make a difference

Here's the child prefab's network identity and transform:

# Answer
Here is the link to documentation about remote actions, that's what you need https://docs.unity3d.com/Manual/UNetActions.html

Just one more thing, in the image the UpdateRate are insane (29), i dont know what you are building but, probably you dont need this. It's a better idea reduce this number and add some interpolation in the rigidbody of you object if you need smoth movement.

If you just dont need sincronization you can simply put update rate in 0. Done.

Good look
> 0 votes

---
Tags: unity, unity-networking
---


# Question
Title: Moving an object forward relative to the distance traveled by another object
I am trying to achieve the camera follow like Ketchapp's game "Zigzag".

I will try to explain the best I can; I have two objects, Player (a sphere) and Camera:

* Player can only move to the left and forward.
* Camera moves forward and always keeps the same distance from the player.

I have tried different things like moving the camera and player at the same speed and decreasing/increasing the speed of camera depending on the distance between them, but in vain.

You can watch the gameplay here https://www.youtube.com/watch?v=5XbPcubaTJI Note how the camera follows the player and just moves forward (not to the left or to the right).

# Answer
The player is just moving left to right. The player is not moving forward and the camera isn't moving forward either. The scrolling background gives the impression of moving forward.

So to achieve a camera to follow like "Zigzag", well you just don't move your camera at all, but move the level!
> 1 votes

---
Tags: unity
---


# Question
Title: How to render multiple triangles using single VBO in OpenGL (LWJGL)?
I'm new to OpenGL and trying to render multiple triangles using single VBO in using LWJGL3. I've followed demos and read some books and wrote following code, but its not drawing my shape. I use vertex and fragment shader.

It prints following log and not drawing anything.

```
0(6) : warning C7533: global variable gl_FragColor is deprecated after version 120

Fragment info
-------------
0(6) : warning C7533: global variable gl_FragColor is deprecated after version 120

[LWJGL] OpenGL debug message
    ID: 0x20071
    Source: API
    Type: OTHER
    Severity: NOTIFICATION
    Message: Buffer detailed info: Buffer object 1 (bound to GL_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations.

```

Here's the source code of runnable class:

```
package mn.digz.lwjgl;

import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.system.MemoryUtil.NULL;

import java.io.IOException;
import java.nio.FloatBuffer;
import mn.astvision.assetmanagement.lib.lwjgl.util.ShaderUtil;

import org.joml.Matrix4f;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GLCapabilities;
import org.lwjgl.opengl.GLUtil;
import org.lwjgl.system.Callback;

/**
 *
 * @author MethoD
 */
public class OpenGLGraphRender {

    long window;
    int width = 1024;
    int height = 768;

    int vao;
    int program;

    int viewProjMatrixUniform;

    Matrix4f viewProjMatrix = new Matrix4f();
    FloatBuffer matrixBuffer = BufferUtils.createFloatBuffer(16);

    FloatBuffer verticesBuffer;
    int vertexPositionAttribute;
    int vertexColorAttribute;
    int pointSize = 3 + 4; // x,y,z + r,g,b,a
    int step = Float.SIZE / 8; // byte per element
    int stride = step * pointSize; // need?

    GLFWErrorCallback errCallback;
    Callback debugProc;

    void init() {
        glfwSetErrorCallback(errCallback = GLFWErrorCallback.createPrint(System.err));

        if (!glfwInit())
            throw new IllegalStateException("Unable to initialize GLFW");

        glfwDefaultWindowHints();
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
        glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
        glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);

        window = glfwCreateWindow(width, height, "Silhouette rendering with geometry shader", NULL, NULL);
        if (window == NULL) {
            throw new AssertionError("Failed to create the GLFW window");
        }

        GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
        glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);
        glfwMakeContextCurrent(window);
        glfwSwapInterval(1); // enable v sync
        glfwShowWindow(window);
    }

    void createProgram() throws IOException {
        int program = glCreateProgram();
        int vshader = ShaderUtil.createShader("mn/astvision/assetmanagement/lib/lwjgl/shader/vs.glsl", GL_VERTEX_SHADER);
        int fshader = ShaderUtil.createShader("mn/astvision/assetmanagement/lib/lwjgl/shader/fs.glsl", GL_FRAGMENT_SHADER);
        glAttachShader(program, vshader);
        glAttachShader(program, fshader);

        glLinkProgram(program);
        int linked = glGetProgrami(program, GL_LINK_STATUS);
        String programLog = glGetProgramInfoLog(program);
        if (programLog != null && programLog.trim().length() > 0) {
            System.err.println(programLog);
        }
        if (linked == 0) {
            throw new AssertionError("Could not link program");
        }
        this.program = program;
    }

    /**
     * Initialize the shader program.
     */
    void initProgram() {
        glUseProgram(this.program);
        viewProjMatrixUniform = glGetUniformLocation(this.program, "viewProjMatrix");

        glBindAttribLocation(program, 0, "vertexPosition");
        glBindAttribLocation(program, 0, "vertexColor");
        vertexPositionAttribute = glGetAttribLocation(program, "vertexPosition");
        vertexColorAttribute = glGetAttribLocation(program, "vertexColor");

        verticesBuffer = BufferUtils.createFloatBuffer(pointSize * 3 * 3); // point size * 3 points * 3 triangles = 21 floats per triangle
        verticesBuffer.put(new float[] {0f, 0f, 0f, 1f, 1f, 0f, 1f, 2f, 0f, 0f, 1f, 1f, 0f, 1f, 1f, 1.7f, 0f, 1f, 1f, 0f, 1f});
        verticesBuffer.put(new float[] {4f, 4f, 0f, 1f, 1f, 0f, 1f, 6f, 4f, 0f, 1f, 1f, 0f, 1f, 5f, 5.7f, 0f, 1f, 1f, 0f, 1f});
        verticesBuffer.put(new float[] {4f, 1f, 0f, 1f, 1f, 0f, 1f, 6f, 1f, 0f, 1f, 1f, 0f, 1f, 5f, 2.7f, 0f, 1f, 1f, 0f, 1f});
        verticesBuffer.flip();

        int vbo = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, vbo);
        glBufferData(GL_ARRAY_BUFFER, verticesBuffer, GL_STATIC_DRAW);

        glVertexAttribPointer(vertexPositionAttribute, 3, GL_FLOAT, false, stride, 0);
        glVertexAttribPointer(vertexColorAttribute, 4, GL_FLOAT, false, stride, step * 3);
        glEnableVertexAttribArray(vertexPositionAttribute);
        glEnableVertexAttribArray(vertexColorAttribute);

        glUseProgram(0);
    }

    void render() {
        viewProjMatrix
            .setPerspective((float) Math.toRadians(30), (float) width / height, 0.01f, 50.0f)
            .lookAt(0.0f, 2.0f, 7.0f,
                    0.0f, 0.0f, 0.0f,
                    0.0f, 1.0f, 0.0f);

        glUseProgram(this.program);
        glUniformMatrix4fv(viewProjMatrixUniform, false, viewProjMatrix.get(matrixBuffer));

        int numItems = 3;
        glDrawArrays(GL_TRIANGLES, 0, numItems);

        glUseProgram(0);
    }

    void loop() throws IOException {
        GL.createCapabilities();

        debugProc = GLUtil.setupDebugMessageCallback();

        glClearColor(0.55f, 0.75f, 0.95f, 1.0f);
        glEnable(GL_DEPTH_TEST);

        /* Create all needed GL resources */
        createProgram();
        initProgram();

        while (!glfwWindowShouldClose(window)) {
            glfwPollEvents();
            glViewport(0, 0, width, height);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            render();

            glfwSwapBuffers(window);
        }
    }

    void run() {
        try {
            init();
            loop();

            if (debugProc != null)
                debugProc.free();
            errCallback.free();
            glfwDestroyWindow(window);
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            glfwTerminate();
        }
    }
}

```

Here's the ShaderUtil.java

```
package mn.digz.lwjgl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import org.lwjgl.BufferUtils;
import org.lwjgl.PointerBuffer;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.system.MemoryUtil.memUTF8;

/**
 *
 * @author MethoD
 */
public class ShaderUtil {

    /**
     * Create a shader object from the given classpath resource.
     *
     * @param resource the class path
     * @param type the shader type
     *
     * @return the shader object id
     *
     * @throws IOException
     */
    public static int createShader(String resource, int type) throws IOException {
        return createShader(resource, type, null);
    }

    /**
     * Create a shader object from the given classpath resource.
     *
     * @param resource the class path
     * @param type the shader type
     * @param version the GLSL version to prepend to the shader source, or null
     *
     * @return the shader object id
     *
     * @throws IOException
     */
    public static int createShader(String resource, int type, String version) throws IOException {
        int shader = glCreateShader(type);

        ByteBuffer source = ioResourceToByteBuffer(resource, 8192);

        if (version == null) {
            PointerBuffer strings = BufferUtils.createPointerBuffer(1);
            IntBuffer lengths = BufferUtils.createIntBuffer(1);

            strings.put(0, source);
            lengths.put(0, source.remaining());

            glShaderSource(shader, strings, lengths);
        } else {
            PointerBuffer strings = BufferUtils.createPointerBuffer(2);
            IntBuffer lengths = BufferUtils.createIntBuffer(2);

            ByteBuffer preamble = memUTF8("#version " + version + "\n", false);

            strings.put(0, preamble);
            lengths.put(0, preamble.remaining());

            strings.put(1, source);
            lengths.put(1, source.remaining());

            glShaderSource(shader, strings, lengths);
        }

        glCompileShader(shader);
        int compiled = glGetShaderi(shader, GL_COMPILE_STATUS);
        String shaderLog = glGetShaderInfoLog(shader);
        if (shaderLog != null && shaderLog.trim().length() > 0) {
            System.err.println(shaderLog);
        }
        if (compiled == 0) {
            throw new AssertionError("Could not compile shader");
        }
        return shader;
    }

    /**
     * Reads the specified resource and returns the raw data as a ByteBuffer.
     *
     * @param resource the resource to read
     * @param bufferSize the initial buffer size
     *
     * @return the resource data
     *
     * @throws IOException if an IO error occurs
     */
    public static ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException {
        ByteBuffer buffer;
        URL url = Thread.currentThread().getContextClassLoader().getResource(resource);
        File file = new File(url.getFile());
        if (file.isFile()) {
            FileInputStream fis = new FileInputStream(file);
            FileChannel fc = fis.getChannel();
            buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
            fc.close();
            fis.close();
        } else {
            buffer = BufferUtils.createByteBuffer(bufferSize);
            InputStream source = url.openStream();
            if (source == null) {
                throw new FileNotFoundException(resource);
            }
            try {
                ReadableByteChannel rbc = Channels.newChannel(source);
                try {
                    while (true) {
                        int bytes = rbc.read(buffer);
                        if (bytes == -1) {
                            break;
                        }
                        if (buffer.remaining() == 0) {
                            buffer = resizeBuffer(buffer, buffer.capacity() * 2);
                        }
                    }
                    buffer.flip();
                } finally {
                    rbc.close();
                }
            } finally {
                source.close();
            }
        }
        return buffer;
    }

    private static ByteBuffer resizeBuffer(ByteBuffer buffer, int newCapacity) {
        ByteBuffer newBuffer = BufferUtils.createByteBuffer(newCapacity);
        buffer.flip();
        newBuffer.put(buffer);
        return newBuffer;
    }
}

```

Here's my vertex shader:

```
#version 150

uniform mat4 viewMatrix;
uniform mat4 projMatrix;

//in vec3 position;
in vec3 vertexPosition;
in vec4 vertexColor;

out vec4 vColor;

void main(void) {
  gl_Position = projMatrix * viewMatrix * vec4(vertexPosition, 1.0);
  vColor = vertexColor;
}

```

Here's my fragment shader:

```
#version 150

in vec4 vColor;

void main(void) {
  gl_FragColor = vColor;
}

```

# Answer
> 1 votes
There are multiple issues with the code you posted.

You're trying to use a uniform named `viewProjMatrix`:

```
viewProjMatrixUniform = glGetUniformLocation(this.program, "viewProjMatrix");

```

But that uniform doesn't exist in your shader. In the shader you have two matrices:

```
uniform mat4 viewMatrix;
uniform mat4 projMatrix;

```

You bind both vertex attributes to the same index (0):

```
glBindAttribLocation(program, 0, "vertexPosition");
glBindAttribLocation(program, 0, "vertexColor");

```

While this isn't illegal, it's not what you mean to be doing. Set `vertexColor` to `1` instead. Or get rid of those two lines and use the default locations given to them.

Strangely you then try and get get the attribute locations. You know the values, you just (incorrectly) set them both to 0.

```
vertexPositionAttribute = glGetAttribLocation(program, "vertexPosition");
vertexColorAttribute = glGetAttribLocation(program, "vertexColor");

```

You are also calling `glDrawArrays` with `3` as the count. A single triangle has 3 indices. You're trying to draw 3 triangles. That's 9 indices.

# Answer
> 1 votes
You use a perspective matrix with a near plane of 0.01 and a far plane of 50. This means that only stuff, that has a Z coordinate between these two values can be rendered. Because all your triangles have a Z coordinate of 0, they'll get culled.

---
Tags: opengl, java, lwjgl, lwjgl3
---


title: Putting each animation on a thread

text:
# Question
Title: Putting each animation on a thread
I'm trying to make my game as friendly to multi-core as possible. as such, i'm putting each animation on a new thread. I was hoping someone could check out my proof of concept code in java;

an example of usage is as follows:

```
    ThreadedAnimation ta = new ThreadedAnimation();
    Thread tat = new Thread(ta);
    tat.start();
    ta.getCurrentFrame();

```

where the threadedAnimation class is as follows:

```
public class ThreadedAnimation implements Runnable{
boolean init = false, toFinish = false, toStop = false; //synchronized info
short[] delay; //delay in ms
Image[] frames; //array for the frames
public Image currentFrame = null; //for pulling the frame
int currentFrameNumber = 0; // simmillar representation. to go barebones, I would just return the int and not the number.

public ThreadedAnimation(short[] del, Image[] fram){
    if(del.length == fram.length){
        currentFrame = fram[0];
    }else{
        System.out.println("bad animation detected");
    }
}
public ThreadedAnimation(){
    delay = null;
    frames = null;
}

@Override
public void run() {
    if(init){
        while(!toFinish && !toStop){
            currentFrameNumber = 0;
            while(!toStop && !(currentFrameNumber> frames.length)){

                long currentTime = System.currentTimeMillis();
                while((System.currentTimeMillis()-currentTime) < delay[currentFrameNumber]){// The reason I don't put TrySleep(delay[i]) is because the thread is interrupted every time we try and get the image.
                    TrySleep(10);
                }
                currentFrameNumber++;
                currentFrame = frames[currentFrameNumber];
            }

        }

    }
}

private void TrySleep(int i) {
    try {
        Thread.sleep(i);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}
public synchronized void  finish(){
    toFinish = true;

}

public synchronized void stop(){ //stops animation where it stands and kills
    toStop= true;

}

public synchronized Image getCurrentFrame(){
    return currentFrame;
}

```

}

# Answer
> 2 votes
First off, threads are expensive. That does not mean that this technique cannot work, just that it is likely to be inefficient.

In your particular case, you will have threads waking up each 10 milliseconds, and as many threads as animations you have. If you will have a thread that wakes each 10 milliseconds anyway, you could use one thread per core (with affinity set to each core) and balance the animation among those threads. That would be more efficient. *We could then consider updating each animation a “task”, and voila you have a rudimentary “task” system.*

*Or at the very least recycle your threads. Notice that when you kill the animation, the thread becomes garbage that the system has to collect and you will be creating a new – expensive – thread for any new animation. Do not do that, do a thread pool.*

What you are doing with the animation thread is a fancy clock. It should be possible to calculate what should be the current frame of the animation given the `currentTimeMillis` and the delays.

If the delays are unpredictable, that means that to calculate the current frame you would: 1) get duration of the animation by adding the delays (value that be stored and reused). 2) Do a mod of the difference of the current time minus the start time by the duration of the animation. 3) Check the resulting reminder against the delays (complexity is O(n)). On the other hand, if the delays are follow a mathematical pattern, then it can probably done much more efficiently. For example, if each frame has the same delay, you do `currentFrameNumber = ((currentTime - startTime) % (delay * frames.length)) / delay;` (complexity is O(1)).

For your threading solution to be worth doing, it should be more efficient that doing that. Moreover, guess what, you can opt to do that only when you need to show one of the sprites, meaning that you would only have to do it for the sprites on screen. Meanwhile your threads will be working for every animation in the scene… behind the scenes. *Or wasting CPU time each 10 milliseconds.*

I guess there is some edge case where you will have too many animation, of which, all of them are always on the screen, and having some animation lag in exchange of responsiveness is acceptable... then I would agree that threading the animation is a good idea... but on a thread pool, please.

---

By the way, you should be able to use the `delay` to sleep... you say:

> the thread is interrupted every time we try and get the image

That should not be the case! *I do not know why it would be… I hope you are not pausing the thread to read it. If it is an artifact `synchronized` (it should not be), then I am going to tell you to get rid of that anyway.*

---

Second, the presented code, I presume is incomplete, otherwise, it will never work because `init` will always be false.

> WHY it takes so much to animate in this method.

It takes forever if `init` is false.

If I were you I would not have `init` and I would not have a default constructor that sets fields to `null`. If you need to do some work before starting the animation, you should be able to work with the `delay` and `frames` arrays before calling the constructor. In fact, I would suggest creating an animation class that has those arrays as members… but that is off-topic.

---

Third, what will be a problem – even for a singular correctly initialized animation – is **thread visibility**. The thread is updating the field `currentFrame`, but the CPU could be keeping the value of `currentFrame` in the local cache of the threads (after all this field is accessed often), resulting in changes made by the animation thread being hidden to (not visible by) other threads.

If this is the problem, it is not that it takes so much to animate in this method, instead that the render thread becomes aware of changes of `currentFrame` too late.

What you need in this case is `volatile`. You can turn `currentFrameNumber`, `toStop` and `toFinish` to `volatile`. You could also turn `currentFrame` to `volatile`, or read from `frames` in `getCurrentFrame`.

In fact, you not only do not need `synchronized` but it counterproductive, it is a waste of resources. The `synchronized` keyword ensures is that at most one thread enters any of the `synchronized` methods of the class at the same time. Well, multiple executions of `finish` or `stop` are idempotent so they don’t need this protection, and `getCurrentFrame` reads a variable that is being set on a method that is not `synchronized` (`run`), thus using `synchronized` on `getCurrentFrame` is useless. Furthermore, `synchronized` does not guarantee visibility… so yeah. Get rid of that.

---

**Final note**: You need a game loop that uses sleep to yield CPU time to the animation thread and any other thing you might have running in the background. If your game loop is eating all the CPU time and the animation threads are not getting enough then the animation are going to lag.

*Yet, you probably should use thread for something more complex that a "flipbook animation"*, in particular something independent of the screen, so that there is some remarkable gain in using threads.\*

---
Tags: animation, multithreading
---


# Question
Title: How to implement different shapes for an area of affect spell?
Let W = wizard

Let 0 = Cast range of spell, or AOE

Here is the problem:

I have a 2D tile map of squares. Let's say I want to have a wizard cast a spell that surrounds his body equally. For this, it would be as simple as using a flood fill or Dijkstra's algorithm, and it would look like this:

```
===0===
=00000=
000W000
=00000=
===0===

```

No problem! However, how will I implement a spell, that, for whatever reason, looks like a plus sign?

```
===0===
===0===
000W000
===0===
===0===

```

Or the spell goes longer in the direction the wizard is facing?

```
=00000=
=00000=
==0W0==
==000==
=======

```

Or two different locations?

```
=======
=00====
===W===
====00=
=======

```

Or, even more awkward, its a ranged splash spell where the player can choose where they want to cast it?

```
=======
=======
===W===
======0
=====00

```

One way would be to have a list of all the locations relative to the wizard beforehand, and add them to the wizards location later. (E.g, for the affect to be 2 tiles north of the wizard, it would store (x+0, y+2), and later add them to the wizard's position, which could be at x=30, y=19, so the affect would be at x=30, y=21.)

A limitation to this, unfortunately, is that it doesn't take into account where the wizard is facing, and it feels inelegant to manually typing in all the locations that the AOE will affect.

Bottom line: How should I approach this problem and create a good, easily adjustable AOE system for a tile based map, that takes into account different AOE shapes and cast positions?

# Answer
> 0 votes
Option #1 - have the spells "hardcoded" - *"a list of all the locations relative to the wizard beforehand, and add them to the wizards location later"*. Despite the sound of it, this is rather simple solution. Especially if you are limiting spell radius to just 3-4 tiles. Hardcoding areas dependend on facing direction fits in as well. You can also use mirroring, rotation and combination of masks to reduce amount of "hardcode" and possible mistakes in updating them in sync.

Option #2 - Have the spells "parametrized". This is good for cases when spells can have larger radius and manually updating the "masks" is tedious process. Make a base spell class with abstract "area of effect" function that will return either a mask, or a hittest for each tile. Now in each child class do its implementation - for a circle spell `Result := sqrt(sqr(dX) + sqr(dY)) < R;`, for a plus spell `Result := (dX = 0) or (dY = 0)` and so on ..

If you have a lot of different spells - having a vizualization helps a lot. Either by seeing all hardcoded masks as `01110` patterns (just like you did in the question) or by having a mode/tool to preview them while dynamically editing the formulas.

---
Tags: tilemap
---


# Question
Title: Question about coding rarity and non-MonoBehaviour referencing
I have a non-MonoBehaviour script called Item which contains two classes.

```
public class Item
{
    public string itemName;
    //public string itemRarity;

    public Item(string newItemName)
    {
        itemName = newItemName;
    }
}

```

and

```
public class ItemRandomizer
{
    List<Item> itemContainer = new List<Item>();

    public void AddItem(Item item, int amount)
    {
        for (int i = 0; i < amount; i++)
        {
            itemContainer.Add(item);
        }
    }

    public Item GetRandomItem()
    {
        int index = Random.Range(0, itemContainer.Count);

        // want to return item combined with rarity
        return itemContainer[index];
    }

```

I want GetRandomItem to not only return a random item "type", e.g., gloves, contained in the itemContainer list, but also combine it with a rarity (common, rare, legendary) and return that if possible.

How can I code this functionality in a flexible way so that two base items with the same drop chance can have varying drop chances when it comes to their rare versions? Swords and axes have the same drop chance, but a rare sword might be rarer than a rare axe. I'd like to maintain that kind of flexibility.

Also, if I make public string itemRarity a property of the Item class, but I want to set the rarity tier in GetRandomItem() in the ItemRandomizer class, how should I do that? Thus far, I've almost exclusively used MonoBehaviour classes so any pointers are appreciated.

# Answer
> 0 votes
```
public class Item
{
    public string name, rarity;
    public Item(string name, string rarity)
    {
        this.name = name;
        this.rarity = rarity;
    }
}

```

Now, I would not add the same item repeatedly to the list. You can do this in a much easier way with a Dictionary:

```
public class ItemRandomizer
{
    Dictionary<Item, int> itemContainer;
    public ItemRandomizer() //Constructor. The "start" method of regular C# classes.
    {
        itemContainer = new Dictionary<Item, int>();
    }

    public void AddItem(Item item, int amount)
    {
        if(itemContainer.ContainsKey(item)
        {
            int items = itemContainer[item] + amount;
            itemContainer [item] = items;
        }
        else
        {
            itemContainer.Add(item, amount);
        }
    }
}

```

I'm not entirely sure what you want, so if I am misinterpreting you, correct me. You want to spawn an item based on its "rarity". Now, for that, you can do the following:

```
public Item GetRandomItem()
{
    Item returnval = null;
    bool foundItem = false;
    for(int i = Random.Range(0, itemContainer.Keys.Count); !foundItem; i = random.Range(0, itemContainer. Keys.Count))
    {
        returnval = itemContainer.Keys[i];
        string rarity = returnval.rarity;
        switch(rarity)
        {
            case "legendary":
                if(Random.Range(0, 101) <= 10) //10% chance of dropping.
                    foundItem = true;
            break;
            case "average":
                if(Random.Range(0, 101) <= 50) //50% chance of spawning
                    foundItem = true;
            break;
            //etc...
            default: break;
        }
    }
    return returnval;
}

```

There might be a few typos in the code, let me know if so - I'm typing this from my phone.

---
Tags: unity
---


# Question
Title: Use constant force to hold something in position
This may actually be more of a Physics.SE question but since im doing this in Unity I figured I'd ask here.

I am playing around with the Constant Force component and have a sphere constrained with a linear configurable joint (y-axis free). With one key I apply a force in one direction to get it moving, but then when i press another key, I want to stop it and hold exactly in place by using an opposite force. So even if some other rigid body hits the sphere, it wont move until I remove a force.

Unfortunately, Unity doesnt allow more than one constant force on a gameobject (probably a good reason, not sure exactly) and I know if I do a net force, that it would just end up being 0, which would kind of work but the sphere would move if it gets hit.

Another thing I tried was to take the spheres current force and constantly flip it from positive to negative every FixedUpdate but that didn't seem to work at all.

I know the quick and easy way would be to just set velocity to zero, but I see tons of comments saying that modifying velocity directly breaks the physics, is bad form, etc. and I want to do this as properly as possible.

The best way I can describe what I'm trying to do is like that science experiment where you take a ping-pong ball and use a blower to push just enough air to counter gravity and the ball seems to hover in place. My only difference is that my constraint is side to side instead of up/down.

# Answer
In your case I wouldn't use a force to get it moving at all, but instead set the position / velocity directly on response to the key presses, and mark the object as kinematic.

What you're describing is fundamentally **not** a natural movement for the sphere. You're talking about applying unrealistic forces out of nowhere to get it into a specific position/velocity. That's what kinematic objects are for - to be able to set those properties directly and then have the other objects in the simulation react to their unnatural movement.

Moving objects only by applying forces to them is great, when you want even the initiating object to move naturally (e.g. a cue ball on a pool table reacting to a non-existent cue that has struck it); but it's not required. It is common to have a single kinematic object, directly controlled by the player/user, which is causing interesting things to happy in your simulation. You may have problems when you try to have more than one kinematic object, or try to move it in a way that is so unrealistic it is beyond the ability of the physical simulation to cope, but if you are careful about how you move it, you're fine.
> 1 votes

# Answer
According to your needs there is only one thing is left, that is Is Kinematic attribute of Rigidbody. Try to turn it on when you want to stop your body.
> 0 votes

# Answer
There's two things you can try:
\- Set it to Is Kinematic, so it will not move unless you explicit do it by code.
\- Set the collision object as IsTrigger, so it will not move if another object collide with it, and to maintain the object on the air, try this:

```
float massObject = 1; // adjust for the crate mass, if needed
Rigidbody rb; //to get the rigidbody component

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

function FixedUpdate()
{
      rb.AddForce(-Physics.gravity * (rb.mass+massCrate));
}

```
> 0 votes

---
Tags: unity, physics
---


title: Separating axes theorem problem

text:
# Question
Title: Separating axes theorem problem
I´ve been following this tutorial : http://www.dyn4j.org/2010/01/sat/ to help me understand and implement the SAT for collision detection in my games as I want to add a support for polygons. However, I´m facing troubles with the overlap function(to determine whether two projections overlap or not). Pieces of code:

```
class Polygon {
    public:
        std::vector<vec2> vertices;
        std::vector<vec2> edges;
        std::vector<vec2> axes;

        Polygon(){}

        Polygon(std::vector<vec2> list) :
            vertices(list)
        {
            init();
        }

        void init() {

            for (std::size_t i = 0; i < vertices.size(); i++) {

                vec2 edge = vertices[i] - vertices[i + 1 == vertices.size() ? 0 : i + 1];

                edges.push_back(edge);

                axes.push_back(edges.back().perp()); // its just (x,y) => (y,-x)
            }

        }

```

The projecting function:

```
    vec2 project(vec2& axis) {

        double min = axis.dot(vertices[0]);
        double max = min;

        for (std::size_t i = 1; i < vertices.size(); i++)
        {
            double p = axis.dot(vertices[i]);

            if (p < min)
                min = p;
            else if (p > max)
                max = p;
        }

        return vec2(min, max);
    }

```

And finally a function to determine if they collide or not:

```
bool collide(Polygon& poly1, Polygon& poly2)
{
    for (std::size_t i = 0; i < poly1.axes.size(); i++)
    {
        vec2 proj1 = poly1.project(poly1.axes[i]);
        vec2 proj2 = poly2.project(poly1.axes[i]);

        if (!proj1.overlap(proj2))
            return false;
    }

    for (std::size_t i = 0; i < poly2.axes.size(); i++)
    {
        vec2 proj1 = poly1.project(poly2.axes[i]);
        vec2 proj2 = poly2.project(poly2.axes[i]);

        if (!proj1.overlap(proj2))
            return false;
    }

    return true;
}

```

How would you implement the overlap function? I found someone elses solution using this overlap function :

```
bool overlap(const vec2& vector) {

    vec2 diffVector(x - vector.x, y - vector.y);

    if (diffVector.magnitude < magnitude)
        return true;
    else
        return false;
}

```

but its not working correctly. Is the error somewhere else or? Also im using for tets :

```
std::vector<cd::vec2> vertices{ {-2.0f,2.0f},{ -1.0f,0.0f },{ 2.0f,0.0f },{2.0f,2.0f },{ -1.0f,3.0f } };
cd::Polygon poly1(vertices);

std::vector<cd::vec2> vertices2{ { 0.0f,-2.0f },{ 0.0f,-3.0f },{ 2.0f,-3.0f },{ 2.0f,-2.0f },{ 1.0f,1.0f } };
cd::Polygon poly2(vertices2); And it ouputs me they don´t collide even when they should collide. Thanks!

```

**Edit1** (due to the first answer) Adding a small screenshot showing a situation where green and red polygons just touch eachother, however the algorithm says they do not collide.

# Answer
> 3 votes
Doing the overlap like that assumes the order of the overlaps.

If you instead try to find the smallest `min` and the biggest `max` and then compare those it should work;

```
bool overlap(const vec2& b) {
    double minA;
    double maxA;
    double minB;
    double maxB;
    if (x < b.x) {
        minA = x;
        maxA = y;
        minB = b.x;
        maxB = b.y;
    }
    else {
        minA = b.x;
        maxA = b.y;
        minB = x;
        maxB = y;
    }

    return !(maxA <= minB || minA >= maxB);
}

```

To find the depth of the penetration something like might do the trick;

```
float getOverlapDepth(const vec2& b) {
  float minA;
  float maxA;
  float minB;
  float maxB;
  if (x < b.x) {
    minA = x;
    maxA = y;
    minB = b.x;
    maxB = b.y;
  }
  else {
    minA = b.x;
    maxA = b.y;
    minB = x;
    maxB = y;
  }

  if (maxA <= minB || minA >= maxB) {
    return 0.0f;
  }
  else {
    if (minB > minA && maxB < maxA) {
      return 100.0f; // Or some other high value to indicate complete overlap
    }
    else {
      return maxA - minB;
    }
  }
}

```

---
Tags: collision-detection, mathematics, vector, separating-axis-theorem
---


# Question
Title: How can we generate terrain using simplex noise 2d with block position vectors
My problem might be special comparing to other questions related to terrain generation using simplex noise 2d. Each chunk contains a table of 1-dimensional array which encompasses the position data( world positions ) and index( whether solid or air ) for every block within it. I separate the underground part( 3d noise portion ) and surface( 2d noise portion ) by doing this in the loop:

```
for(int x = 0; x <= width; x++){
  for(int y = 0; y <= height; y++){
   for(int z = 0; z <= depth; z++){
  /* Use 3d noise to Generate underground caverns and overhangs when z is smaller than 15 */
      if(z <= 15){
        if(USimplexNoise::SimplexNoise3D(x, y, z) > threshold){
          BlockIndex[].add(1);//solid
        }else{
          BlockIndex[].add(0);//air
        }
     }else{
  /* Switch to 2d noise and generate the surface when z is bigger than 15*/
  /* This is where I get confused */
        if(USimplexNoise::SimplexNoise2D(x, y) > threshold)
    }
   }
  }
}

```

In the surface generation part, I'm trying to assign a value for BlockIndex(Solid or air), but I have no idea about the way to do that when I have to determine whether a block should be solid or not using simplex 2d.

On what circumstance should the block be solid or air?

Pseudo-code would help a lot.

# Answer
I solved my problem by treating what simplexnoise2d(x, y) returns as the threshold( height value )
> 0 votes

---
Tags: terrain, voxels
---