# Question
Title: OpenGL Orthographic projection questions
I'm studying now about projections with OpenGL and I've some questions:

**Is there importance for the viewer's location?** I know if I move forward/backward it won't mind, but what if I move upward with 30 degrees for e.g.

**Does the viewer is located in the 0,0,0 axis**? or he can be in another place after defining glOrtho's properties.

**Are there only 6 projections?** (I'm asking this because of the properties of the box, and defining the glOrtho - near, far, left, right, up, bottom)

**Can I hide objects with ortho proj?** I think it's obvious that yes, but I'm still curious maybe I'm wrong.

**Do objects that are closer to me seem bigger, meaning that other objects may be hidden?** I believe that not. the objects don't seem bigger. they stay the same size.

# Answer
> 2 votes
> Is there importance for the viewer's location?

Yes the viewer's location is very important. Even on the z-axis it is, because if an object goes outside of the projection's viewing frustum, it cannot be rendered, as said in this answer. Movement on other axes behaves like they would in a perspective projection.

> Does the viewer is located in the 0,0,0 axis?

As far as I know, the viewer is always initially located at the origin. However, you can always translate the view matrix away from that point.

> Are there only 6 projections?

The arguments of `glOrtho` (`near`, `far`, `left`, `right`, `up`, and `bottom`) just define the positions of the faces of the viewing frustum, on their respective axes. This "viewing frustum" is a rectangular solid, like the image below (please ignore the colors of the axes):

> Can I hide objects with ortho proj?

Yes, if an object is outside of the viewing frustum, or if another object covers it, it will not be rendered (if that's what you mean by "hide").

> Do objects that are closer to me seem bigger, meaning that other objects may be hidden?

The answer to the first part of your question is no, since the definition of an orthographic projection is that objects always stay the same size, no matter their distance from the viewer. However, to the second part of your question, the depth buffer still works as it would with a perspective projection. An object hides another object (well, technically a *fragment*) that lies behind it (as long as you clear the depth buffer bit).

---
Tags: opengl, projection
---


title: Skyrim/Papyrus: Random Actor Patrol

text:
# Question
Title: Skyrim/Papyrus: Random Actor Patrol
I saw this question and was hopeful to find the answer to my question, but no such luck: How do I make someone walk in Skyrim?

I want to, using papyrus ONLY, make Actors that I spawn to travel/patrol to a PatrolIdleMarker, preferably one that I create in the Papyrus script and set the coordinates for.

Example: I want a bandit to appear at a random location but specific distance from the Player. Then I want the bandit to start moving towards the player, attacking the player. The script below works just fine for this:

`ScriptName SomeQuestName extends Quest`

`ActorBase property LvlBanditMelee1H auto

Int[] BanditStatus
Actor[] Bandits

Event OnInit()
 Int MaxBandits = 11
 Bandits = new Actor[11]
 BanditStatus = new Int[11]
 int i=0
 while(i

Event OnUpdate()
 Float SpawnDistance = 15000.0
 Float ClearDeadDistance = 10000.0
 Float ClearAllDistance = 20000.0
 Int SpawnCounter = 0
 Int MaxBandits = 10
 if (PlayerRef.Z < 20000 && PlayerRef.GetWorldSpace() == Tamriel && (MQ101DragonAttack.IsCompleted() || MQ101DragonAttack.GetStage() > 195))
 int i = 0
 int j = 0
 while(i
 if(VerboseDebug==1)
 Debug.Notification("Bandit #" + i + " has wrong BanditStatus.")
 EndIf
 Else
 Distance = PlayerRef.GetDistance(Bandits[i])
 if((Bandits[i].IsDead() && Distance > ClearDeadDistance ) || Distance > ClearAllDistance )
 If(BanditStatus[i]==2)
 Bandits[i].Delete()
 Bandits[i] = None
 BanditStatus[i]=0
 EndIf
 if(BanditStatus[i]==1)
 Bandits[i].Disable(true)
 BanditStatus[i]=2
 EndIf
 EndIf
 EndIf
 EndIf
 i+=1
 EndWhile

```
    RegisterForSingleUpdate(30.0)

````

`EndEvent`

But lets say I wanted the Bandit to just patrol passed the player, replacing the bandit with say an Imperial guard?

ActorBase property LvlGuardImperial auto

Removing one row to stop spawned actor to start attacking the player from a distance: Bandits\[i\].StartCombat(PlayerRef)

And instead adding Bandits\[i\].EnableAI() won't work - the imperial guard will stand in one spot, only moving if combat starts close by or if the player comes into proximity and the guard is hostile to the player. If they are friendly the guard will simply stand/talk but not patrol or walk...

I need the codelines for adding creating a PatrolIdleMarker, LinkedReference or something else that I can set X,Y,Z to related to the Player, so that the spawned Actors will patrol passed the point where the player was when they spawned.

I have even tried to make them patrol to PatrolIdleMarkers already defined in vanilla Skyrim (Stable outside Solitude, Barracks in Falkreath etc), but the Actors will just not start patrolling/walking...

It also seems no forums are active anymore when it comes to Skyrim... I am so glad there will be a new release of Skyrim this fall (Skyrim Remastered) and hopefully some old modders will attend the forums again...

# Answer
> 0 votes
If you wanna move it around after, declare  `Objectreference PatrolMarker`  as a script global property like your arrays, then in any event (usually the first one, as redux's replace the current ref, but whenevr works best for ya) all you need to do is put `PatrolMarker = Game.GetPlayer().PlaceAtme(PatrolIdleMarker, 1)` If you declare it the way I wrote it the first time, it'll be a single-event-only property. The PatrolMarker from your OnInit() won't be usable when your OnLoad() event fires, and if you use `PatrolMarker = Game.GetPlayer().PlaceAtme(PatrolIdleMarker, 1)` again it'll make a new Marker. Since these are patrol markers, I recommend using this second approach if you read this, since you can then add  `StartTimer(300, 34543)` to your OnInit() and  `Event Ontimer(int aiTimerId)
PatrolMarker.DIsableNoWait()
PatrolMarker.Delete()
EndEvent` to disable them. You can use whiles in your timer NP if you've got more than one ref, and obviously know how to setup and deal with arrays, I'll leave ya to it. The placeatme usage is in both games exactly the same I know for sure, but some of the rest might need to be adapted to your version of Papyrus. Idk about the timer in particular, pretty sure they were added in Fallout 4, since we dont have OnUpdate() or RegisterForUpdate() or anything, all timers. But there HAS to be a timer system in your Papyrus of some kind or it couldn't work, which I'm sure you know all about, so have fun, hope I helped.

# Answer
> 0 votes
In Fallout 4 I'd use  `objectreference PatrolMarker = Game.GetPlayer().PlaceAtme(PatrolIdleMarker, 1)`  just make sure to get the properties right. idk how that'd "mesh" with what you're doing, what I can see of your your script dont actually do anything besides delete or disable some bandits, but it's gotta be something not showing up properly, there's no way  `while(i
if(VerboseDebug==1)` can actually do anything in either game, since "i" has no comparable values and you never end any of your whiles.

# Answer
> 0 votes
I will answer the question myself now that I know the answer: You use the PathToReference function or the above suggested Patrol functionality. Difference is that PathToReference only works once and puts a strain on the CPU everytime it is called, but will make the AI move toward the reference.

https://www.creationkit.com/index.php?title=PathToReference\_-\_Actor

Example:

; Make actor path to the player at half speed Bob.PathToReference(Game.GetPlayer(), 0.5)

This does not make the actor attack the player like StartCombat, but will make the Actor move toward the target (player in above example).

I also suggest using PlayerRef instead of Game.GetPlayer():

Actor property PlayerRef Auto

Bob.PathToReference(PlayerRef,0.5)

Hope this helps other struggling with this.

---
Tags: scripting, skyrim-modding
---


# Question
Title: Do I lose any functionality using Visual Studio for Unity 3d?
MonoDevelop has always had a strange tendency to stop functioning in basic ways ... autocompletion, copy/paste-clipboard, error detecting, and other silly things.

I routinely fix this by running clean / rebuild all, then restarting MonoDevelop. But this is time-consuming. I've read that Monodevelop has issues...

If I switch to Visual Studio will I lose anything at all that I rely on with Monodevelop's integration to unity? Or will I in fact gain?

# Answer
Visual Studio is becoming the most fitted IDE in order to develop with Unity. You won't loose anything in comparison to MonoDevelop.

You will still have autocompletion, debugging tools, documentation access, MonoBehavior scripting wizard, ... I have been using Visual Studio along with Unity for years now. I can't stand Monodevelop anymore.

Check these links :
> 3 votes

---
Tags: unity, visual-studio, monodevelop
---


title: 3D scanners that captures movement?

text:
# Question
Title: 3D scanners that captures movement?
Could there be a 3D scanner that captures movement? One that scans, let us say, 30 times per second (for 30 fps) to make an animated 3D scene? Is this possible? Why?

Suppose we want to scan a person dancing (I know a similar result could be achieved by applying a 3D scan of the person to a motion-captured data, but it is an example). Instead of a simple 3D scan of the person, it would make 30 scans every second. Then a computer would get all these point clouds data (of each "frame") and merge them into an animation by comparing different scans. It is different from motion capture because these 3D scans would create many point clouds every second, rather than just capturing the motion by itself. Just like normal cameras film several frames per second to make a video, 3D movement scanners would make several scans to make a 3D animated scene.

Does this already exist? And do you think the limit of nowadays computers processing powers are a problem to scan a scene with such high frequency (30 scans per second)?

# Answer
I don't know of anyone having done this but it may be possible. There are a number of 3D scanning systems available that use consumer sensors like Kinect; as you can see in this video of one such system you move the Kinect around the object and record it from multiple angles, so you could get multiple angles simultaneously by having multiple Kinects.

> do you think the limit of nowadays computers processing powers are a problem to scan a scene with such high frequency

Unless you're trying to generate the animated scan *in real-time* then no processing isn't a limiting factor. While generating a 3D mesh from the scan images is a processing-intensive task, capturing the images is done at the framerate of your camera, and then you process the images later. The main limitations are physical ones, like getting a bunch of Kinects and building the rig to hold them.
> 1 votes

---
Tags: 3d-meshes, 3d-modeling, motion-capture
---


# Question
Title: Unity: How to resize a game object for a certain amount of time?
I've tried to make a coroutine like this

```
private IEnumerator applyPowerUp(string type, GameObject player)
{
    GameObject originPlayer = new GameObject();
    originPlayer = player;

    if (type == "Bigger")
    {
        Debug.Log("make it big");
        player.transform.localScale = new Vector3(1.25f, 2.9f, 0);
        player.transform.position = new Vector2(player.transform.position.x + 0.4f, player.transform.position.y);
        yield return new WaitForSeconds(5);
        player = originPlayer;
    }
}

```

The game object are getting bigger but after 5 secs it didn't turn back to its origin size.

# Answer
```
GameObject originPlayer = new GameObject();
originPlayer = player;

```

this doesn't do what you think it does.

instead you want to save the just the original scale and restore that:

```
if (type == "Bigger")
{
    Vector3 origScale = player.transform.localScale;

    Debug.Log("make it big");
    player.transform.localScale = new Vector3(1.25f, 2.9f, 0);
    player.transform.position = new Vector2(player.transform.position.x + 0.4f, player.transform.position.y);

    yield return new WaitForSeconds(5);

    player.transform.localScale = origScale;
    player.transform.position = new Vector2(player.transform.position.x - 0.4f, player.transform.position.y);
}

```
> 2 votes

---
Tags: unity, scale, coroutines
---


title: Unity Combining Passes in Shader

text:
# Question
Title: Unity Combining Passes in Shader
I have a shader which uses multiple passes to determine the thickness of an object at each point. I want to use this thickness value in order to sample from a texture, which will determine the color of the screen at that point. However, since the calculation is performed in two passes, I don't have any way to access the one value which results at the end, which is what I would be using to index the uv for the texture. Thanks for any help in advance!

```
{
Properties
{
    _MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
    Pass
    {
        Cull Back ZWrite On ZTest Always
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
            float3 normal : NORMAL;
        };

        struct v2f
        {
            float2 depth : DEPTH;
            float4 vertex : SV_POSITION;
        };

        v2f vert (appdata v)
        {
            v2f o;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.depth = -UnityObjectToViewPos(v.vertex).z * 200 * _ProjectionParams.w;
            return o;
        }

        sampler2D _MainTex;

        fixed4 frag (v2f i) : SV_Target
        {
            float c=1-i.depth;
            fixed4 col = fixed4(c,c,c,1);
            return col;
        }
        ENDCG
    }
    Pass
    {
        Cull Front ZWrite On ZTest Always
        BlendOp RevSub
        Blend One One
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
        };

        struct v2f
        {
            float2 depth : DEPTH;
            float4 vertex : SV_POSITION;
        };

        v2f vert (appdata v)
        {
            v2f o;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.depth = -UnityObjectToViewPos(v.vertex).z * 200* _ProjectionParams.w;
            return o;
        }

        sampler2D _MainTex;

        fixed4 frag (v2f i) : SV_Target
        {
            float c = 1-i.depth;
            //fixed4 col = tex2D(_MainTex,c.xx);
            fixed4 col = fixed4(c,c,c,1);
            return col;
        }
        ENDCG
    }
}
}

```

# Answer
Use a grab pass

```
{
Properties
{
    _MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
    Pass
    {
        Cull Back ZWrite On ZTest Always
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
            float3 normal : NORMAL;
        };

        struct v2f
        {
            float2 depth : DEPTH;
            float4 vertex : SV_POSITION;
        };

        v2f vert (appdata v)
        {
            v2f o;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.depth = -UnityObjectToViewPos(v.vertex).z * 200 * _ProjectionParams.w;
            return o;
        }

        sampler2D _MainTex;

        fixed4 frag (v2f i) : SV_Target
        {
            float c=1-i.depth;
            fixed4 col = fixed4(c,c,c,1);
            return col;
        }
        ENDCG
    }

    GrabPass { "_GrabTexture" }

    Pass
    {
        Cull Front ZWrite On ZTest Always
        BlendOp RevSub
        Blend One One
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
        };

        struct v2f
        {
            float2 depth : DEPTH;
            float4 vertex : SV_POSITION;
            float4 grabUv : TEXCOORD0;
        };

        v2f vert (appdata v)
        {
            v2f o;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.depth = -UnityObjectToViewPos(v.vertex).z * 200* _ProjectionParams.w;
            o.grabUv = ComputeGrabScreenPos (o.vertex);
            return o;
        }

        sampler2D _MainTex;
        sampler2D _GrabTexture;

        fixed4 frag (v2f i) : SV_Target
        {
            fixed4 lastPassColor = tex2Dproj(_GrabTexture, i.grabUv);
            float c = 1-i.depth;
            fixed4 col = tex2D(_MainTex,c.xx);
            //fixed4 col = fixed4(c,c,c,1);
            return col;
        }
        ENDCG
    }
}
}

```
> 7 votes

---
Tags: unity, shaders
---


# Question
Title: Score balancing and progression limitation based on stars
# Introduction

I'm creating a game where the player can obtain 1 to 3 stars for each level based on the score it gets (based on the completion time). The levels are grouped in "worlds" each of which is unlocked when the user obtains a given number of stars in the previous levels.

For example, world 1 has 5 levels and to unlock world 2 the user needs to gain at least 5 stars (thus at leas one star per level in average).

Here is a basic idea of the `words -> n° of levels in that world -> stars to unlock`

```
1 -> 5 -> 0 (of course)
2 -> 5 -> 5 / 15 (33%)
3 -> 5 -> 10 / 30 (33%)
4 -> 7 -> 25 / 45 (55%)
5 -> 7 -> 30 / 66 (45%)
...

```

To determine the score you should reach, for each level, to get 0 / 1 / 2 / 3 stars, I recorded some play stats from a bunch of beta-testers obtaining a normal distribution of play times for each level. Given each distribution, I should be able to answer this question for each level:

> at what score should I reward `n` stars in order for `x%` of the player to get `n` stars overall?

---

# Justification

The "high score progress" mechanic is meant to be one of three different possible ways of progression, the other two being: exploration and "character building". New worlds can be unlocked by paying a given amount of coins which are found hidden in levels. A player either rushes to the end of the level obtaining high scores or takes its time and scouts out every coin in each level, obtaining enough coins to pay the next world. As for the "character building", a player may choose to fight every enemy in the levels (which are more likely placed on the main path) and being very good at timing battle controls, gain experience and level up its character. With level up you can speed up your character (getting higher scores) or improve coins (getting more coins without too much exploration), this way the "character building" mechanic places between the other two. Reducing the percentage of users that reach final worlds by score is a way to forcefully funnel players to their "most suited" mechanic.

---

# Tuning

So now I can change the thresholds for each star at each level (or group of levels) in order to filter the percentage of players that will obtain a given number of stars at some point. This way I can set the game difficulty as the difficulty to unlock a given world which is the percentage of people who are good enough to gain enough stars to unlock that world.

For example for early world progress difficulty, I chose a base of `1.22` as exponential base of the percentage reduction (difficulty growth), like this:

```
world -> difficulty coeff. -> perc. players

1 -> 0 -> 100%
2 -> 1.22 -> 98.78%
3 -> 1.4884 -> 98.5116%
4 -> 1.815848 -> 98.184152%
5 -> 2.21533456 -> 97.78466544%
...

```

This way, for example, the last world should be reached by about 47% of the players.

Now I want to know how to tune percentages of people gaining 1 / 2 / 3 stars in order to stick to this given percentage progression. In order to do this, I found the minimal configurations of possible stars obtained in each world level in order to unlock the next one, for example:

```
world -> n° 1 stars -> n° 2 stars -> n° 3 stars -> stars to unlock next world
1 -> 5 -> 0 -> 0 -> 5
2 -> 10 -> 0 -> 0 -> 10
3 -> 5 -> 10 -> 0 -> 25
4 -> 12 -> 10 -> 0 -> 30
5 -> 18 -> 11 -> 0 -> 40
...

```

Note that if the user got `10 x 2 stars` in the previous world, then it still has those `10 x 2 stars` in later worlds, unless it tops them wit `3 stars`.

---

# My Calculations

Now, for example, if I want `98.78%` of the players to be able to unlock the second world, given they have to obtain minimum `1 star` at each previous level, then `p^5 = 0.9878` and `p = rad(5, 0.9878) ≈ 0.9975`, so `99.75%` of the players should be able to get at leas 1 star in each level of the first world.

For the third world, things get a little harder, as the 1 star probabilities for the first 5 levels are locked now. Players must be able to obtain at least 1 star in each of the 10 levels of the first two worlds with an overall probability of `98.5116%`, but the probability to obtain 1 star in the first 5 levels is locked at `99.75%`, with an overall probability of obtaining 1 star in each of the first 5 levels of `98.78%`. So I had to solve this equation: `p * 0.9878 = 0.985116` so `p = 0.985116 / 0.9878 = 0.9973` which is the probability `p` to get at leas 1 star in all the 5 levels of the second world. So the probability to obtain 1 star for each single level of the second world is `p = rad(5, 0.9973) = 0.9995` which is slightly higher than the previous world.

Fourth world gets even weirder, as the restrictions shifts on the `10 x 2 stars` that players need to obtain in the 15 previous levels. To do this, I used binomial distribution to find the probability to extract at least `10` successes over `15` attempts which gave a probability of `58.79%` to obtain 2 stars in each of the 15 levels of the first 3 worlds in order to have a `98.184%` probability to finish the third world with at leas `10 x 2 stars`.

Fifth world differs from fourth only by `7 x 1 star` so I just calculated `p * 0.98184 = 0.97784` where `p` is the probability to obtain 1 star in each of the 7 levels of the fifth world, obtaining a probability to obtain 1 star for each single level of the fifth world of `99.50%`.

---

# Problems

Now **I'm stuck** at world 6 where the user is required to obtain at least `11 x 2 stars`. How do I calculate this probability? I can use the binomial distribution, but the probabilities of the events are not the same everywhere as the probability to obtain 2 stars in the first 5 words is locked.

Is there any formula to help me with this? Is there any simpler / more direct approach I can fallow? Does any of this make any sense at all?

# Answer
> 0 votes
After some reading and tinkering I decided to fallow a more straight forward approach and use simulation to obtain some empirical data.

To do so, I wrote a code snippet "simulating" one billion games like this:

1. A new game starts
2. Player has 0 feathers
3. Player starts at world 1 with 5 levels
4. Every level in each world has the same 3 probabilities for players to get 1 - 2 - 3 stars (in percentage).
5. For each level in the current world the player extracts a random number between 0 and 100
6. I compare the extracted number with the 3 probabilities to see how many stars the player got in that level
7. Gained stars are added to the player's stack
8. When player reaches the end of the world it can progress only if it has enough stars
9. Each world has a counter of how many players were able to unlock it.

This might seem too simplistic, but it actually works. As we know, with a (good) random number generator any number has the same probability to be extracted, whilst actual real life level completion times tend to assume a Gaussian distribution with a peak around the average. But here's the quirk: what I am considering is not the completion time itself, but the percentage of players completing the level within that time **at most**. So finding out z-scores for my required percentages allows me to identify the time thresholds for each single level, no matter how the actual play times are distributed. This way I can use a random number extraction simulation to simulate something more complex and find the correct thresholds for each level in order to ensure the desired percentage of player would be able to progress.

---
Tags: mathematics, game-design, balance, difficulty, progression
---


# Question
Title: OpenGL - Updating VAO array buffer range
I am trying to stream data to a buffer which I have bound to a VAO vertex buffer binding point that I want to access through vertex attributes in the shader.

Usually I stream to buffers which I have bound as `GL_UNIFORM_BUFFER`s and I do it like this:

```
//create an immutable data storage
glNamedBufferStorage(uboID, capacity, data, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT);

//map entire storage forever
mappedPtr = glMapNamedBufferRange(uboID, 0, capacity,  GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT);

//bind buffer to target(GL_UNIFORM_BUFFER) binding point
glBindBufferBase(GL_UNIFORM_BUFFER, uboBinding, uboID);

//bind shader interface block to target binding point
glUniformBlockBinding(shaderProgramID, blockIndex, uboBinding);

```

Now the uniform block can be accessed in the shader program and i can stream to it like so:

```
//copy data to mapped pointer at stream offset
memcpy(mappedPtr + uploadOffset, &uploadData[0], uploadSize);

//This is the important part: tell the shader which range of the buffer to use
glBindBufferRange(GL_UNIFORM_BUFFER, uboBinding, uboID, uploadOffset, uploadSize);

//increment offset
uploadOffset += uploadSize;

```

If I bind a buffer to a VAO and access its data as vertex attributes in the shader, I don´t know how to give the shader the range in which the updated data can be found. I can give an offset when binding a buffer to a VAO when calling `glVertexArrayVertexBuffer`, but it has a few more parameters and does not seem like the right thing to call every frame. I have not gotten it to work with it, too.

Is there something like `glBindBufferRange` for vertex buffers bound to VAOs?

# Answer
you can use separate attrib format so you can update the offset and stride of the vbo serpately from the format:

```
//during initialization
glBindVertexArray(vao);

// set the details of a single attribute
glVertexArrayAttribFormat(vao, posAttrLoc, 3, GL_FLOAT, false, offsetof(Vertex, pos));
// which buffer binding point it is attached to
glVertexArrayAttribBinding(vao, posAttrLoc, vertexBindingPoint);
glEnableVertexArrayAttrib(vao, posAttrLoc);

```

then to set the vbo:

```
glVertexArrayVertexBuffer(vao, vertexBindingPoint, mesh.vbo, mesh.vboOffset, sizeof(Vertex));

```
> 3 votes

---
Tags: opengl, vao, streaming
---


# Question
Title: how to make a humanoid character bone rotate to face an object in unity?
I want to character to be able to move in a direction and be able to aim to object in other direction. I use code below to control bone of a character:

```
anim.SetBoneLocalRotation(HumanBodyBones.Spine, Quaternion.Euler(...));

```

but I don't know what is the right way to rotate chest and spine of a character to make upper body aim to a position.

# Answer
> 2 votes
Maybe try this:

```
var dir = target.position - boneTransform.position;
var q = Quaternion.LookRotation ( dir );
anim.SetBoneLocalRotation(HumanBodyBones.Spine, q);

```

# Answer
> 1 votes
I don't know if this is the "right" way to do this, but whenever I had to manually rotate a bone, I would make a Transform boneToBeRotated member in the controlling class, and slot in whatever bone from the Scene hierarchy. Then you can manipulate it like any other transform, choosing rotation or localRotation as you see fit.

Oh, and with that method the rotation has to be done in LateUpdate, in order to override the normal animation rotation.

---
Tags: unity, animation, skeletal-animation
---


# Question
Title: Round position to center of current grid position
The title may not make sense, nor may the question - I'll try nevertheless. I'm attempting to make a game similar to The Powder Toy.
Essentially, this is a physics simulation game, where the users create various structures using the provided materials.
As of now, I've created the grid, and given the user the ability to draw with grey cells (or, Stone).
Of course, this may seem like what I would want - however, all the cells are stored in a two dimensional array. When the user clicks on the screen, the program round the x and y of the cursor to the grid, and adds to the array like that.
What I want to happen is for the cell to change in the place of the cursor, instead of rounding it to the nearest cell.
I've attempted to explain it in this image:
In this image, the green large dots are the mouse position, and the place at which the arrows are pointing are examples of where the cell could be.
Green represents what I want to happen but in most cases doesn't, and red is what does happen, but what I don't want.

Here's part of my function to set the cells:

```
public void handleInput () {
    if (Gdx.input.isButtonPressed(Buttons.LEFT)) {
        mouse_x = Gdx.input.getX();
        mouse_y = Gdx.input.getY();

        rou_mouse = new Vector2(round2px(mouse_x), round2px(mouse_y));

        set_px (rou_mouse, new Element_stone());
}

```

Where `set_px` sets a certain item, this is used to draw to the screen.
I hope this is enough information, but if you would need anymore to solve it, I'd be happy to update the post to include more code.

Oh, and I should probable mention I'm using LibGDX.

# Answer
What you really want to do is "floor" instead of round. Flooring rounds down, which will select the corner of the cell that the is mouse pointer is *in*, instead of plain rounding, which rounds to the corner that is closest to the mouse pointer.

```
int mouseX = Gdx.input.getX();
int mouseY = Gdx.input.getY();

/*
 * cellWidth and cellHeight must be int's; division between two ints chops off the
 * remainder and returns the whole number (effectually flooring the quotient)
 */
int gridX = mouseX / cellWidth;
int gridY = mouseY / cellHeight;

```

I would modify your `set_px` method to take in arguments of type `int`, instead of a `Vector2` (which uses `floats` and can get confusing).

```
set_px(gridX, gridY, new Element_stone());

```

I would also take a look at Java Naming Conventions!
> 1 votes

# Answer
Ok this is how i would do it.

```
 public void handleInput () {
                mouse_x = Gdx.input.getX();
                mouse_y = Gdx.input.getY();

                rou_mouse = new Vector2(mouse_x/cellWidth, mouse_y/cellHeight);

                set_px (rou_mouse, new Element_stone());

        }

```

The new vector2 arguments should give what cell number your clicking on in relation to your array.

```
grid[rou_mouse.x][rou_mouse.y]

```

Just like that
> 0 votes

# Answer
So if I understood, you want to get the cell that is clicked so you can color it.

```
private void fillTouchedCell() {
  if (Gdx.input.isTouched()) {
    Cell c = getCellAtTouch();
    if (c != null) {
      //cell clicked, we cant fill it with color
      c.fill(Color.RED);
    }
  }
}

private Cell getCellAtTouch() {

  unpojectedTouch.set(Gdx.input.getX(), Gdx.input.getY(), 0); //insert input into a Vector3
  cam.unproject(unpojectedTouch); //convert to your camera viewport size

  touch.set(unpojectedTouch.x, unpojectedTouch.y);

  for (int x = 0; x < GRID_COLUMNS; x++) {
    for (int y = 0; y < GRID_ROWS; y++) {

      Cell cell = cells[x][y]; // get cell from your 2-side array

      if (touch.x > cell.getX() && touch.x < cell.getX() + cell.getWidth()) {
        if (touch.y > cell.getY() && touch.y < cell.getY() + cell.getHeight()) {
          return cell;
        }
      }
    }
  }

  return null;
}

```
> 0 votes

---
Tags: java, libgdx, grid
---


title: Manage vertical levels rendering

text:
# Question
Title: Manage vertical levels rendering
I've been working on a semi-professionnal project for more than one year. The game is in 3D with a TopView camera. In this game, the player will be in very vertical spaces, with lots of ladder and stairs.

The actual problem is that I need to show only what is at the actual height of the player.

I have made a shader that 'cut' the objects above a given height.

The problem is that my mesh are open above this height, and we just see nothing inside.

If you have any idea on how to make something to fill an open mesh or any other system that will do the job, i'll be very pleased to read you :)

This is what I have

This is what I aim to (black above top of walls)

# Answer
> 1 votes
# Similar problem: rendering sliced volumes with solid inside

I recall a similar situation to your problem, but can't find it anymore. The user wanted to render sliced volumes, but when he just cut the polygons as you did he got the empty space problem as well.

A solution would be to disable backface culling and draw backfaces in a solid color, independant of lighting.

# Backface culling

Backface culling is a technique to speed up rendering. Every polygon can be considered to have two sides, a front side and a back side. Whether the *backface* or the *frontface* is facing the camera, is decided by the winding order of the vertices (https://www.khronos.org/opengl/wiki/Face\_Culling). You can then use *backface culling* to only draw polygons facing the camera. This effectively cuts the number of polygons to render in two.

This is the reason you are seeing an "open mesh" as you describe it. The polygons of the wall are facing to the outside. Polygons on the inside are culled. Normally this is not a problem, as you can't see inside of closed volumes, unless you place the camera inside of the object. However when you have open volumes (e.g. through a slicing shader), the insides can become visible, and the "trick" of leaving out the backfaces becomes a problem.

# Solution to your problem

So in summary, you could draw the backfaces of of all volumes that can be sliced by your shader. I would render them in a solid black color, unaffected by lighting, to achieve the effect in your reference screenshot.

One small caveat: if your floor plane intersects the walls at the bottom, it may end up showing through. You could solve this by "closing" the wall meshes at the bottom, by using a bottom quad that lies slightly above the floor. It won't be visible for unsliced walls, and for slices walls it'll give you a nice black bottom, without the floor shining through.

**EDIT:** been Googling around for a while, and the terms used to describe this problem are "capping sliced/cut meshes/geometry/volumes". It should also be possible with the stencil buffer, but I don't have much experience with it myself. Found these pages, but they are quite dated:

https://www.opengl.org/archives/resources/code/samples/advanced/advanced97/notes/node10.html

https://www.opengl.org/discussion\_boards/showthread.php/144180-Using-the-stencil-buffer-to-cap-solids

# Answer
> 0 votes
Close your walls mesh and just paint it plain black on the texture

---
Tags: unity, shaders
---


# Question
Title: Perlin noise terrain generation with integer (discrete) elevation levels results in artifacts at rounding boundaries
I am trying to generate terrain with discrete height levels using Unity's built in 2D Perlin noise function. The output is a float in \[0,1\]. I then scale the float linearly to a range \[minimum Height, Maximum Height\], and round it to the nearest integer.

The problem is that this results in artifacts at rounding boundaries, as can be seen in the following image:

As you can see, the ridge line partially marked in red should not be there. It is created because that's the rounding boundary, meaning that this is the line between x.49 and x.50 (x is integer), so the x.49 is rounded to x, while the x.50 is rounded to x+1.

I'll demonstrate that by zooming to a part of the image and showing the height value of different blocks:

The height of Block 1 is 14.48

The height of Block 2 is 14.52

The height of Block 3 is 15.6

The height of Block 4 is 14.6

As you can see, the only reason there is a ridge between Block 1 and Block 2, is because 1's height is rounded to 14, while 2's height is rounded to 15. This is unlike Blocks 3 and 4, which should have an elevation difference between them as per the Perlin noise function.

I can of course use Floor or Ceil or other methods to turn the float result from the Perlin Noise function into an integer, but that simply results in artifact lines appearing at other places.

Any help in solving this issue would be greatly appreciated.

Thank you.

Edit:

Here is how I get the height of each column:

```
float grassHeightFloat = WorldGenMath.getNoise(x + grassHeightRandOffSet, z + grassHeightRandOffSet,
            grassSmoothness, grassMinHeight, grassMaxHeight)

uint grassHeight = Convert.ToUInt32(grassHeightFloat);

```

WorldGenMath is:

```
private static float scaleNoise(float value, float minScale, float maxScale)
    {
        return scale(value, 0, 1, minScale, maxScale);
    }
private static float scale(float value, float min, float max, float minScale, float maxScale)
    {
        float scaled = minScale + (float)(value - min) / (max - min) * (maxScale - minScale);
        return scaled;
    }
public static float getNoise(uint x, uint z, float smoothFactor, int minScale, int maxScale)
    {
        float noise = Mathf.PerlinNoise(x * smoothFactor, z * smoothFactor);
        return scaleNoise(noise, minScale, maxScale);
    }
public static float getNoise(long x, long z, float smoothFactor, int minScale, int maxScale) {
        return getNoise(Convert.ToUInt32(x), Convert.ToUInt32(z), smoothFactor, minScale, maxScale);
    }

```

# Answer
The effect looks like its an issue of adding 2 perlin noise maps over one-another and 1 of them is not properly scaled resulting in an edge instead of a nice hill. 1 of the maps returns between 0 and 1, and not minHeight / maxHeight.
> 0 votes

---
Tags: unity, procedural-generation, terrain, perlin-noise
---


# Question
Title: Can't get reliable collision detection/response in Monogame
So, I currently have a Rectangle that updates with player position, and is the size of the sprite. I'm using Tiled as my tile editor, and have an Object layer called "collision" which I loop over when loading the map, and store each object as a Rectangle in a list. Then in my Update I check if the player is colliding with any of those rectangles (via looping over the list) with Rectangle.Intersects(Rectangle). And if a collision is detected, I handle it with this function:

```
private static void HandleCollision()
{
    if (_currentLevel.IsCollisionTile())
    {
        float deltaLeft = Math.Abs((Player.Instance.Position.X + Player.Instance.PlayerCollider.Width) - (_currentLevel.collidingRectangle.X));
        float deltaRight = Math.Abs((Player.Instance.Position.X) + (_currentLevel.collidingRectangle.X + _currentLevel.collidingRectangle.Width));
        float deltaUp = Math.Abs((Player.Instance.Position.Y + Player.Instance.PlayerCollider.Height) - (_currentLevel.collidingRectangle.Y));
        float deltaDown = Math.Abs((Player.Instance.Position.Y) - (_currentLevel.collidingRectangle.Y + _currentLevel.collidingRectangle.Height));

        if (deltaLeft < deltaRight && deltaLeft < deltaUp && deltaLeft < deltaDown)
        {
            Player.Instance.Position.X -= deltaLeft;
        }
        else if (deltaRight < deltaLeft && deltaRight < deltaUp && deltaRight < deltaDown)
        {
            Player.Instance.Position.X += deltaRight;
        }
        else if (deltaUp < deltaLeft && deltaUp < deltaRight && deltaUp < deltaDown)
        {
            Player.Instance.Position.Y -= deltaUp;
        }
        else if (deltaDown < deltaLeft && deltaDown < deltaRight && deltaDown < deltaUp)
        {
            Player.Instance.Position.Y += deltaDown;
        }
    }
}

```

I know this is ugly, but that's not the problem, the problem is that when it detects a collision, the player "spazzes out" and just bounces in and out of the rectangle it's colliding with. I've tried a couple other ways too, like just setting the player position without using absolute values, with similar calculations. The same problem happens though. Also it allows the player to just phase through platforms from one side, and the player will get teleported to other sides sometimes, so this is very bad.

I'm not sure how else to handle it, I've done research and googled a lot, as well as searched here, but everything I find is about the actual collision detection, which I'm doing via the Rectangle.Intersects() method. I've been at this for 3-4 days, before deciding to post here.

# Answer
Of-course it bounces. You are doing this:

* Detect rectangle intersection using Monogame API calls (this only tells you that an intersection occurred)
* Make the player going back/forward by the tile rectangle

The problem with this method is that the player will be pushed by the same width/height no matter where the collision did happen. With the most common implementation of player's x/y changing by a certain amount of pixels per frame/update, depending the speed of movement and where the starting position was, the collision may be detected when player is 5 pixels inside the tile, 3 pixels inside the tile, 14 pixels inside the tile, or not get detected at all, for example player is at x = 5, tile is at x = 22, tile and player box are 16x16, and you set speed at 40 pixels per frame, resulting in the player going through the tile with no collision being detected, because player was at 5 one frame, and at 45 the next frame.

\[Animated gif here\]

A **quick** fix

Calculate the penetration vector of the player rectangle into the tile rectangle. By moving the player back by the penetration vector, not the tile width, the player will be rejected and leaving touching the tile side.

This method has issues with tile based maps, that you will need to address somehow but you have a starting point now. Experiment to adapt to your needs.

This is what you want: https://vimeo.com/64923588

The formula for the penetration vector, as long as we are in Axis Aligned Bounding Box (AABB) land, is simple:

```
TX = Player.x - Tile.x;
TY = Player.y - Tile.y;

```

But you will push the player only in the direction of the axis with greater absolute value.

Read more on penetration vector for AABB here, which uses minkowski difference to solve collisions.

Possible solutions to "player stuck between tiles" or "player pushed out of an entire line of tiles":

Possible solutions to "player still miss the tile if moving too fast":

* Don't allow player to move more pixels, per frame, than the tile width (only possible if you have a constant tile width).
* Use a more complex AABB collision/penetration detection that account for moving AABB: Simple intersection tests for games
> 1 votes

---
Tags: c#, collision-detection, monogame, tiled
---


# Question
Title: Scale object based on another object's position
Despite an hour or so of Googling I can't seem to figure out how to calculate the scale factor based on distance. Here's the illustration of my problem.

I've tried manipulating the x values and such, but until now I still cannot figure it out. Here's the snippet:

```
Vector3 v3Scale = frontWall.transform.localScale;
frontWall.transform.localScale = new Vector3(v3Pos.x*2.0f , v3Scale.y , v3Scale.z);

```

Any ideas? Thanks in advance!

UPDATE:

```
if(getTarget.CompareTag("LeftRightWall") && getTarget.transform.childCount == 1)
        {
            float translate = getTarget.transform.position.x - getTarget.transform.GetChild(0).gameObject.transform.position.x;
            Debug.Log("value :"+translate);
            foreach (GameObject frontWall in GameObject.FindGameObjectsWithTag("FrontWall"))
            {
                Vector3 v3Scale = frontWall.transform.localScale;
                float scaleFactor = translate/frontWall.transform.localScale.x;
                frontWall.transform.localScale = new Vector3(translate , v3Scale.y , v3Scale.z);
            }
            v3Pos.z = getTarget.transform.position.z;
            v3Pos.y = getTarget.transform.position.y;
            getTarget.transform.position = v3Pos;
            getTarget.transform.GetChild(0).gameObject.transform.position = new Vector3(-v3Pos.x, v3Pos.y, v3Pos.z);
        }

```

The LeftRightWall is the ones that I drag on the picture, with another vertical line as its child. The FrontWall is the horizontal line that is stretched when the LeftRightWall is dragged. Hope its clear enough. Thanks

UPDATE: This is the closest one from what I'm trying to achieve... ((

Here's the code:

```
float translate = getTarget.transform.position.x - getTarget.transform.GetChild(0).gameObject.transform.position.x;
            Debug.Log("value :"+translate);
            foreach (GameObject frontWall in GameObject.FindGameObjectsWithTag("FrontWall"))
            {
                Vector3 v3Scale = frontWall.transform.localScale;
                frontWall.transform.localScale = new Vector3(translate+v3Pos.x, v3Scale.y , v3Scale.z);
            }

```

UPDATE: This is what I'm able to do so far, thanks to the answer below. However I still don't know why the other side of the panel is behaving like that. The scale of horizontal lines also shrinks when I click on the vertical line.

This is the updated code:

```
ray = mainCamera.ScreenPointToRay(Input.mousePosition);
        float dist;
        plane.Raycast(ray, out dist);
        Vector3 v3Pos = ray.GetPoint(dist);
        if(getTarget.CompareTag("LeftRightWall") && getTarget.transform.childCount == 1)
        {
            float translate = getTarget.transform.localPosition.x - getTarget.transform.GetChild(0).gameObject.transform.position.x;
            Debug.Log("value :"+getTarget.transform.GetChild(0).gameObject.transform.localPosition.x);
            foreach (GameObject frontWall in GameObject.FindGameObjectsWithTag("FrontWall"))
            {
                Vector3 v3Scale = frontWall.transform.localScale;
                float scaleFactor = (translate/v3Scale.x);
                frontWall.transform.localScale = new Vector3(v3Scale.x*scaleFactor, v3Scale.y, v3Scale.z);
            }
            v3Pos.z = getTarget.transform.localPosition.z;
            v3Pos.y = getTarget.transform.localPosition.y;
            getTarget.transform.localPosition = v3Pos;
            getTarget.transform.GetChild(0).gameObject.transform.position = new Vector3(-v3Pos.x, v3Pos.y, v3Pos.z);
        }

```

# Answer
Maybe this math could guide you if as I understand your problem is that the horizontal and vertical lines "split" and you want them to stick together.

Having the distance between the two upper points of vertical lines, you can get the distance between them. Let's say `d1`.

The horizontal length of your upper line is `length`.

Then, `d1 / length` will give you the scale factor you need to "achieve" d1.

Numeric example:

```
distance = 10
length = 8

scaleFactor = 10/8 = 1.25

```

Then, `8 * 1.25 = 10`.

I'm not completely sure this is what you expect, if it's not, please update your question with more details.

---

EDIT: In your updated code, I don't see your scaleFactor been used, your frontWall scale depends on translate, not on the factor. Besides that, this scaleFactor is calculated with scale.

What I tried to tell you to do is something more like the following:

```
Vec3 translate = positionX - other.positionX; //That's ok
float scaleFactor = translate.transform.x / frontWall.lengthX;
//Here, it's meant to use the length of the frontWall in its X-axis
Vec3 newScale = new Vec3(frontWall.lengthX * scaleFactor, localScale.y, localScale.z);

```

Excuse me for this code not being compilable, I've not been using Unity for a while now and I'm on my Smartphone.
> 1 votes

---
Tags: unity, c#, transformation, scale
---


# Question
Title: Issue in using Set Integer (by ref) in Unreal Engine 4.16 blueprint
I am trying to set the value of an integer by reference in a macro created in my blueprint script. The macro does a simple conditional check of an integer and increments it if it is less than a max value. I was using one of the maze generating tutorials and the function throws a failed to resolve term Value passed into Target error. I am not sure why it cannot deduce the type of Value. The original tutorial was made in UE 4.6, so could it be due to updates made in UE 4.16? I have attached a screenshot of my blueprint.

# Answer
In your case you can use `IncrementInt`:

It is working in 4.17 as well.
> 1 votes

---
Tags: unreal, blueprints
---


# Question
Title: Unity performance: change sprite from array or sprite sheet animation?
Quite some time ago I made a "GIF player" that basically reads a sprite array and swaps the sprite using a `Coroutine`, one after the other, in order to imitate a "GIF" animation.

I was working but I have no clue about performance as on my PC it was fine.

Thing is, the game is meant for mobile and I experience some lag and I don't know if it is due to my not using sprite sheet animations instead of my shiny solution.

The question is: Is there some difference between the sprite sheet anim and swapping sprites from an array? I know Unity's API (that I used) cannot be called from other than the main thread. What about sprite sheet animations? Using another thread would definitely help but I can't do that and maybe they could.

# Answer
It could be due to a lot of reasons. Most of them maybe aren't even related to that..?

But, about performance, using a spritesheet should always be better than manually swaping sprites.

The probably best solution would be to use a custom shader which makes use of a Texture2DArray to play the animation. But that is quite harder than making a spritesheet.
> 1 votes

# Answer
I'd just like to add that you can view relevant performance stats, like draw calls, by selecting stats under the game tab in the Unity editor.

A sprite sheet is generally useful for reducing draw calls as the entire sheet can be pushed to the graphics card instead of each sprite individually (a costly operation). Have a search for "unity sprite sheet draw calls".
> 1 votes

---
Tags: unity, animation, performance, spritesheet
---


# Question
Title: No perfomance gain on LIBGDX GLES with sampler2D[]
I'm trying to render 3 textures 400 times (first,second,third 400 times). I use vertex shader that takes attribute tex\_id; - this is the id of texture to use. In fragment shader i have sampler2D textures\[3\]; and binding them via `setUniformi("textures[0..3],0...3);` So i draw all textures in one draw call binding them once. In desktop i have really fast results, but on GLES there is no difference at all. Using 1 draw call with 1 tetures binding, or using 400 drawcalls with 400 textures bindings has same fps. Why? First i think about gles limitations of lower android versions, then try adroid 4.4+ with API18 glSurfaceView20, but nothing changes.

# Answer
> 0 votes
So, there is no perfomance gain on phone, because of low end GPU + more complex fragment shader. if i work with only 2 textures = less "if statements" or readin from sampler2D\[\] in shader = more fps. Better way is to accurately use your textureAtlases and keep fragment shader for batching as simple as you can.

# Answer
> 0 votes
I think the problem you described is Libgdx Disable Vsync for Android Instead of Desktop. According to it, you could not disable vsync in your mobile device, and you could get same fps if the game performance is fine.

---
Tags: libgdx, shaders, opengl-es
---


# Question
Title: Problem if 2 HTC Vive into field of view of emitters?
I am developing an app for a trade fair that uses the HTC Vive.

Now I am wondering how the HTC Vive syncs with the sensors...I suppose it uses bluetooth, are the sensors "coupled" with the glasses for example with a MAC-Address or sth like that, so another glasses will not work at all, before not configuring it?

I mean, if for any reason another glasses (connected to other computer but powered on) come into the field of view of the emitters, could it be a problem?

Since I have no access at the moment for a second HTC Vive I can't just test it.

If someone has info regarding this it will be very useful.

# Answer
The HTC Vive synchronises with the emitters via the emitters giving a flash.

The emitters are kinda dumb (in an amazingly smart way), they give a flash to synchronise, then they scan a vertical line over the room, and then a horizontal line. Each one does that in turn.

All the sensors and intelligence is in the many IR sensors on the tracked devices. Given that the emitters don't need to be connected to the PC at all multiple should work fine.

Source: http://gizmodo.com/this-is-how-valve-s-amazing-lighthouse-tracking-technol-1705356768
> 1 votes

---
Tags: htc-vive
---


title: Simple bare-bones path-finding routine

text:
# Question
Title: Simple bare-bones path-finding routine
I have a 2D grid with a number of cells. I need to find a path from one cell to another. There are no obstacles or opponents, and all cells are identical. What is a SUPER SIMPLE routine to calculate the shortest path? I have read about A\* and other routines, but they are waaaaaaaay overkill in my case at this point. (Maybe I will need them later, in the future.) Thanks!

# Answer
> 1 votes
If you are locked to a grid and can only move in the four cardinal directions with no obstacles, then this becomes similar to the lattice path problem on Project Euler. If we call the dimensions on this lattice x and y, then subtract the destination's x from the start's x to get the number of steps right that need to be taken (left if negative). Do the same with y to get the number of steps up or down. The steps can be taken in any order (left then up, up then left, etc.) Each order will give you a different path, but get you to the same place. The number of paths when the change in x is the same as the change in y corresponds to the middle column of Pascal's Triangle. In other words, a 2x2 grid has 2 paths, a 3x3 grid has 6 paths, a 4x4 grid has 20 paths, and so forth. **All these paths have the same length.**

This means pathfinding doesn't work like normal. Usually, you would expect a straight line to be shorter, but if you approximate a straight line by zigzagging, you don't save any time.

```
    _|                            |
  _|     is just as long as       |
_|                           _ _ _|

```

The easiest to implement would be the latter example. However, if you want the zigzag that approximates the line, you can find x/y. This is how many to move right for every cell you move up. For example, if `x / y = 2`, then move like this: `right, right, up, right, right, up, ...`. If it is less than one, take the reciprocal, and move that much on y for every movement on x.

---
Tags: path-finding
---


title: System.Drawing.dll not found

text:
# Question
Title: System.Drawing.dll not found
I am creating an asset, in Unity, and I need to use `System.Drawing`. I have been trying to figure out how to add the DLL in a way that works, but I have had zero luck. I have tried adding the DLL to the assets folder, but it just shows up in Visual Studio as if it couldn't be found. I have also followed the instructions of a similar question, on the Unity Answers page, without any luck.

How do I use `System.Drawing` in Unity?

# Answer
After playing around with `System.Drawing` from my Windows folder, and noting that *all* answers on Google appeared to be incorrect in some way or another, I re-read the first answer I came across. I believe others have mentioned it, and at least one of the other answers attempts to utilise it. I will provide it, here, with all of the included steps. I was able to solve this problem after only *carefully* reading step one.

---

> **Best Answer**
> **Answer** by DarkCloud14 · May 16, 2012 at 10:55 PM
> Hi there,
> not sure if still someone wants to know how to use System.Drawing even if it's not officially supported by Unity. Ok here is what I've found out for Unity 3.5.1f2 so far:
>
> 1. If you wanna use it and don't want to get Errors in Unity Editor (not MonoDevelop) you must drag the file System.Drawing.dll into your Project tree. On default Windows Installation the file can be found in the following directory: `%Unity Folder%\Editor\Data\Mono\lib\mono\2.0` on OSX it should be in the Unity.app in somewhere. You may also be able to use the current `System.Drawing.dll` of Mono 2.10.8 but I didn't test this yet.
> 2. The Api Compatibility Level must be set to .NET 2.0!! The option ".NET 2.0 Subset" doesn't work.
> 3. For a Windows only version you would be done now and it should work. I didn't test the whole functionality of System.Drawing!! I just tested some of the Bitmap functionality.
> 4. Additional step for MacOSX: After you've build the Application you should open the .app/Contents directory. Create a Plugins directory there and the copy the file libgdiplus.dylib from the lib directory of Mono 2.10.8 for OSX (On windows you can use 7-zip and some other tools to get the libgdiplus.dylib from the OSX download image)! After another test the version of Unity at least the one shipped with Windows Unity doesn't work. Now rename the file libgdiplus.dylib to gdiplus.dll.bundle. After that it should also work under OSX.

---

You will note the inclusion of accessing `%UnityFolder%\Editor\Data\Mono\lib\mono\2.0`, much like the alternate answer. You should note that **this is not** where you put `System.Drawing.dll`. In fact, if you have done so in following the previous answer, read on; you may have caused some damage.

This is actually where you will *find* `System.Drawing.dll`; or at least, the version you want to copy and paste to your *Assets* folder. The version from your *Windows* folder is likely of a newer version, as was the case, with me. You might prefer the newer version, but unfortunately, Unity does not. They are simply not compatible.

The version you find in your *mono* folder *is* compatible. It is for this reason that I advise against attempting to *place* `System.Drawing.dll` here. You will likely overwrite the older version with the newer version, which is not compatible with Unity.

---

To sum up, access `%UnityFolder%\Editor\Data\Mono\lib\mono\2.0` to locate a *compatible* version of `System.Drawing.dll`. Copy this file to your assets folder. You should immediately note the inclusion of `System.Drawing.dll` in your script references1, and be able to use it as intended.

1 At least, it is immediately noticeable in MonoDevelop.
> 4 votes

# Answer
On macOS 10.12 with Unity 5.6.1f1, System.Drawing.dll was in `/Applications/Unity/Unity.app/Contents/Mono/lib/mono/2.0`.
> 0 votes

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


# Question
Title: How does someone go about selling a game or making a royalties deal with Nintendo(or Pokemon Company)?
It seems like Niantic did just that. If someone were to create their own game(Pokemon, hypothetically), how would they, if at all possible, sell that game to Nintendo or at least make a royalties deal? Or any other game, for that matter?

# Answer
> 1 votes
With regard to other people's IP (intellectual property), it's almost always a **"don't call us, we'll call you"** situation.

Most companies like to keep their IP in-house, or hand-pick the studios they might be interested in contracting with. When these deals do happen, it's usually not so much a matter of "you make your game and then offer us a royalty for using our IP" as "you will work in cooperation with us to develop a game according to our direction and approval. We'll pay your development costs on a milestone basis, and offer you a cut of the sales once we recoup those costs" (like a traditional publishing arrangement, or sub-contract, depending on the degree of creative freedom involved)

So, these deals can be quite involved to negotiate and see through. Moreover, you never know when a company whose IP you want to work with already has other plans for it - like a game already in development but unannounced, a deliberate pause in the release schedule to avoid brand fatigue, or negotiations in progress with another studio. So if you're making the first move, there's a risk you might sink time and energy into developing a compelling pitch when the answer was always going to be "no" before you even got a meeting.

(I say this as someone who once lost days developing some pretty sweet claymation shaders when, due to a miscommunication, we briefly thought our studio had a shot at a contract for a Clayfighter game) ;)

The one exception is when you have some demonstrated expertise that would give you something unique and compelling to offer the IP holder, something you can do for them that's outside of their experience - as arguably Niantic brought to the table with their mobile, location-based gaming know-how (and geomapping data) from Ingress.

If all you have is good game design or skilled artists/developers/musicians, that's great, but so do many other development studios around the world, so it's unlikely to stand out enough for a successful company to want to risk their IP on you.

Better to take work for hire contracts, where companies are actively soliciting developers to work with their IP, or develop your own games with your own original IP. Along the way, you might develop a high enough profile that IP holders will come to you for your skills, and even if not, you're still selling games. :)

---
Tags: nintendo
---


# Question
Title: Question about creating Enemies in C++ RPG
I don't know if this is Technically the right place to ask this but I need help designing a function, I need a Rubber Duck if you would.

I'm working on an Enemy class for my C++ RPG and I am in need of some suggestions.

The Base of my design as far as the Battle system and Character Objects and Enemies and such is that all have an ID. A simple int as it were that I associate with Character Names via enum ie.

```
enum class Character {PLAYER1 = 0, PLAYER2 = 1};

```

and enemies like so.

```
enum class Enemy {WOLF = 0, GHOST = 1, LICH = 2};

```

I have a random number generator and a map to my enemy enum in my mob class that does two things.

1. selects an amount. // Self explanatory how many enemies there are.
2. Selects a random ID from the map. // The type of Monster you'll face.

My Question is, how would I design a function that will construct an enemy based on it's ID?

# Answer
> 1 votes
I suggest using the Type Object pattern, as described in Game Programming Patterns by Robert Nystrom:

> Define a type object class and a typed object class. Each type object instance represents a different logical type. Each typed object stores a reference to the type object that describes its type.

Move traits common to all monsters of the same type into an instance of a breed class (like max hp or name). When creating a new monster, randomly select a breed from a collection, and then give the newly created enemy a reference to that breed.

This way, you only need to define the properties of each breed at the beginning of the game, and they could be loaded from a file instead of defined programmatically. This will minimize the amount of duplicate code you have to write for each type, reducing the likelihood of introducing errors and making it easier to read.

In addition, now you can swap the monsters type at any time, like from living into undead or into a sheep with a spell of polymorph.

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


# Question
Title: Change transparency of image at runtime, LOVE2D
I would like to know how to take a defined image (e.g. a tile) in the LOVE game engine and draw it with a transparency that may vary per-frame. Stencils seem to only work for completely hiding parts of an image; I need to make an entire tile translucent, and the degree of translucency needs to be able to vary during gameplay.

(purpose: I am messing around with a game idea that involves partial information during fog-of-war, represented by superimposing all tiles that might be somewhere based on what you currently know)

# Answer
> 2 votes
Just set the color to white-with-less-than-full alpha before drawing the image. For instance, this would draw your image at around 50% opacity:

```
love.graphics.setColor(255, 255, 255, 128)
love.graphics.draw(image, 0, 0)

```

The easiest way to work with this if you want to fade something in / out is to have a fractional multiplier value from 0 to 1 and set the alpha component to 255 * that, i.e.

```
love.graphics.setColor(255, 255, 255, 255 * someMultiplier)

```

---
Tags: graphics-programming, lua, love2d
---


# Question
Title: How to make a script work when clicked only on the given prefab?
I am very new to unity but not to C#.

I am working in Unity 2D

I made this prefab called LongLane. Its basically a collection of sprites of road, put together into a Gameobject. Now I wanted objects to spawn on the road when I ONLY click on the road, I can spawn the object on the road but they spawn regardless of where I click. I have written some code but they aren't clear and readable.

So how do I make a script work only when clicked on that specific prefab

# Answer
Add a script to the prefab where you check if the button has been pressed then raycast to get the position of the hit. If this doesnt work, make sure your prefab has a collider component.

```
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            var clickposition = hit.point;
            // insert code to spawn object at clickposition
        }
    }
}

```

**Note** If you'll only perform this action on mousedown or up you can save one check on `if (Input.GetMouseButtonDown(0))` every update by implementing the `void OnMouseDown()` or `void OnMouseUp()`. This will make your update cleaner as well.

Similar Question: Move object to mouse click position
> 1 votes

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


# Question
Title: how to solve slow framerate (how to solve situation when user uses computer much slower then minimum requirement)
We have some minimum requirements set for the game, however, it's possible to play the game on much slower computers and we argue in the team how to approach the situation when the hardware is too slow to run the game the way it's meant to run.

We generally have three ideas:

1. run benchmark in the beginning and if the computer won't pass it inform the player he can't play, he should update drivers etc,
2. under certain framerate pause the game and ask the player to disable thing running in background or update drivers etc.

(1. and 2. can be combined)

3. under certain framerate slow the game down - so let's say the game should run on 60 FPS and between 60 and 20 the speed will be normal and if it goes lower than 20 fps it will progressively slow down so the player sees the same amount of frames as it'd run at 20FPS

In our case, the game looks pretty bad when we simulate 10 FPS and less and it isn't nice under 20.

Is there any common approach to this?

# Answer
I think most would agree that it is (too) annoying to support lowest-end hardware.

Common or not, I cannot tell, but here is one set of principles that fits one of **our** products (a rather advanced 3D simulation, aimed at households and professional users) but **not necessarily others**:

**1. Questions**

We often get the question "what GPU should it be?". We give no specific answer, instead we give the guidelines below.

**2. Type of hardware**

There are consumer and professional products. For example the Nvidia "Quadro" series of 1/2-height GPU's are very durable and expensive - but slow. These are often used by authorities. We do **not** recommend these, instead we recommend **consumer products**.

**3. GPU**

* (Very generic) We propose the graphics card costs at least 80 euros if bought today in the nerdy store.
* (A bit more specific) We require a Passmark-score of at least 1000 per screen (up to 4 supported).

It's easy to check any GPU, just google for example

*passmark GTX760*

The first hit is usually the good one, tells us this GPU gets 4947 points - excellent for 4 screens.

https://www.videocardbenchmark.net/gpu.php?gpu=GeForce+GTX+760&id=2561

**4. Low-end support**

We do absolutely not bother to support bad or outdated hardware.

**5. Code/settings**

Small team - we have pre-selected good, reasonable values for texture filtering etc., that make it look good. These are fixed in the code. Eg. Antialias multisampling is set to 4 samples, as 8 or 16 was a sufficient cost with no relevant impact. This depends very much on the visualisation.
> 1 votes

# Answer
Nobody's going to keep playing if they're at ~15 FPS or less. **I'd just ignore the problem**. Down-scaling the game speed for low-fps players goes against the consistency principle; if I were to play your game and find out that the game plays differently, depending on the FPS, I'd just drop it.

You could implement different speeds that can be selected by the players, not forced upon them.

It might help if you'd tell us the minimum hardware requirements and a few FPS-related statistics for different hardware.
> 0 votes

---
Tags: frame-rate, hardware, requirements
---


# Question
Title: How to trigger poison effects efficiently
I'm trying to trigger poison effects at the end of each turn in a turn based game. Each Actor in battle has a list of active effects, each of which could be a poison. I simply want to Execute() all of those Poisons.

See my code below; is there a way I can combine my two queries or make them more efficient so that the moment a Poison is found, that Poison executes?

```
var poisonedActors =
            from Actor actor in ins.BattleParticipants
            where actor.ActiveEffects.Any(activeEffect => activeEffect is Poison)
            select actor;
var poisons =
            from ActiveEffect activeEffect in poisonedActors
            where activeEffect is Poison
            select activeEffect;
foreach (Poison poison in poisons)
            poison.Execute();

```

EDIT: Is this more efficient? Is there a better way to do things?

```
    foreach (Actor actor in ins.BattleParticipants)
        foreach (ActiveEffect activeEffect in actor.ActiveEffects)
            if (activeEffect is Poison)
                activeEffect.Execute();

```

# Answer
A "performance critical" part of your code is the check `if (activeEffect is Poison)`

It looks as though Poison inherits from `ActiveEffect` but that it is different from the other classes that inherit from `ActiveEffect` since you want to call execute separately.

**I would do this if performance was critical:** create a separate list (`ActiveEffectsExecuteOnTurnEnd`) in 'Actor' where you only put stuff that will execute at the end of the turn.
> 2 votes

---
Tags: c#, databases
---


title: Getting choppy, jumpy animation

text:
# Question
Title: Getting choppy, jumpy animation
Hey I'm trying to get a smooth animation for my player movement. Earlier I changed my frames to render at fixed time(1/60 sec). Well that makes my player now run at a constant speed but the animation now appear to be choppy and it seems like the player jumps from one point to another instead of smoothly transitioning between them. Below is my code and an gif animation of player movement. How do I make the animation appear smooth?

```
float deltaTime = 0;
float oldTime = 0;

//The direction in which the player will move
int playerX = 0;
int playerY = 0;

//callback method for keyboard events
void keyboard_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
    if (key == GLFW_KEY_W && action == GLFW_REPEAT) {
        playerX = 0; playerY = 1;
    }
    if (key == GLFW_KEY_S && action == GLFW_REPEAT) {
        playerX = 0; playerY = -1;
    }
    if (key == GLFW_KEY_D && action == GLFW_REPEAT) {
        playerX = 1; playerY = 0;
    }
    if (key == GLFW_KEY_A && action == GLFW_REPEAT)
    {
        playerX = -1; playerY = 0;
    }
}

//update player's position
void update() {
    player->move(playerX, playerY, TIME_PER_FRAME);
}

//set up glfw keyboard callback function and other stuff
void init() {
    glClearColor(0, 0, 0, 0);
    player->bindVertexAttributes(shader.getAttributeLocation("position"));
    glfwSetKeyCallback(window->getGLFWWindow(), keyboard_callback);
}

//wait logic
float expected_frame_end = glfwGetTime() + TIME_PER_FRAME;
void wait() {
    while (glfwGetTime() < expected_frame_end) {

    }
    expected_frame_end += TIME_PER_FRAME;
    playerX = playerY = 0;
}

//rendering function
void render() {
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    player->setUniformMatrixLocation(shader.getUniformLocation("projectionMatrix"), shader.getUniformLocation("transformationMatrix"));
    shader.useProgram();
    update();
    player->render();
    wait();
    shader.stopProgram();
}

//main function
int main(int argc, char** argv) {
    init();
//main loop
    while (!glfwWindowShouldClose(window->getGLFWWindow())) {
        render();
        window->swapBuffers();
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

```

# Answer
Not sure what happens in your `player->move()` but it seems the problem is your wait logic setting the x and y movement to 0.

This will make the player stop until keyboard input is polled again and this can be what causes the jittering in movement.

I see you defined the deltatime and oldtime but not used them. You should do is to update the movement dependent on the time elapsed since the last frame. Something like this: `float deltaTime = glfwGetTime() - oldTime;` This might require you to add a speed parameter to the character movement to define how many units it should move per second. For example `player.x += playerX*speed*dt;`

if speed is 1 the player will move 1 unit in the x direction per second
> 1 votes

---
Tags: opengl, animation, glfw
---


# Question
Title: How to make camera smooth when following player
When my character moves through my cameras 'FollowPlayer' script, the background just looks really glitchy and bad Is there anyway to fix this?

This is my script:

```
using UnityEngine;
using System.Collections;
public class FollowPlayer : MonoBehaviour {
    Transform bar;

    void Start() {
        bar = GameObject.Find("PlayerMovingBar").transform;
    }

    void Update() {
        transform.position = new Vector3(
            bar.position.x, transform.position.y, transform.position.z);
    }
}

```

# Answer
> 1 votes
Using Lerp will give a smooth following effect as @Hellium mentioned. It's also recommended to use it in the `LateUpdate()` method.

See Unity documentation for that : MonoBehaviour.LateUpdate()

Good luck on your project!

# Answer
> 0 votes
You may simply need to Lerp to the desired position :

```
public float followSpeed = 10 ; // Change the value here to have the desired result

void Update() {
    Vector3 targetPosition = new Vector3(bar.position.x, transform.position.y, transform.position.z);
    transform.position = Vector3.Lerp( transform.position, targetPosition, followSpeed * Time.deltaTime );
 }

```

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


# Question
Title: In what order should collisions be resolved?
I am creating my 2D game engine and I need to know if I should first move all objects and then resolve collisions with all objects or I should move and resolve collision one by one objects.

# Answer
Of the games I have made (2D or 3D) I move and resolve collisions one-by-one. I did not choose this because it was necessarily superior, but that the logic seemed simpler when I initially made it.

If your objects are moving slowly enough, it should not matter. However, if you have objects that can move considerable distances with each step, potentially stepping over another object, then it might be an issue.

I had this issue in one game and I resolved it by modifying my alghorithm to also check for collisions that **could have occurred anywhere along the path of movement** between steps. This fixed the issue with me, since the faster moving objects were usually processed last. If you are still having trouble, you could do one better and check if a **collision could have occurred because two paths of movement crossed**.

Thus, either approach was fine from a practical standpoint. In this case I went with the one-by-one processing because it made sense in my particular workflow.
> 2 votes

---
Tags: collision-resolution
---


# Question
Title: Why when switching between cameras the speed movement value of the camera is showing for a second?
It's showing for a millisecond. When i switch between the cameras there is a filed that should show the current camera speed movement in case the camera is moving.

Now the cameras are not moving. But yet when i switch between the for a millisecond i see a number value on the speed filed. How can i make that if the cameras are not moving then don't display anything in the speed movement filed ?

Could be the cameras are moving a bit even if they are "not" moving ?

The switch cameras script:

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

public class SwitchCameras : MonoBehaviour {

    public Camera[] cameras;
    public int currentCamera = 0;

    void Awake()
    {
        if (cameras == null || cameras.Length == 0)
        {
            Debug.LogError("No cameras assigned..", gameObject);
            this.enabled = false;
        }
    }

    void LateUpdate()
    {
        if (Input.GetKeyDown(KeyCode.C))
        {
            // disable current
            cameras[currentCamera].enabled = false;

            // increment index and wrap after finished array
            currentCamera = (currentCamera + 1) % cameras.Length;

            // enable next
            cameras[currentCamera].enabled = true;
        }
    }
}

```

The user information script where i update the ui Text with the cameras info:

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

public class UserInformation : MonoBehaviour
{
    public Text cameraName;
    public Text cameraSpeed;
    public Text cameraOriginalPosition;
    public Text nextTarget;
    public Text nextTargetPos;
    public Text nextTargetDis;
    public SwitchCameras switchcameras;
    public Transform target;

    private Vector3[] originalCamerasPosition;
    private Vector3 lastPosition;
    private Camera[] Cameras;
    private int cameraIndex = 0;

    // Use this for initialization
    void Start()
    {
        Cameras = switchcameras.cameras;
        if (Cameras.Length > 0)
        {
            originalCamerasPosition = new Vector3[Cameras.Length];
            for (int i = 0; i < Cameras.Length; i++)
            {
                originalCamerasPosition[i] = Cameras[i].transform.position;
            }
        }
    }
    // Update is called once per frame
    void Update()
    {
        if (cameraIndex == Cameras.Length)
            cameraIndex = 0;

        if (Cameras[cameraIndex].enabled == true)
        {
            cameraName.text = Cameras[cameraIndex].name;
            float camSpeed = (Cameras[cameraIndex].transform.position - lastPosition).magnitude / Time.deltaTime;
            cameraSpeed.text = camSpeed.ToString();
            lastPosition = Cameras[cameraIndex].transform.position;
            cameraOriginalPosition.text = originalCamerasPosition[cameraIndex].ToString();
            if (target != null)
            {
                nextTarget.text = target.ToString();
                nextTargetPos.text = target.transform.position.ToString();
                var distance = Vector3.Distance(Cameras[cameraIndex].transform.position, target.transform.position);
                nextTargetDis.text = distance.ToString();
            }
        }
        else
        {
            cameraIndex++;
        }
    }
}

```

I have a UI empty GameObject and under it as children i have a Canvas \> Panel and under Panel i have the buttons and texts and labels.

The Switch Cameras script is attached to another empty GameObject and under this one as children i have all the Cameras. Main Camera and two other Cameras.

Update:

This is what i tried now in the UderInformation script:

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

public class UserInformation : MonoBehaviour
{
    public Text cameraName;
    public Text cameraSpeed;
    public Text cameraOriginalPosition;
    public Text nextTarget;
    public Text nextTargetPos;
    public Text nextTargetDis;
    public SwitchCameras switchcameras;
    public Transform target;

    private Vector3[] originalCamerasPosition;
    private Vector3[] lastPosition;
    private Camera[] Cameras;
    private int cameraIndex = 0;

    // Use this for initialization
    void Start()
    {

        Cameras = switchcameras.cameras;
        if (Cameras.Length >= 1)
        {
            originalCamerasPosition = new Vector3[Cameras.Length];
            for (int i = 0; i < Cameras.Length; i++)
            {
                originalCamerasPosition[i] = Cameras[i].transform.position;
            }

            lastPosition = new Vector3[Cameras.Length];
        }
    }
    // Update is called once per frame
    void Update()
    {
        if (cameraIndex == Cameras.Length)
            cameraIndex = 0;

        if (Cameras[cameraIndex].enabled == true)
        {
            cameraName.text = Cameras[cameraIndex].name;
            lastPosition[cameraIndex] = switchcameras.lastCameraPosition;
            float camSpeed = (Cameras[cameraIndex].transform.position - lastPosition[cameraIndex]).magnitude / Time.deltaTime;
            cameraSpeed.text = camSpeed.ToString();
            cameraOriginalPosition.text = originalCamerasPosition[cameraIndex].ToString();
            if (target != null)
            {
                nextTarget.text = target.ToString();
                nextTargetPos.text = target.transform.position.ToString();
                var distance = Vector3.Distance(Cameras[cameraIndex].transform.position, target.transform.position);
                nextTargetDis.text = distance.ToString();
            }
        }
        else
        {
            cameraIndex++;
        }
    }
}

```

But still the camera/s speed part is not working good. When i'm running the game the first camera is not moving but i see the speed value changing very fast. Then when i switch the cameras when it's getting to the moving camera it's showing the speed very fast running numbers so i can't track it with the eyes.

The question is why first time i see speed values when the camera is not moving? And if the code should be this way ?

# Answer
> 1 votes
Basically, your speed equation doesn't consider that the camera can change. Consider:

1. You update `lastPosition` with the position of the current camera.
2. You switch cameras.
3. `camSpeed` is calculated using the difference between the camera's current position and `lastPosition`.

Those are different positions, because `lastPosition` was the position of the last camera, not the current camera.

Fix it by either tracking `lastPosition` per camera, or update `lastPosition` when you switch cameras.

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


# Question
Title: Has anyone ever made a shader that produces something similar to pixel art?
I find that pixel art is really pleasing to look at; it has this kind of crisp, satisfying perfection to it.

I've been following some beginner pixel art tutorials, when I got an idea: what if someone made a shader (in GLSL for example) that took 3D scenes and did the best possible job at making it look like it was drawn by a pixel artist? The concepts of anti-aliasing and shading should be relatively easy to perform. Constraining your colour palette would be very simple as well.

Of course, no computer program could outdo the manual work of a great pixel artist, but has anyone ever tried this before?

* Is this idea at all possible?
* Are there any games that use it?
* Have there been (documented) failed attempts?

# Answer
> 2 votes
To get a look very close to pixel art, simply use a cel shader and upscale the result without interpolation.

This will give you proper results for still images, but the illusion will fall apart as soon as you see it in motion. Why? Because there are some things which you see very rarely in classic pixel art games, because they take tremendous effort to create:

* Rotating objects by angles which are not divisors of 360°
* Allowing objects to rotate on more than one axis
* Enlarging and shrinking objects in non-fixed steps
* Use a very large number of animation frames
* Changing the direction from where an object is lit

When you overdo any of that, the viewer will notice you are actually using a 3d engine and not real pixel-art.

* To avoid uncanny scaling, use an orthographic projection.
* To avoid uncanny rotations, only rotate objects by 90° angles (45° at most). That includes your camera. Note you can get away with *starting* at an uneven angle. That way you create fake pixel art with an isometric or dimetric perspective.
* To avoid uncanny animation smoothness, jump directly between animation keyframes without interpolation.
* To avoid uncanny light direction changes, use ambient and constant directional light only (what you can change, though, is light color and intensity. "Real" pixel art games often simulate that by changing the color palette)

---
Tags: shaders, fragment-shader, pixel-art
---


# Question
Title: 2D Circle detection algorithm partially working
Hello GameDev stack exchange!

I'm adapting a rectangle to circle collision detection algorithm from the second (not the accepted) answer from here: https://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection. This is C++ code. Here is my adaptation:

```
bool Collision::checkCircleToRectCollision(sf::CircleShape circle, float rectX, float rectY, float width, float height)
{
    sf::Vector2f circleDistance;

    circleDistance.x = std::abs((circle.getPosition().x - rectX) + circle.getRadius());
    circleDistance.y = std::abs((circle.getPosition().y - rectY) + circle.getRadius());

    if (circleDistance.x > (width / 2 + circle.getRadius())) {
        return false;
    }

    if (circleDistance.y > (height / 2 + circle.getRadius())) {
        return false;
    }

    if (circleDistance.x <= (width / 2)) {
        return true;
    }

    if (circleDistance.y <= (height / 2)) {
        return true;
    }

    float cornerDistance = ((circleDistance.x - width / 2) * (circleDistance.x - width / 2)) +
                          ((circleDistance.y - height / 2) * (circleDistance.y - height / 2));

    return cornerDistance <= (circle.getRadius() * circle.getRadius());
}

```

The problem is the collision detects only the lower right section of the circle. Without the `+ circle.getRadius()` inside of `circleDistance.x = std::abs((circle.getPosition().x - rectX)` the algorithm detects even less area. Here is a a picture to visualize. I want the algorithm to detect the entire blue area. It currently only detects the red area. This is a an approximate, but very accurate from what I can tell. The white box is my players hitbox.

I've spent a few days googling and this is the closest I've gotten, but now I'm stuck. How can I make the algorithm detect the entire blue circle? Thanks in advance! :)

# Answer
> 1 votes
So it seems that I was passing my function described in the original post the wrong values. Passing the correct values works well enough that I'm marking this as solved and answering my own question. I changed the following in main.cpp:

```
if (collision.checkCircleToRectCollision(circle, player.boundingBox.getPosition().x,
                                                 player.boundingBox.getPosition().y,
                                                 5, 5)) {
     //Collision
}

```

to use the correct player values:

```
if (collision.checkCircleToRectCollision(circle, player.boundingBox.getPosition().x,
                                                 player.boundingBox.getPosition().y,
                                                 player.size.x, player.size.y)) {
     //Collision
}

```

And all is well. Thanks anyways! :)

---
Tags: c++, 2d, collision-detection
---


# Question
Title: Procedurally generating a building of specific area
Myself and a team are working on a factory builder game that gives the player a random factory at the start of the game. To try to make sure there is a sense of "fairness," ideally the randomly generated factory would have an area within a few units of (placeholder value) 30.

Its relatively simple to write a basic random rectangle generator to meet these specifications, but our goal is for the factory to be more complex, perhaps made up of 2, 3, or even 4 intersecting rectangles, producing more complex shapes (think of L, U, and O shaped buildings).

I've tried generating a random rectangle and then using basic algebra to fill in a 2nd rectangle, but so far I've had no luck implementing more than 2 rectangles, and even then I am unhappy with the results for just a 2 rectangle design.

Some more relevant info: 2D top down Some of the mechanics are factorio style so rooms should have reasonable length and width to allow room for machinery Currently in Java and Lua (can use built in libraries from either if needed)

Thanks in advance!

EDIT: When I say "good" or "bad" outputs, a bad output would be any output which has space unusable by the player. The factory shape limits where the player can place factory machines such as conveyor belts. Ideally, the factory shouldn't have areas that are only 1-2 blocks wide, the shape shouldn't be one or two big rectangles with a line of 1-2 blocks "hanging" out to one side. A good output would be where all floor space is "workable", so all areas are at least 3-4 blocks wide. A good output doesn't always have to be complex (1 or 2 rectangles is okay), but it should have a fair chance if being made up of more than 1-2 rectangles.

# Answer
You could use pre-generated polyominoes as meta shapes to build an assortment of buildings.

Let's say your minimum acceptable distance is 3 blocks. Then the smallest acceptable building unit we'll consider is 3x3. For convenience, I'm going to call that a cell & it gives an area of 9 blocks. Next, take your target starting area & divide it by the cell area. Using the starting value you gave, we get 3.333; so 3 cells would give you a bit less than you want & 4 cells would give you more.

From here you have a couple of options. If you're flexible on your starting area, use whatever method works best for you to pick the number of cells that gives you an acceptable amount (i.e. round to the nearest value, round up, etc). I'm going to call this the cell count.

Next, randomly select the polyomino with the desired cell count. Replace each square on the polyomino with a building cell & you have your final shape.

To illustrate, say we choose to round down. Here are all the size 3 polyominoes (not including rotations / flips):

Let's assume we randomly pick the L shape & apply a random rotation, your building would have the following layout:

A couple of issues. First, there's a limit on the number of cells you can use. Wikipedia will give you all polyominoes up to size 8 (octomino). It includes summary data for up to size 12, but I don't know if there's an online listing for all them. Second, the solution above only works exactly for building sizes that are multiples of 9. There are a couple of ways to work around some of these issues:

1) Use a different cell size. For instance 3x4, 4x4, etc.

2) Add additional cells to a starting polyomino. This can be tricky if you must ensure all shapes are equally likely, but chances are for most game dev purposes you don't need a truly uniform distribution of building shapes.

3) Pad out out a building to make it bigger. Going back to the example, if you used 3 cells, your building would have an area of 27 squares leaving you short by 3. You could then scan the perimeter for a location to glue a size 1x3 group of squares. As long as your makeup group is at least AxB where A is at least your minimum acceptable distance, your result will not violate your minimum acceptable distance constraint. Building off the example above, here's an illustration of a possible result:

4) Instead of padding out a building that's too small, you could trim down a building that's too large. Ensuring that your minimum acceptable distance constraint is followed is more complex than the padding option, but would give you more alternatives to consider.

Some other comments:

Just because you could use all possible polyominoes of a given size doesn't mean you should. If some of them aren't fun, break your theme, are offensive to your audience (swastika patterns), or cause some other problem, take them out. Also, you could weight your selection routine if some patterns are interesting, but too weird to routinely pop up. Finally, you could use this solution in combination with your current strategy. Maybe 70% of the time you generate rectangular buildings & 30% of the time you use the polyomino approach. Or maybe you start with a rectangular building & glue a small polyomino to the outside.
> 7 votes

# Answer
A simple way to build a procedural generator is:

1. Randomly build things
2. Run a function that checks whether the output is good
3. If the output is not good, go to step 1

Even if it takes thousands of runs to complete, most simple generators get by just fine with this approach. The advantage is that there's not a lot of smarts required in the generator, and since checking whether something's good is much easier than building something that is good 100% of the time, this approach is very easy.

You've listed some objective measures on whether an output is good; that should be enough for you to create a quick and dirty generator. Place rectangles at random inside an area, and reject the output if, for example, there are areas that are only 1-2 blocks wide.

Start with that, improve and optimise afterward.
> 16 votes

# Answer
Given a restriction of "all areas are at are at least 3-4 blocks wide" the first idea that leaps to my mind is something like the following:

1. pick one of 3x3, 3x4, 4x3 or 4x4
2. place a block of that size in the center of the grid
3. pick a direction (up, left, right, down)
4. try to place a 3x3 block alongside previously placed blocks in that direction
5. if successful, with some probability, try to expand the block to a 4x3 block in one of the directions you didn't just pick
6. with some probability, move a to random edge of the filled in blocks
7. repeat steps 3 to 6 until the area is large enough

The basic idea is, given you want all areas to have at least a given size, only work in areas that are that size. More generally, if you want something to be true of all generated outputs, see if it can be made true of all partially generated outputs.
> 7 votes

# Answer
Consider using booleans NOT and UNION and choosing between them randomly.

1. Place a random rectangle.
2. Place a second random rectangle.
3. Randomly choose whether to UNION them or SUBTRACT the second from the first.
4. Repeat for a number of rectangles. Although, only two or three might give reasonable enough results.

Then, I would calculate the area and scale it up or down to more closely match the approximate size you seek, and then test that there are no dimensions less than a required minimum amount.
> 0 votes

---
Tags: java, 2d, procedural-generation, geometry, lua
---