# Question
Title: Any tips for aligning existing sprite sheets to a grid?
I've been dabbling with sprites, and I've found most sprite sheets that have been posted for existing games (for example, Sonic & Knuckles) are not aligned to a grid.

I've found this frustrating when trying to use these sheets to set up animations in Unity. I managed to align the spritesheet above manually, but it took a while and I'm wondering if anyone has tips on how to make this process easier/faster?

# Answer
in your example, the frames are divided into unequal parts, but they have a pivot poitn down the center. Unity has the ability to create frames automatically
> 3 votes

---
Tags: 2d, animation, sprites, spritesheet
---


# Question
Title: Why when adding audio foot steps to the character using animation events only one foot play the sound?
The animation in the Animator is HumanoidWalk In the inspector of the animation in the Animation tab at the bottom I clicked on the Events clicked to add event names the function as Step and moved the time slider to 0.67 moved the slider in the preview window of the character so the right leg foot will be close to the ground and clicked on apply:

Then I did the same but changed the time a bit more almost to 0.7 and called the function Step again and at the preview window now it';s the other leg foot close to the ground and clicked apply:

I added to the character in the hierarchy a Audio Source component and a script name Foot Steps:

And the script it self:

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

public class FootSteps : MonoBehaviour
{
    [SerializeField]
    private AudioClip[] clips;

    private AudioSource audioSource;
    private GameObject[] Foots;

    private void Awake()
    {
        audioSource = GetComponent<AudioSource>();
        Foots = GameObject.FindGameObjectsWithTag("Foot");
    }

    private void Step()
    {
        AudioClip clip = GetRandomClip();
        audioSource.PlayOneShot(clip);
    }

    private AudioClip GetRandomClip()
    {
        return clips[UnityEngine.Random.Range(0, clips.Length)];
    }
}

```

In the Hierarchy in the script in Clips I added same 8 audio clips just for the testing I could add only 1 it doesn't matter:

When running the game I marked with blue circle only this foot play the step/s sounds. And if I change the time to be the same 0.67 it will play two sound the same so it will sound like one or if the time is 0.67 and 0.7 it will hear two steps but only on the left leg foot.

The second leg foot never play the sound no matter how many times I changed the preview animation legs.

I tried to follow the instructions of this tutorial but no success:

Add foot steps tutorial

Should be simple but only one foot is working. I can't figure out what am I missing.

# Answer
I have had trouble calling events on the animator. This doesn't answer your specific question but provides another solution. The way I do footstep sounds is to raycast from the foot bone and play the footstep sound effect that corresponds to the surface which the raycast collides with. You can set the surface type several ways. I use layer mask since it is easily integrated with `Physics.Raycast()`. Physics.Raycast reference

```
private void PlayFootStepSound(){
    RaycastHit hit;

    if(Physics.Raycast(footBone.transfrom.position,
    -footBone.tranform.up, out hit, stepDistance, surfaceLayer){

        // make the magic happen....
    }
}

```

Hope this helps.
> 1 votes

# Answer
"You're adding your events at the wrong timestamps. Take a look at the little white line in the "Events" timeline. In your first screenshot, the line is right past 0:33 and in your second screenshot, the line is slightly right of 0:83. That's where your events should be (not 0:67 and 0:70)."

It was my wrong thought that I need to set the timestamp on my own. Instead all I needed to do is to set in the preview window each time the step of the character for each foot and when clicking on the add event button it's setting the timestamp automatic. And I was setting it on my own. This part was not explained in the video tutorial I followed:

Add footsteps tutorial
> 0 votes

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


# Question
Title: How to get crash reports from game Unity3d
I am working on a project and I am in need of to gather CrashReports, email crash log, along with allowing the user to describe how the crash happened. I cannot find anything on how to do this, anyone has any ideas? Thanks!

-Learning Unity User

# Answer
I suggest you look at Cloud Diagnostics in Unity.

I used this feature to keep track of crashes in my game.
> 2 votes

---
Tags: unity
---


# Question
Title: Position of an object relative to another in a 2D plane
I have two objects, A and B, each of them has a set of coordinates (x,y). How do I understand where is A in relation to B's position?

If I where to just check each coordinates I could do it like this:

B(x:5,y:5), A(x:4,y:5); x = 5-4 = 1; y = 5-5 = 0; A it's on the left

B(x:5,y:5), A(x:6,y:5); x = 5-6 = -1; y = 5-5 = 0; A it's on the right

B(x:5,y:5), A(x:5,y:6); x = 5-5 = 0; y = 5-6 = -1; A it's on top of B

B(x:5,y:5), A(x:6,y:5); x = 5-5 = 0; y = 5-4 = 1; A it's under B

But I was wondering, since I'm using a standard Vector2 data structure (from LibGDX), with the ability to normalize, compute distances, etc.. If I could do it using those methods instead of subtracting the coordinates each time.

If it can help, I need to know the position of A relative to B because A is supposed to push B, so if A it's on B's left, B needs to move right, etc...

# Answer
> 0 votes
If you want to get position A relative to B, you just need to substract them, like you were doing. If you want to make use of the methods, you can use the method "sub": https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/math/Vector2.html#sub-com.badlogic.gdx.math.Vector2-

```
Vector2 relative = A.sub(B); //contains the position of A relative to B
Vector2 direction = B.sub(A); //direction that B will move after being hit by A

```

# Answer
> 0 votes
Coordinates of A xa,ya and B xb,yb and vector AB X=xa-xb ,Y=ya-yb

I give a formula to give point A in relation to point B in 8 directions.

For E=0,NE=1,N=2,NW=3,W=4,SW=5,S=6 and SE=7

F(X,Y)=MOD((4-2\*(1+SIGN(X))\* (1-SIGN(Y^2))-(2+SIGN(X))\*SIGN(Y)

```
  -(1+SIGN(ABS(SIGN(X*Y)*ATAN((ABS(X)-ABS(Y))/(ABS(X)+ABS(Y))))

  -PI()/(8+10^-15)))/2*SIGN((X^2-Y^2)*(X*Y))),8)

```

---
Tags: java, mathematics, vector, coordinates
---


# Question
Title: Trigger an event only if two colliders fully cover each other
Let's say I have two different objects that can go through each other. Both have a circle collider (2d) that has the exact same size and there is a good chance that the two colliders will completely overlap each other. How can I trigger an event when that happens?

# Answer
> 2 votes
In that case you might just want to compare their positions:

```
if (transform.position == other.transform.position) {

```

Keep in mind that this checks for *exact* equality. Positions are floating point values and many games leave them to the physics engine, so they might differ by a miniscule amount which is invisible to the player but visible to the scripting engine. Actually, Vector3 overloads the == operator to return `true` when the distance between the vectors is smaller than 0.00001f, but even that might be too pedantic in some cases.

A better check might be to calculate the distance and trigger the condition when it is "close enough", in this example 1/100th of a unit:

```
if (Vector3.Distance(transform.position, other.transform.position) < 0.01f ) {

```

# Answer
> 0 votes
I'm not sure if there is a way to do that which covers all types of colliders, but for circle colliders you can do this:

For each circle collider, you have the object's `position`, then you can add the circle collider's `offset` to get he centre of the resulting circle collider. You can also get the circle collider's `radius` to compare how they overlap.

Let `A` be the position of the first circle collider (`gameObject.position` +`circleCollider.offset`) and `B` the same but for the second circle collider. Let `Ar` be the `radius` (`circleCollider.radius`) of the first circle collider and `Br` the `radius` of the second. Then:

```
// will be true if B is inside A's radius
bool aCollision = distance(A,B) <= Ar;

// will be true if A is inside B's radius
bool bCollision = distance(A,B) <= Br;

// this will be true if either A is inside B's radius, or B is inside A's radius
bool eitherCollision = aCollision || bCollision;

// this will be true if both A is inside B's radius, and B is inside A's
bool bothCollision = aCollision && bCollision;

```

This is a way to manually handle collision, so that you get the desired effect. Keep in mind though that the last line will only be true if `A` and `B` have the same radius, and the distance of each other is exactly that radius. Otherwise they can't both "include" each other at the same time.

Keep in mind this is pseudocode/C#. You would most likely need to replace `distance` with `Vector2.Distance`, or an equivalent in any other language.

I'm not sure what is the desired effect that you want, if you just want to make sure that both colliders simply overlap, without checking their radius or anything else, then @Phillipp's answer is way simpler.

---
Tags: unity
---


# Question
Title: How do I get the number of Steam friends online programmatically?
How can I get the current number of Steam friends online in order to insert it into a script or program? I'm looking to use this value to do something like changing an LED colour or for providing data for a desktop widget etc.

Is this possible? How do I get access to that number?

P.S. I got my idea from here: Xbox Live Traffic Light Notifies You When Friends are Gaming

# Answer
> 7 votes
Steam does not support it, but there is a workaround to get it done programmatically. However, private profiles will *not* work, so you will not be able to see a friend's status, even if they allowed you to see it. The API is *public* and it will only be able to see and parse public profiles.

In short you need to query Steam's web API in a loop:

1. `GetFriendList` \- get all friends of that account
2. For each friend use `GetPlayerSummaries` and the `personastate` in the returned result will include their online status.
3. Save results, repeat, compare.

---
Tags: steam
---


# Question
Title: Why is my Unity camera chasing player script running slow?
I have a camera class, that is suppose to chase my player, which works, but its really really slow. It only has this line of code, which makes sense to me, player moves, camera moves. Any idea of why my game runs slower.

```
void Update()
{
    transform.position= new Vector3(player.transform.position.x, player.transform.position.y, -10);
}

```

# Answer
> 9 votes
I think the reason this is happening is because you are updating the player and the camera in a random order, which may make the camera move first, which wouldn't cause it to move at all, then the player would move, and the next update the camera has to catch up to the player, which causes a lag like appearance.

**Using LateUpdate() on your camera instead of Update() should fix this problem**, as you want to edit the movement of the camera after the player has moved first (creating a chasing camera)

Take a look at the Update Order

# Answer
> 1 votes
When you say "really really slow", what exactly do you mean? Are you running this on a mobile device? On the PC it shouldn't matter. Are you going from like 1000fps to 750fps or something?

Is this showing up in the built-in profiler?

Regardless, one speed optimization you can try, if all else fails, is by caching off your transforms.

The built in unity `.transform` property is quite literally doing `return GetComponent( typeof( Transform ) )` (or its equivalent). Storing off a local variable to both your transform and the player's transform will prevent that lookup every time you call it.

# Answer
> -2 votes
No!

1. You can't choose obj file because Unity will have a very slow camera and etc. Convert them for example with iClone 3DXchange v7.01 Pipeline to fbx only!
2. You must occlusion your camera!
3. Chage size of your texture with Advanced JPEG Compressor.
4. Change your build setting like my picture.

Your camera will be high speed.

---
Tags: unity, camera
---


# Question
Title: How do I spawn trees so that they stick out perpendicular to a 3D planet?
I have a 3D tree that I want to clone so that it is perpendicular to a planet gameobject, so it looks upright when spawned. I tried by copying down all desired rotations of the tree and adding them into a dictionary full of vector3’s so that I can access any one of them when I need to. However, using Quaternion.Euler() doesn’t copy the coordinates exactly when I pass them in; they are always wrong. Below is the code:

```
public void PlaceFauna(GameObject prefab, Vector3 position, Vector3 rotation, GameObject icosphere)
{
    prefab.transform.position = position;       // Moves prefab into scene and sets position
    prefab.transform.rotation = Quaternion.EulerAngles[rotation];   // Sets rotation to that of the one in the dictionary
    GameObject clone = Instantiate(prefab) as GameObject;   // Creates clone
    clone.name = clone.GetInstanceID().ToString();  // Gives clone a unique name
    clone.transform.parent = icosphere.transform;   // Puts clone under region
    prefab.transform.position = new Vector3(0, 0, 40);  // Moves prefab out of scene
}

```

It takes in the position and the rotation from the dictionary and applies .Euler() to the prefab so that the tree (should) match the position. However it does not do this. Where am I going wrong?

# Answer
> 2 votes
I have learnt that using Euler angles to transform a gameobject is the root of my problem as the desired position can be lost through translating between quaternions and Eulers. Since unity uses Quaternions solely and just uses Euler angles for humans to better understand, conversions can often be messed up. I worked around this problem with a different strategy; I calculated a vector between the centre of the planet and the position of the face, and set the tree’s rotation to match this vector:

```
prefab.transform.rotation = Quaternion(FromToRotation(new Vector3(0, 0, 1), position);

```

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


title: Help with 3D Double Jumping in Unity

text:
# Question
Title: Help with 3D Double Jumping in Unity
I'm having some trouble with vertical movement. I'm trying to add double-jumping but none of the scenarios online seem to be working, and I can only ever manage to get a single jump. Here's my code:

```
using UnityEngine;
using System.Collections;

public class Moving : MonoBehaviour {
//public float speed;
CharacterController controller;
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
public bool candoublejump = true;
public int jumptime = 0;
private Vector3 moveDirection = Vector3.zero;
// Use this for initialization
void Start () {
    controller  = GetComponent<CharacterController>();
}

void FixedUpdate() {
    if (controller.isGrounded) {
        moveDirection = new Vector3 (Input.GetAxis ("Horizontal") * 2000, 0, Input.GetAxis ("Vertical") * 2000);
        moveDirection = transform.TransformDirection (moveDirection);
        moveDirection *= speed;
    }
    if (Input.GetButton ("Jump")) {
        if (controller.isGrounded) {
            moveDirection.y = 0;
            moveDirection.y = jumpSpeed;
            candoublejump = true;
        } else {
            if (candoublejump) {
                candoublejump = false;
                moveDirection.y = jumpSpeed;
            }
        }
    }
    moveDirection.y -= gravity * Time.deltaTime;
    controller.Move(moveDirection * Time.deltaTime);
}
}

```

Is there something wrong with my keyboard maybe? My theory is that it's checking for the double jump in the split second after you did the first one, which isn't helpful because you're still holding the jump button.

# Answer
There are two problems here.

First, as you surmised, `GetButton()` asks "is the button currently in the pressed state?" So unless the player manages to tap the button so precisely that it's pressed for exactly one frame, you'll get multiple hits from the button being held down.

To fix this, you can use `GetButtonDown()`, which asks "did the button enter the pressed state *this frame*?"

But there we run into problem number two: you're checking for jump input, which is true for exactly one frame, in `FixedUpdate`, which can be called zero or multiple times per frame. This can lead to missed or double-handled inputs.

I discuss this input timing issue and a way to solve it in this earlier answer. In your case it would look something like this:

```
bool hasHandledInputThisFrame = false;

void HandleInput(bool isFixedUpdate) {
    bool hadAlreadyHandled = hasHandledInputThisFrame;
    hasHandledInputThisFrame = isFixedUpdate;
    if(hadAlreadyHandled)
        return;

    // Handle instantaneous inputs & physics effects exactly once per frame.
    if (Input.GetButton ("Jump")) {
        if (controller.isGrounded) {
            moveDirection.y = 0;
            moveDirection.y = jumpSpeed;
            candoublejump = true;
        } else {
            if (candoublejump) {
                candoublejump = false;
                moveDirection.y = jumpSpeed;
            }
        }
    }
}

void FixedUpdate() {
    HandleInput(true);

    if (controller.isGrounded) {
        var inputDirection = new Vector3 (Input.GetAxis ("Horizontal") * 2000, 0, Input.GetAxis ("Vertical") * 2000);
        var newVelocity = transform.TransformDirection (inputDirection);
        newVelocity *= speed;

        // Preserve vertical velocity due to jump/falling.
        newVelocity.y = moveDirection.y;
        moveDirection = newVelocity;
    }

    moveDirection.y -= gravity * Time.deltaTime;
    controller.Move(moveDirection * Time.deltaTime);
}

void Update() {
    HandleInput(false);
}

```
> 1 votes

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


# Question
Title: Difference between reflection mapping and raytracing
Both methods involve casting a ray unto the reflecting object. It will be reflected. In reflection mapping - the intersection of this reflected ray with the environment map (texture) will yield the result.

Isn't it the same for ray-tracing, though? Or is ray-tracing classified only as ray-tracing if it works with the real 3D geometry in the scene (not pre-computed images).

# Answer
Up until recently, when someone said raytracing, they almost certainly meant rendering the *whole scene* with ray-based techniques. Meaning...

1. For each pixel in the image, we fire a ray from the camera through that point in the image plane
2. We search the scene for where this ray intersects an object, and render a surface there
3. We calculate the colour of the pixel using the material of the struck surface point, modulated by information from additional rays, such as...

* Rays aimed at light sources to detect intersections with occluding objects, to determine illumination / shadow
    * Rays reflected from the hit point to detect intersections with other scene objects and compute their colours to draw specular / mirror-like reflection of other parts of the scene viewed through this surface
    * Rays scattered from the hit point to detect intersections with other scene objects and compute their colours to gather diffuse bounced light (global illumination)

Each of these rays can independently searching our whole scene for new intersections, and evaluate material colours the same way, firing subsequent rays of their own... repeating this rendering process down to some maximum recursion depth, so we get extremely accurate calculation of the light bouncing around the scene even between many unrelated surfaces.

This is in contrast to techniques like reflection mapping, shadow mapping, parallax occlusion mapping, etc, which are tricks we can use to add additional detail and effects to scenes rendered with *rasterization*. In rasterization, we flip the problem: rather than each image pixel searching for the geometry in the scene under it, we take each piece of geometry and compute which pixels it covers:

1. For each vertex in the scene, we project it into image space
2. For each triangle, we compute the image pixels/fragments that fall between these transformed vertices in our image plane
3. For each of these pixels/fragments, we compute the colour by running a shader program that generally has limited information about only the immediate context of this operation.

This is super fast on GPUs, and has historically outperformed raytracing for rendering large complex scenes in realtime. But it has a downside: the information we have at the rasterization/shading stage is usually fairly local to the triangle/fragment we're drawing.

We typically don't have the ability to search the whole scene for arbitrary ray-geometry intersections - so we use approximations. These usually involve looking up some data from a pre-computed texture "map" of the relevant values, which is why you'll often find "mapping" in the names of these techniques.

* Instead of casting a ray toward the light and looking for intersecting occluders, we use a shadow map computed in advance or earlier in the frame to decide whether we're in shadow.
    * Instead of drawing specular reflection by intersecting a reflected ray with the scene and computing the colour of that scene point recursively, we look up a particular pixel from a reflection map (again, either precomputed & baked or updated earlier this frame) to approximate what's *probably* in roughly that direction.

    Although we're computing a reflected ray here, we're not really "tracing" that ray through our scene to find intersections in the same way that a raytracing renderer does. We're just using some similar math to compute a lookup coordinate.

    That said, in some cases we can use raymarching with our depth buffer to get more raytracing-like results.

I say "until recently" because new graphics cards are starting to introduce more options for hybridizing raytracing and rasterization techniques. So now on some GPUs and in some circumstances, you *can* issue ray-geometry intersection searches from pixels of rasterized geometry. It's still costly and needs to be carefully budgeted, but you may find these techniques starting to complement or even displace many of the approximations we've traditionally used in rasterization.
> 2 votes

# Answer
Ray-tracing generally refers to techniques that perform repeated ray-casts with the reflections of a ray through a scene. Changes in the scene will always be present in reflections generated by ray-tracing.

Reflection mapping is effectively the ray tracing method with two optimizations:

* Only one reflection is performed.
* The result is retrieved from an environment map.

Since the environment maps are pre-generated, they do not respond to changes in the scene and this is where reflection mapping majorly differs from ray-tracing.

It is technically possible to retrieve the result from the next surface the ray hits in the scene. If this technique is used it would be considered ray-tracing and still capture some changes in the scene.
> 0 votes

---
Tags: textures, graphics, raycasting, terminology, reflection-rendering
---


title: Steering constantly turning in circles

text:
# Question
Title: Steering constantly turning in circles
I've been working on a fish system in a compute shader but bugs have been drowning me. The latest bug had me strip almost all the functionality to track down:

Fish keep turning in circles. It starts slowly, the fish gains velocity in the proper direction, then it reverses. The fish slowly loses velocity until it does a 180 and then the forward wander then applies acceleration behind it repeating the process. However the reverse isn't exactly 180 degrees behind it. It goes from doing roughly 180 degree instant turns to tracing smooth circles over a period of roughly 10 seconds.

```
float desiredSpeed = 0.2f;
// Wander Behavior substitute
float3 acceleration = (fish.mat._21_22_23 * desiredSpeed  - fish.velocity) * velocityMultiplier;

// Acceleration
float accelMag = length(acceleration);
float3 steerDirection = fish.mat._21_22_23;
if (accelMag > 0)
    steerDirection = acceleration / accelMag;
if (accelMag > desiredAccel)
{
    acceleration = steerDirection * desiredAccel;
    accelMag = desiredAccel;
}

// Direction
if (accelMag > 0)
{
    // Removed rotation smoothing
    fish.mat._21_22_23= normalize(acceleration); // forward
    fish.mat._11_12_13 = normalize(cross(fish.mat._21_22_23, float3(0, 0, 1))); // right
    fish.mat._31_32_33 = normalize(cross(fish.mat._11_12_13, forward)); // up
}

// Velocity
fish.velocity += fish.mat._21_22_23 * accelMag * fishDeltaTime;

speed = length(fish.velocity);
if (speed > desiredSpeed)
{
    fish.velocity = fish.velocity / speed * desiredSpeed;
    speed = desiredSpeed;
}
fish.mat._41_42_43 += fish.velocity * fishDeltaTime;

```

Once the fish is going in circles I understand what is happening. The fish has a velocity off to one side and it calculates the desired velocity as (forward * speed - velocity). That translates to an acceleration added at an angle pointing inwards away from the velocity so the fish continues to turn. You can sort of see it in this picture:

The light gray line is the current velocity, dark blue the desired wander velocity (forward), light blue the wander acceleration that is causes the fish to turn to the left.

My questions are:

Why does the fish slow and start to turn if acceleration is only added in the forward direction?

How do I rewrite the code so that the this sort of situation doesn't happen? Ideally the current velocity would become more forward and the corrective acceleration would lower until it went back to a normal straight line.

# Answer
So it turns out the turn starts because of what I assume is accumulated floating point error from increasing velocity in this line:

```
float3 acceleration = (fish.mat._21_22_23 * desiredSpeed  - fish.velocity) * velocityMultiplier;

```

A small difference in direction causes the fish to turn slightly which is enough to start a positive feedback loop that ends with the fish going in circles.

My current thought is to based the acceleration on the current velocity rather than the current direction:

```
float3 wanderDirection = forward;
if (any(fish.velocity))
    wanderDirection = normalize(fish.velocity);
float3 acceleration = (wanderDirection * desiredSpeed  - fish.velocity) * velocityMultiplier;

```

This makes sense once it is expanded to a wander behavior and I believe it solves most of my problems.
> 0 votes

---
Tags: algorithm, ai, hlsl, steering-behaviors, compute-shader
---


# Question
Title: How can I remove the 'already played' moves from the 'available moves' list?
```
            List<int> boardmove = new List<int>();
            boardmove.Add(0);
            boardmove.Add(1);
            boardmove.Add(2);
            boardmove.Add(3);
            boardmove.Add(4);
            boardmove.Add(5);
            boardmove.Add(6);
            boardmove.Add(7);
            boardmove.Add(8);

            int rand = rnd.Next(1, count);

            int num_one = boardmove[rand];

            boardmove.RemoveAt(num_one);

            count--;

```

I am trying to implement a computer player for my tic tac toe game. I am using a list to move the computer player, I want to index in the list and then remove the value I have selected. I want to select a unique value from the list each time.

```
            List<int> boardmove = new List<int>();
            boardmove.Add(0);
            boardmove.Add(1);
            boardmove.Add(2);
            boardmove.Add(3);
            boardmove.Add(4);
            boardmove.Add(5);
            boardmove.Add(6);
            boardmove.Add(7);
            boardmove.Add(8);

            int selectedIndex = rnd.Next(0, boardmove.Count);

            int selectedMove= boardmove[selectedIndex];
            Console.WriteLine(selectedMove);

            boardmove.RemoveAt(selectedIndex);
            Console.WriteLine(selectedIndex);

```

# Answer
You're close, but you want to make a few small changes:

```
int rand = rnd.Next(1, count);

```

Let's use more descriptive variable names, following camel-casing conventions, and remember that list indexing starts at zero. We don't need a separate count variable because the `List<T>` has one built-in:

```
int selectedIndex = random.Next(0, boardMove.Count);

```

Then

```
int num_one = boardmove[rand];

```

becomes:

```
int selectedMove = boardMove[selectedIndex];

```

And finally, here we're trying to remove from an indexed location, but passing a value from that index instead of the index itself.

```
boardmove.RemoveAt(num_one);

```

We can fix that as either:

```
boardMove.Remove(selectedMove);

```

or (slightly faster)

```
boardMove.RemoveAt(selectedIndex);

```

Just make sure you're matching apples to apples. Methods that want an index should be passed an index. Methods that want a value should be passed a value.

---

Also, make sure you're not running this code back-to-back the way you've shown it here. I assumed you'd just snipped out the relevant bits for brevity, but just in case, you'll want your code to be in at least three parts:

```
// 1. Declare a member variable to hold your list of remaining moves,
//    so it can persist between turns. Prep its capacity to 9 entries.
List<int> boardMove = new List<int>(9);

// 2. Have a dedicated method to put stuff in order when starting a new game.
void StartGame() {
    // Erase any remaining moves left-over from last game.
    boardMove.Clear();

    // Prep the moves list with one of each move.
    for(int i = 0; i < 9; i++)
        boardMove.Add(i);

    // Do other stuff like setting up the board / etc...
}

// 3. Have a function to choose a random move when you need one.
//    This just picks from the existing list, it doesn't make a new one.
int SelectRandomMove() {
    int selectedIndex = random.Next(0, boardMove.Count);
    int selectedMove = boardMove[selectedIndex];
    boardMove.RemoveAt(selectedIndex);
    return selectedMove;
}

```
> 3 votes

# Answer
```
            Random rnd = new Random();

        List<int> boardmove = new List<int>(9);
        for (int i = 1; i < 10; i++)
            boardmove.Add(i);

        while (gameOver==false)
        {
            Console.Write("Enter X spot (1-9): ");
            int num = Convert.ToInt32(Console.ReadLine());

            int selectedIndex = rnd.Next(1, boardmove.Count);

            int selectedMove= boardmove[selectedIndex];
            Console.WriteLine(selectedMove);

            boardmove.RemoveAt(selectedIndex);

```

I have figured out my problem by moving my list initialization before my while loop
> 1 votes

# Answer
```
        Random rnd = new Random();

        List<int> boardmove = new List<int>(9);
        for (int i = 1; i < 10; i++)
            boardmove.Add(i);

        while (gameOver==false)
        {
            Console.Write("Enter X spot (1-9): ");
            int selectedMoveX= Convert.ToInt32(Console.ReadLine());

            int selectedIndex = rnd.Next(1, boardmove.Count);

            int selectedMoveO= boardmove[selectedIndex];

            boardmove.RemoveAt(selectedMoveX);
            boardmove.RemoveAt(selectedIndex);

            switch (selectedMoveX)

```

this code works correctly I am posting so that I can help others. is there anyway I can make the X input more bulletproof.
> 0 votes

---
Tags: c#
---


# Question
Title: How to determine what direction an object should orbit around another
I am creating a game in Unity with 2D. When a button is clicked a static object is attaching a hinge joint to a dynamic object, so the dynamic object orbits it. When the dynamic object gets attached, I am setting the dynamics objects `transform.up` vector to be pointing at the static object. Then, taking what ever the dynamic objects magnitude was and setting that as its velocity to the right. I do this because I want the dynamic object to orbit the planet at the same exact speed as when it wasn't orbiting.

The problem I am having, is I don't know how to determine if the object should orbit clockwise or counter-clockwise. It's easy for me to determine this when I look at an image, but I don't know how to via code.

Here is an example

Does anyone know how I can determine this?

# Answer
> 1 votes
Welcome to the joy of the cross product!

The cross product of two 3D vectors gives a third vector that's perpendicular to both the inputs:

```
Vector3 c = Vector3.Cross(a, b);

```

In a left-handed coordinate system like Unity's, you can make a thumbs-up pose with your left hand, and hold it so that the flat of your hand points in the direction `a` and your fingers curl toward `b`. The cross product of the two points in the direction of your thumb.

That means if `a` and `b` are in the 2D plane `xy`, the cross product points along the `z` axis: with `z` component greater than zero if `b` is clockwise of `a`, and less than zero if `b` is counter-clockwise of `a`.

So, specifically:

```
float OrbitDirection(Rigidbody2D orbiter, Transform center) {
    Vector3 toCenter = center.position - orbiter.position;
    return Mathf.Sign(Vector3.Cross(orbiter.velocity, toCenter).z);
    // This is equivalent to:
    // return Mathf.Sign(orbiter.velocity.x * toCenter.y - orbiter.velocity.y * toCenter.x);
}

```

This returns `+1.0f` if the object should orbit counter-clockwise (positive rotation about the z axis), and `-1.0f` if the object should orbit clockwise (negative rotation about the z axis).

---
Tags: unity, 2d, vector, hinge-joint
---


# Question
Title: OpenGL Texture from Raw Data Not Rendering Correctly
Starting off the class in question is here:

```
using System;

public class FontService
{
    private int[] characterTextures;

    public void InitalizeTextures()
    {
        characterTextures = new int[94];
        var font = new FontFace(File.OpenRead(Path.Combine(Environment.GetFolderPath(
            Environment.SpecialFolder.ApplicationData), @"RyuFs\system\fonts\FontStandard.ttf")));

        for (int i = 33; i < 127; i++)
        {
            var surface = RenderSurface((char)i, font);

            characterTextures[i - 33] = LoadTexture(surface);
        }
    }

    public void DrawText(string text)
    {
        GL.Viewport(0, 0, 500, 500);
        GL.BindTexture(TextureTarget.Texture2D, characterTextures[text[0] - 33]);

        GL.Enable(EnableCap.Blend);
        GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
        GL.Enable(EnableCap.DepthTest);
        GL.DepthFunc(DepthFunction.Lequal);
        GL.Enable(EnableCap.Texture2D);

        GL.ClearDepth(1);
        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        GL.ClearColor(Color.White);

        GL.Begin(PrimitiveType.Triangles);
        GL.Color4(Color.White);

        GL.TexCoord2(0, 0); GL.Vertex2(100, 100);
        GL.TexCoord2(0, 64); GL.Vertex2(100, 164);
        GL.TexCoord2(32, 64); GL.Vertex2(132, 164);

        GL.TexCoord2(32, 64); GL.Vertex2(132, 164);
        GL.TexCoord2(32, 0); GL.Vertex2(132, 100);
        GL.TexCoord2(0, 0); GL.Vertex2(100, 100);
        GL.End();

        GL.BindTexture(TextureTarget.Texture2D, 0);
        GL.Disable(EnableCap.Texture2D);
        GL.Disable(EnableCap.DepthTest);

    }

    public unsafe Surface RenderSurface(char c, FontFace font)
    {
        var glyph = font.GetGlyph(c, 32);
        var surface = new Surface
        {
            Bits = Marshal.AllocHGlobal(glyph.RenderWidth * glyph.RenderHeight),
            Width = glyph.RenderWidth,
            Height = glyph.RenderHeight,
            Pitch = glyph.RenderWidth
        };

        var stuff = (byte*)surface.Bits;
        for (int i = 0; i < surface.Width * surface.Height; i++)
            *stuff++ = 0;

        glyph.RenderTo(surface);

        return surface;
    }

    private unsafe int LoadTexture(Surface surface)
    {
        int width = 32; //surface.Width;
        int height = 64; //surface.Height;
        int len = width * height;
        byte[] data = new byte[len];
        //Marshal.Copy(surface.Bits, data, 0, len);
        int[] pixels = new int[len];

        int index = 0;
        for (int i = 0; i < len; i++)
        {
            int c = (byte)i; //data[i];
            pixels[i] = (byte.MaxValue << 24) | (c << 16) | (c << 8) | c;
        }

        GL.Enable(EnableCap.Texture2D);
        int textureID = GL.GenTexture();
        GL.BindTexture(TextureTarget.Texture2D, textureID);

        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Clamp);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Clamp);

        fixed (int* dataptr = pixels)
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, (IntPtr)dataptr);
        GL.BindTexture(TextureTarget.Texture2D, 0);
        GL.Disable(EnableCap.Texture2D);

        Marshal.FreeHGlobal(surface.Bits); //Give the memory back!
        return textureID;
    }
}

```

Currently I get this output (It's an odd shaped window):

What I expect the code to do is generate rainbow textures with constant Alpha on line 96:

```
int index = 0;
for (int i = 0; i < len; i++)
{
    int c = (byte)i; //data[i];
    pixels[i] = (byte.MaxValue << 24) | (c << 16) | (c << 8) | c;
}

```

After that I expect it to convert the data into a texture on line 113:

```
fixed (int* dataptr = pixels)
    GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, (IntPtr)dataptr);

```

Finally DrawText should render just the first char of the string, 'H' in my example but as it's just got a dummy texture it should render a rainbow square.

I would also like to be able to blend it properly with respect to alpha so 0 alpha is totally transparent and 100% alpha is totally opaque.

Some extra info that may help you, help me:

* Running under .Net Core 2.0
* OpenTK window host
* Using Open GL ES 2.0
* InitalizeTextures is called on GL load
* DrawText is called with help in gldraw. The only other gl calls are a clearcolor to white (prior) and a frame swap (post)
* No shaders are loaded
* Orthographic viewport where 1 pixel = 1 unit

So to sum it all up, what's wrong with my code causing these issues? I know it's messy, I will clean it up on commit :)

Thank you for reading this far and any help would be appreciated.

# Answer
Turns out there are a couple issues with my code: the fact that it doesn't generate a rainbow box but a grey gradient as user1118321 said in a comment; the wrong pixel type, byte, not uint8888; and probably more.

But the real issue was the texture coordinates. I failed to realize they are always from (0,0) to (1,1) and not the size of the of the texture as I had been using them. Anyway with that done it's all fixed. I don't have the code as I ended up completely rewriting it for its actual use.
> 2 votes

---
Tags: c#, textures, opengl-es2, opentk
---


# Question
Title: Unity Checkpoint System that remembers NPC interactions + Environment changes?
I have already implemented a checkpoint system that respawns the player at the last checkpoint they cross through. Now imagine this:

* NPC A interacts with NPC B
* NPC B walks over to a nearby car
* A bird flies over the car and takes a dump
* Player dies tragically (lol)
* Player respawns at the last checkpoint X

Given that checkpoint X is achieved after watching all these NPC interactions, how can I fast forward/skip these interactions when respawning the player? The build I have right now respawned at the correct location but of course, the NPC interactions happen again even though they were supposed to end before reaching that last checkpoint (if that makes any sense )

I understand that this can be achieved by saving all the last known locations of the NPCs, flags that indicate whether the bird took a dump (true/false). For example, this seems quite tedious for a game like Uncharted/GTA where a lot of interactions happen at the same time.

My initial thought was to somehow fast forward the entire game to a point where all these interactions are done and dusted. That way, I can safely respawn the player knowing that they don’t see something they’ve already seen.

Sorry for the detailed post Any tips on how this can be accomplished?

# Answer
Look at the overall game in itself first. I recently played Hitman so I will try and use how I would make the NPCs work.

The game will be bigger than a single complex scene, thus all GameObjects (plus NPCs) will have to page in and out depending on their visibility. As the bird is paged out, it must be able to save its state and restore that state when it pages back into the scene.

Now on to how to save this data. Come up with or get one, a collection of data (a database). and structure it such that objects can fetch and store/update their records without having to read the entire database or parse all of it into memory. Also as fore-sight, make it so that you can fit the entire game world state into the memory as a database. The technical design is up to you but SQLite is one option.

All gameobjects report to the game's state manager and when they get paged in, they just restore their state from the database. When they go out of camera view enough to get paged, they save their state to the database. Be sure to deregister a paged-out object from the state manager too. The state manager should be designed such that can send a command to alo objects in the scene and tell them to save their state and that's how you save your entire game.

You should consider putting in place a quest tracker for objects in the game. Your gameobjects must then have some sort of looped or single quest status. If the bird poops once and doesnt need to do it again, then if it has pooped, its quest state is saved to the database. When the game tries to page it back in or reload it, the bird refuses because it's completed its quest. If it poops then goes to eat again, simply save the last state, for example eating, before it gets pajed out. When the bird is re-loaded back in or paged in, it knows it was eating and now, it should go and poop. It'll loop until it gets paged out again and the cycle repeats.

Now, when you save the entire game, the game state manager tells all in-scene objects to save their state to the database. When reloading the game you simply parse this info from however you had saved it. The technical structure is trivial, as long as it is fast and a sort of random access system.

When you reload the scene you start with global fixed gameobjects designed to keep track of which place the player was in when the game was saved. The fixed gameobject will then load that zone, position the player in it, and load in all the gameobjects that were there at the time of saving. When the gameobjects are added to the zone, they start to query their state from the database and those that need to be displayed, get displayed. those that have a completed quest status, don't need to process further.

You'll use flags that you decide on for the gameobjects. I use static strings and ints.

Get to work!
> 1 votes

---
Tags: unity, savegame
---


# Question
Title: How to delete Unity Hybrid ECS Entities?
I'm trying to get into Unity's Hybrid ECS feature. Creating and Manipulating Entities has worked fine so far for me, but somehow I can't find a viable option to delete Entities which works 100% of the time without errors.

I know about object pooling, however in this particular case there is no way around deleting Entities.

Thank you in advance!

# Answer
Coming from an Entitas background here, i usually:

1. Create a component called Destroy.
2. at the end of the execution cycle i have a Cleanup System that reacts for entities that have the Destroy component and Destroy them, i also check if they have a View component so i can destroy the attached GameObject. usually Entitas does the magic with pooling.

```
public class EntityDestroySystem: ICleanupSystem
{
    private Contexts _contexts;

    private IGroup<RenderEntity> _renderGroup;
    private IGroup<GameEntity> _gameGroup;

    public EntityDisposeSystem(Contexts contexts)
    {
        _contexts = contexts;

        _renderGroup = _contexts.render.GetGroup(RenderMatcher.AllOf(RenderMatcher.Destroy));
        _gameGroup= _contexts.game.GetGroup(GameMatcher.AllOf(GameMatcher.Destroy));
    }

    public void Cleanup()
    {
        foreach (var e in _renderGroup.GetEntities())
        {

            e.Destroy();
        }

        foreach (var e in _gameGroup.GetEntities())
        {
            e.Destroy();
        }
    }
}

```
> 1 votes

---
Tags: unity, entity-system, entity, entity-component-system
---


title: DirectX11 program bug full screen

text:
# Question
Title: DirectX11 program bug full screen
I have a problem switching the engine from full screen to normal. I use alt + enter. The problem is this: when I start the engine in full screen and press alt + enter - it hangs. For mode of the screen corresponds to the flag *modeScreen*. Below there is a video showing the work:

youtube.com

This link has a minimal example. First, start in normal mode and switch, and everything works well. Then start up in full screen and when switching the problem.

As you can see, when you start in full screen and try to change the screen mode, it hangs. How to overcome it?

The minimal complete verifiable example:

```
// headers
#include <windows.h>

#include <d3d11.h>

#include <string>

// libraries
#pragma comment(lib, "d3d11.lib")

// global variable
IDXGISwapChain* swapChain(nullptr);
ID3D11Device* device(nullptr);
ID3D11DeviceContext* deviceContext(nullptr);
ID3D11RenderTargetView* backBuffer(nullptr);
ID3D11Texture2D* DepthStancil(nullptr);
ID3D11DepthStencilView* DepthStancilBuffer(nullptr);
ID3D11RasterizerState* rasterizer(nullptr);

D3D11_TEXTURE2D_DESC descDepth;
D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
D3D11_VIEWPORT vp;

// governors variable
int height(1080); // h window
int width(1920); // w window
bool modeScreen(false); // mode screen(true - full screen, false - windowed mode)

// constants windows message
#define WM_RENDER WM_USER + 1001

// functions
LRESULT WINAPI WndProc(HWND, UINT, WPARAM, LPARAM);
void createDescsTarget(int w, int h);
bool createTargetRender(int w, int h);
bool renderStateEdit(const D3D11_FILL_MODE& fm);
bool resizeWindow(SIZE p);
void renderEditor();

// main
int WINAPI WinMain(HINSTANCE hInst,
    HINSTANCE hPrev,
    LPSTR szCmdLine,
    int nShowCmd)
{
    WNDCLASSEX wcx = {0};
    wcx.cbSize = sizeof(WNDCLASSEX);
    wcx.style = CS_HREDRAW | CS_VREDRAW;
    wcx.lpfnWndProc = WndProc;
    wcx.hInstance = hInst;
    wcx.lpszClassName = TEXT("Win32 DirectX");

    if ( !RegisterClassEx(&wcx) )
        return 1;
    HWND hWnd = CreateWindowEx(0,
        TEXT("Win32 DirectX"),
        TEXT("Test going to full screen DirectX programm"),
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT,0,
        width,height,
        0,
        0,
        hInst,
        0);

    if (!hWnd)
        return 2;

    // init dx
    DXGI_SWAP_CHAIN_DESC sdesc;
    ZeroMemory(&sdesc, sizeof(sdesc));
    sdesc.BufferCount = 1;
    sdesc.OutputWindow = hWnd;
    sdesc.SampleDesc.Count = 4;
    sdesc.SampleDesc.Quality = 0;
    sdesc.Windowed = true;
    sdesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
    sdesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sdesc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
    sdesc.BufferDesc.Height = height;
    sdesc.BufferDesc.Width = width;

    D3D_FEATURE_LEVEL levels[] = {
        D3D_FEATURE_LEVEL_12_0,
        D3D_FEATURE_LEVEL_11_1,
        D3D_FEATURE_LEVEL_11_0,
        D3D_FEATURE_LEVEL_10_1,
        D3D_FEATURE_LEVEL_10_0,
        D3D_FEATURE_LEVEL_9_3,
        D3D_FEATURE_LEVEL_9_2,
        D3D_FEATURE_LEVEL_9_1
};

    UINT flags(NULL);
#ifdef DEBUG
    flags = D3D11_CREATE_DEVICE_DEBUG;
#endif
    flags |= D3D11_CREATE_DEVICE_DISABLE_GPU_TIMEOUT;
    HRESULT hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE,
        NULL, flags, levels, 8, D3D11_SDK_VERSION, &sdesc,
        &swapChain, &device, NULL, &deviceContext);
    if (hr != S_OK)
        return 2;

    createDescsTarget(width, height);
    if (!createTargetRender(width, height))
        return 2;
    if (!renderStateEdit(D3D11_FILL_MODE::D3D11_FILL_SOLID))
        return 2;

    hr = swapChain->SetFullscreenState(modeScreen, nullptr);
    if (hr != S_OK)
        return 2;

    ShowWindow(hWnd, nShowCmd);
    UpdateWindow(hWnd);
    MSG msg;
    while (true)
    {
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        if (msg.message == WM_QUIT)
            break;
        else
            SendMessage(hWnd, WM_RENDER, NULL, NULL);
    }
    return( (int)msg.wParam );
}

LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg) {
    case WM_DESTROY:
        PostQuitMessage(0);
        break;

    case WM_SIZE:
    {
        SIZE p;
        p.cx = LOWORD(lParam);
        p.cy = HIWORD(lParam);
        if (p.cx == 0 || p.cy == 0)
        {
            PostMessage(hWnd, WM_QUIT, NULL, NULL);
            break;
        }
        if (!resizeWindow(p))
            PostMessage(hWnd, WM_QUIT, NULL, NULL);
        SendMessage(hWnd, WM_RENDER, NULL, NULL);
        break;
    }

    case WM_RENDER:
        renderEditor();
        break;

    }
    return DefWindowProc(hWnd, msg, wParam, lParam);
}

void createDescsTarget(int w, int h)
{
    ZeroMemory(&descDepth, sizeof(descDepth));
    descDepth.Width = w;
    descDepth.Height = h;
    descDepth.MipLevels = 1;
    descDepth.ArraySize = 1;
    descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    descDepth.SampleDesc.Count = 4;
    descDepth.SampleDesc.Quality = 0;
    descDepth.Usage = D3D11_USAGE_DEFAULT;
    descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    descDepth.CPUAccessFlags = 0;
    descDepth.MiscFlags = 0;

    ZeroMemory(&descDSV, sizeof(descDSV));
    descDSV.Format = descDepth.Format;
    descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
    descDSV.Texture2D.MipSlice = 0;

    vp.Width = (float)w;
    vp.Height = (float)h;
    vp.MinDepth = 0.0f;
    vp.MaxDepth = 1.0f;
    vp.TopLeftX = 0;
    vp.TopLeftY = 0;
}

bool createTargetRender(int w, int h)
{
    ID3D11Texture2D* texture(nullptr);
    HRESULT hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&texture);
    hr = device->CreateRenderTargetView(texture, NULL, &backBuffer);
    if (hr != S_OK)
        return false;
    texture->Release();

    if (DepthStancil)
        DepthStancil->Release();
    if (DepthStancilBuffer)
        DepthStancilBuffer->Release();

    hr = device->CreateTexture2D(&descDepth, NULL, &DepthStancil);
    if (hr != S_OK)
        return false;
    hr = device->CreateDepthStencilView(DepthStancil, &descDSV, &DepthStancilBuffer);
    if (hr != S_OK)
        return false;

    deviceContext->OMSetRenderTargets(1, &backBuffer, DepthStancilBuffer);
    deviceContext->RSSetViewports(1, &vp);

    return true;
}

bool renderStateEdit(const D3D11_FILL_MODE& fm)
{
    if (rasterizer)
        rasterizer->Release();
    D3D11_RASTERIZER_DESC wfd;
    ZeroMemory(&wfd, sizeof wfd);
    wfd.FillMode = fm;
    wfd.CullMode = D3D11_CULL_BACK;
    wfd.DepthClipEnable = true;
    HRESULT hr = device->CreateRasterizerState(&wfd, &rasterizer);
    if (hr != S_OK)
        return false;
    return true;
}

bool resizeWindow(SIZE p)
{
    HRESULT hr(S_OK);

    int w = p.cx;
    int h = p.cy;

    width = w;
    height = h;

    descDepth.Width = w;
    descDepth.Height = h;
    vp.Width = (float)w;
    vp.Height = (float)h;

    deviceContext->OMSetRenderTargets(0, 0, 0);
    backBuffer->Release();

    hr = swapChain->ResizeBuffers(0, p.cx, p.cy, DXGI_FORMAT_UNKNOWN, 0);
    if (hr != S_OK)
        return false;
    createTargetRender(w, h);
    return true;
}

void renderEditor()
{
    float color[] = { 0.36f, 0.36f, 0.36f, 1.0f };
    deviceContext->ClearDepthStencilView(DepthStancilBuffer, D3D11_CLEAR_DEPTH, 1.0f, 0);
    deviceContext->ClearRenderTargetView(backBuffer, color);

    swapChain->Present(0, 0);
}

```

P.S .: I also try to change the application using alt + tab. However, if the application is running in full screen, then it goes out of it. Why is that? And how to fix it? Thank.

P.S.S .: Sorry for my bad English ...

# Answer
> 0 votes
I solved this problem. I present the code and a small ReadMe.

**Code:**

```
// headers
#include <windows.h>

#include <d3d11.h>

#include <string>

// libraries
#pragma comment(lib, "d3d11.lib")

// global variable
// dx
IDXGISwapChain* swapChain(nullptr);
ID3D11Device* device(nullptr);
ID3D11DeviceContext* deviceContext(nullptr);
ID3D11RenderTargetView* backBuffer(nullptr);
ID3D11Texture2D* DepthStancil(nullptr);
ID3D11DepthStencilView* DepthStancilBuffer(nullptr);
ID3D11RasterizerState* rasterizer(nullptr);
D3D11_TEXTURE2D_DESC descDepth;
D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
D3D11_VIEWPORT vp;

// winapi
HWND hWnd;
HHOOK ExistingKeyboardProc;
HINSTANCE hInstance;
std::wstring className(L"Win32 DirectX");
WINDOWPLACEMENT fullscreenPlacement = { 0 };
WINDOWPLACEMENT windowedPlacement = { 0 };

// auxiliary
bool isRender(false);

// governors variable
int height(600); // h window
int width(800); // w window
bool modeScreen(false); // mode screen(true - full screen, false - windowed mode)
bool enabelAltEnter(false); // enable mode alt + enter?(true - enable)

// constants windows message
#define WM_RENDER WM_USER + 1001

// functions
LRESULT WINAPI wndProc(HWND, UINT, WPARAM, LPARAM);
void createDescsTarget();
bool createTargetRender();
bool renderStateEdit(const D3D11_FILL_MODE& fm);
int resizeWindow(SIZE p);
void renderEditor();
bool initDirectX();
bool hookKeyboardProc(HINSTANCE hinst);
LRESULT CALLBACK keyboardProcLowLevel(int nCode, WPARAM wParam, LPARAM lParam);
int unHookKeyboardProc();
void clear();

// main
int WINAPI WinMain(HINSTANCE hInst,
    HINSTANCE hPrev,
    LPSTR szCmdLine,
    int nShowCmd)
{
    hInstance = hInst;
    hookKeyboardProc(hInstance); // set keyboard hook

    WNDCLASSEX wcx = {0};
    wcx.cbSize = sizeof(WNDCLASSEX);
    wcx.style = CS_HREDRAW | CS_VREDRAW;
    wcx.lpfnWndProc = wndProc;
    wcx.hInstance = hInstance;
    wcx.lpszClassName = (LPCSTR)className.c_str();

    if ( !RegisterClassEx(&wcx) )
        return 1;
    hWnd = CreateWindowEx(0,
        (LPCSTR)className.c_str(),
        TEXT("Test going to full screen DirectX programm"),
        WS_OVERLAPPEDWINDOW,
        300,300,
        width,height,
        0,
        0,
        hInstance,
        0);

    if (!hWnd)
        return 2;

    ShowWindow(hWnd, nShowCmd);

    if (!initDirectX())
        return 2;

    MSG msg;
    while (true)
    {
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        if (msg.message == WM_QUIT)
            break;
        else
            SendMessage(hWnd, WM_RENDER, NULL, NULL);
    }

    clear();

    return( (int)msg.wParam );
}

// realisation all function's
LRESULT WINAPI wndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg) {
    case WM_DESTROY:
        PostQuitMessage(0);
        break;

    case WM_SIZE:
    {
        SIZE p;
        p.cx = LOWORD(lParam);
        p.cy = HIWORD(lParam);
        std::string out = "size screen: " + std::to_string(p.cx) + ", " + std::to_string(p.cy) + "\n";
        OutputDebugStringA(out.c_str());
        if (resizeWindow(p) == -1)
            PostMessage(hWnd, WM_QUIT, NULL, NULL);
        break;
    }

    case WM_RENDER:
        renderEditor();
        break;

    case WM_KEYDOWN:
        switch (wParam)
        {
        case VK_HOME:
            {
                modeScreen = modeScreen ? false : true;
                if (modeScreen)
                {
                    windowedPlacement.length = sizeof(WINDOWPLACEMENT);
                    GetWindowPlacement(hWnd, &windowedPlacement);
                }
                HRESULT hr = swapChain->SetFullscreenState(modeScreen, nullptr);
                if (hr != S_OK)
                    PostMessage(hWnd, WM_QUIT, NULL, NULL);
                if(!modeScreen)
                    SetWindowPlacement(hWnd, &windowedPlacement);
                break;
            }

        case VK_ESCAPE:
            PostMessage(hWnd, WM_QUIT, NULL, NULL);
            break;

        default:
            break;
        }
        break;

    case WM_ACTIVATE:
        if (modeScreen && IsIconic(hWnd) && WA_ACTIVE == LOWORD(wParam))
        {
            isRender = true;
            SetWindowPlacement(hWnd, &fullscreenPlacement);
            swapChain->SetFullscreenState(true, nullptr);
        }
        break;

    default:
        break;

    }
    return DefWindowProc(hWnd, msg, wParam, lParam);
}

bool initDirectX()
{
    // init dx
    DXGI_SWAP_CHAIN_DESC sdesc;
    ZeroMemory(&sdesc, sizeof(sdesc));
    sdesc.BufferCount = 1;
    sdesc.OutputWindow = hWnd;
    sdesc.SampleDesc.Count = 4;
    sdesc.SampleDesc.Quality = 0;
    sdesc.Windowed = true;
    sdesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
    sdesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sdesc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
    sdesc.BufferDesc.Height = height;
    sdesc.BufferDesc.Width = width;

    D3D_FEATURE_LEVEL levels[] = {
        D3D_FEATURE_LEVEL_12_0,
        D3D_FEATURE_LEVEL_11_1,
        D3D_FEATURE_LEVEL_11_0,
        D3D_FEATURE_LEVEL_10_1,
        D3D_FEATURE_LEVEL_10_0,
        D3D_FEATURE_LEVEL_9_3,
        D3D_FEATURE_LEVEL_9_2,
        D3D_FEATURE_LEVEL_9_1
    };

    UINT flags(NULL);
#ifdef DEBUG
    flags = D3D11_CREATE_DEVICE_DEBUG;
#endif
    flags |= D3D11_CREATE_DEVICE_DISABLE_GPU_TIMEOUT;
    HRESULT hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE,
        NULL, flags, levels, 8, D3D11_SDK_VERSION, &sdesc,
        &swapChain, &device, NULL, &deviceContext);
    if (hr != S_OK)
        return false;

    if (!enabelAltEnter) // disable mode alt + enter
    {
        IDXGIDevice * pDXGIDevice;
        HRESULT hr = device->QueryInterface(__uuidof(IDXGIDevice), (void **)&pDXGIDevice);
        if (hr != S_OK)
            return false;

        IDXGIAdapter * pDXGIAdapter;
        hr = pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void **)&pDXGIAdapter);
        if (hr != S_OK)
            return false;

        IDXGIFactory * pIDXGIFactory;
        hr = pDXGIAdapter->GetParent(__uuidof(IDXGIFactory), (void **)&pIDXGIFactory);
        if (hr != S_OK)
            return false;

        hr = pIDXGIFactory->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER);
        if (hr != S_OK)
            return false;
    }

    isRender = true;

    if (resizeWindow({ width, height }) == -1)
        return false;
    if (!renderStateEdit(D3D11_FILL_MODE::D3D11_FILL_SOLID))
        return false;

    hr = swapChain->SetFullscreenState(modeScreen, nullptr);
    if (hr != S_OK)
        return false;

    return true;
}

bool hookKeyboardProc(HINSTANCE hinst)
{
    ExistingKeyboardProc = SetWindowsHookEx(
        WH_KEYBOARD_LL,
        keyboardProcLowLevel,
        hinst,
        NULL);

    if (!ExistingKeyboardProc)
        return false;
    else
        return true;
}

LRESULT CALLBACK keyboardProcLowLevel(int nCode, WPARAM wParam, LPARAM lParam)
{
    KBDLLHOOKSTRUCT * hookstruct = (KBDLLHOOKSTRUCT *)(lParam);

    switch (wParam)
    {
    case WM_KEYDOWN:
        break;
    case WM_SYSKEYDOWN:
        if ((((hookstruct->flags) >> 5) & 1))
        {
            // ALT +
            switch (hookstruct->vkCode)
            {
            case VK_TAB: // ALT+TAB
            {
                if (modeScreen && !IsIconic(hWnd))
                {
                    isRender = false;
                    fullscreenPlacement.length = sizeof(WINDOWPLACEMENT);
                    GetWindowPlacement(hWnd, &fullscreenPlacement);
                    ShowWindow(hWnd, SW_SHOWMINNOACTIVE);
                    swapChain->SetFullscreenState(false, nullptr);
                }
            }
            break;
            case VK_RETURN: // ALT+ENTER
                break;
            case VK_ESCAPE: // ALT+ESC
                break;
            case VK_DELETE: // ALT+DEL
                break;
            };
        }
        break;
    case WM_KEYUP:
        break;
    case WM_SYSKEYUP:
        break;
    }

    return CallNextHookEx(ExistingKeyboardProc, nCode, wParam, lParam);
}

int unHookKeyboardProc()
{
    if (ExistingKeyboardProc)
    {
        BOOL retcode = UnhookWindowsHookEx((HHOOK)keyboardProcLowLevel);

        if (retcode)
        {
            // Successfully
        }
        else
        {
            //Error
        }
        return retcode;
    }
    else
    {
        //Error
        return -1;
    }
}

void createDescsTarget()
{
    ZeroMemory(&descDepth, sizeof(descDepth));
    descDepth.Width = width;
    descDepth.Height = height;
    descDepth.MipLevels = 1;
    descDepth.ArraySize = 1;
    descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    descDepth.SampleDesc.Count = 4;
    descDepth.SampleDesc.Quality = 0;
    descDepth.Usage = D3D11_USAGE_DEFAULT;
    descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    descDepth.CPUAccessFlags = 0;
    descDepth.MiscFlags = 0;

    ZeroMemory(&descDSV, sizeof(descDSV));
    descDSV.Format = descDepth.Format;
    descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
    descDSV.Texture2D.MipSlice = 0;

    vp.Width = (float)width;
    vp.Height = (float)height;
    vp.MinDepth = 0.0f;
    vp.MaxDepth = 1.0f;
    vp.TopLeftX = 0;
    vp.TopLeftY = 0;
}

bool createTargetRender()
{
    if (backBuffer)
        backBuffer->Release();
    if (DepthStancil)
        DepthStancil->Release();
    if (DepthStancilBuffer)
        DepthStancilBuffer->Release();

    HRESULT hr = swapChain->ResizeBuffers(0, 0,0, DXGI_FORMAT_UNKNOWN, 0);
    if (hr != S_OK)
        return false;

    ID3D11Texture2D* texture(nullptr);
    hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&texture);
    hr = device->CreateRenderTargetView(texture, NULL, &backBuffer);
    if (hr != S_OK)
        return false;
    texture->Release();

    createDescsTarget();

    hr = device->CreateTexture2D(&descDepth, NULL, &DepthStancil);
    if (hr != S_OK)
        return false;
    hr = device->CreateDepthStencilView(DepthStancil, &descDSV, &DepthStancilBuffer);
    if (hr != S_OK)
        return false;

    deviceContext->OMSetRenderTargets(1, &backBuffer, DepthStancilBuffer);
    deviceContext->RSSetViewports(1, &vp);

    return true;
}

bool renderStateEdit(const D3D11_FILL_MODE& fm)
{
    if (rasterizer)
        rasterizer->Release();
    D3D11_RASTERIZER_DESC wfd;
    ZeroMemory(&wfd, sizeof wfd);
    wfd.FillMode = fm;
    wfd.CullMode = D3D11_CULL_BACK;
    wfd.DepthClipEnable = true;
    HRESULT hr = device->CreateRasterizerState(&wfd, &rasterizer);
    if (hr != S_OK)
        return false;
    return true;
}

int resizeWindow(SIZE p)
{
    if (!isRender)
        return 0;
    if (IsIconic(hWnd))
        return 0;

    width = p.cx;
    height = p.cy;
    if (!createTargetRender())
        return -1;
    SendMessage(hWnd, WM_RENDER, NULL, NULL);
    return 1;
}

void renderEditor()
{
    float color[] = { 0.36f, 0.36f, 0.36f, 1.0f };
    deviceContext->ClearDepthStencilView(DepthStancilBuffer, D3D11_CLEAR_DEPTH, 1.0f, 0);
    deviceContext->ClearRenderTargetView(backBuffer, color);

    swapChain->Present(0, 0);
}

void clear()
{
    if (swapChain)
        swapChain->Release();
    if (device)
        device->Release();
    if (deviceContext)
        deviceContext->Release();
    if (backBuffer)
        backBuffer->Release();
    if (DepthStancil)
        DepthStancil->Release();
    if (DepthStancilBuffer)
        DepthStancilBuffer->Release();
    if (rasterizer)
        rasterizer->Release();
    DestroyWindow(hWnd);
    UnregisterClass((LPCSTR)className.c_str(), hInstance);
}

```

**ReadMe:**

Keys:

* Escape key - exit
* Home key - change screen mode

Flags:

* modeScreen flag - true, run in full screen mode; false, run in windowed mode
* the enabelAltEnter flag is true, the alt + enter combination works and switches the screen modes; false - the combination does not work

Release:

* Minimize and Restore by Alt + Tab
* Block alt + enter
* Minimization and correct recovery
* Resizing window mode

Solution: I had to call the function *ShowWindow(hWnd, nShowCmd)* Before initializing DIrectX. And the alt + tab combination is made using hooks. I used C - style, but only for an example. Make classes is not difficult.

---
Tags: directx, directx11, fullscreen, dxgi
---


# Question
Title: How to determine polygon based on point lists?
I have several lists of interconnected points. They are ordered so I can connect them together. Using these interconnected points I'd like to find the different points and intersection points that form a polygon. I imagine it's something often done in video game but I struggle to find a clear explanation.

Thanks for your help and guidance.

Original point set:

After having connected the points:

Desired polygon to find:

# Answer
A possible solution is to cull points that you are certain that are not part of the polygon.

Start with a definition of the polylines:

```
List<point> polyline = new List<point>(); //I use a list versus array so
                                          //it is easier to insert/remove
                                          //points later.

polyline[0] = {P00, P01} //Red
polyline[1] = {P10, P11, P12} //Green
polyline[2] = {P20, P21, P22, P23} //Blue

```

Next, find the intersection points (a linesegment-linesegment intersection loop). Insert the found point in these polylines.

This results in:

```
polyline[0] = {P00, X02, X01, P01} //Red
polyline[1] = {P10, X03, P11, X01, P12} //Green
polyline[2] = {P20, X02, P21, P22, X03, P23} //Blue

```

If a polyline has no intersections, it is either completely outside of the polygon or completely inside the polygon. These lines may be removed.

Also if a polyline has only *one* intersection, one endpoint is inside the polygon and the other endpoint outside the polygon. Such line can also be removed. Keep in mind there may be an edge case where an intersection and a polyline vertex overlap.

You should now have a set of polylined that share part of the polygon.

Now cull the *endpoints* of the polylines if they do not share a common point (so if the point exists in another polyline it is also a polygon vertex. Repeat until the endpoints of the polylines are shared points.

This results in points bound by the polygon.

```
polyline[0] = {X02, X01} //Red
polyline[1] = {X03, P11, X01} //Green
polyline[2] = {X02, P21, P22, X03} //Blue

```

Using the shared endpoints you can reconstruct the polygon. You may need to reorder the polyline (example; righthand endpoint X01 of the Red line is connected to the righthand endpoint X01 of the green polygon, so you need to reverse the green line).

```
polygon = {X02, X01, P11, X03, P22, P21, X02}

```

Again it might be required to reverse the polygon to keep clockwise notation.

A few points to note:

* Polylines can have shared endpoints to begin with (in the Green and Blue lines P10 could be the same as P23).
* If multiple polygons are possible (P20 lies below line P11-P12) it will work, but the result may not be what you are looking for.
* Keep rounding and floating point errors in mind when checking if a point is equal to another point. Prevent calculating the same intersection twice.
> 5 votes

---
Tags: mathematics, geometry, point-cloud
---


title: Sprite brighter than texture

text:
# Question
Title: Sprite brighter than texture
I have imported a new texture into UE, and have created a new sprite. I have setup the material of the sprite as follows:

I have also set my texture as texture-parameter. But my sprite renders brighter than its texture:

Why? What am I doing wrong?

Thank you in advance.

# Answer
> 2 votes
Check the camera and light settings. The default camera uses eye adaptation to make everything in dark scene gradually brighter.

# Answer
> 0 votes
Try checking the sRGB checkbox and maybe change the compression settings. You could also try changing the brightness and brightness curve values.

---
Tags: textures, graphics, unreal-4, unreal, materials
---


# Question
Title: low FPS when battery is low ( unity android )
i make a **simple** 2d scene in unity 2017.3.1f1 (only 5 sprite renderer). I realized that when my **Android** device's battery is under **20 %**, the frame rate will be 60 to 30. I did all the **optimizations** I heard, like:

DynamicBatching, Sprite Atlas , Quality Setting , sprite Texture Comprestion Override for Android And I emphasize that my scene contains only 5 **sprite** (one background and several buttons)

i use Application.targetFrameRate = 60; because if don't , all time The motions are stuttering Whether the battery is over 20% or not.

And when the vsync is off, the frame is locked to 30 and when it's turned on, it changes for about half a second between 30 and 60

according to profiler (on my android device) Gfx.WaitForPresent start growing!!! (if you want to say it is **GPU bound** , i think render time don't grow And scence is very simple)

In all these modes, The motions are **stuttering**.

I tested two kinds of moves

1: Moving camera in the update method by the following code:

```
void Update () {
    if(startMvCm){
        if (cam.position.y > EndCm ) {
            cam.Translate(0f,(speedCm*Time.fixedDeltaTime),0);
        } else {
            cam.position = new Vector2(0,EndCm);
            startMvCm = false;
        }
    }
}

```

2: An animation of moving an image in canvas (simple UI menu with 5 button) using Animator.

And this low **FPS** see more in **low Battery** on my Huawei Mate 10 Lite

# Answer
It's likely this is an issue largely outside of your control.

If it is true that the only variable in your tests is your phone's battery percentage, then this is almost certainly the result of your phone trying to throttle itself to conserve battery or (indirectly) to say within a certain thermal profile (depending on how you are *getting* the phone to 20% battery).

The Android PowerManager API has methods to tell if your application is on the whitelist for ignoring battery optimizations, and suggests how you can prompt the user to put your application on that whitelist. It's not something you can do unilaterally, however. You will have to ask the user for permission because the user is in control of the device. Google also has requirements about what is and isn't considered an appropriate request. And unfortunately I don't see that this is directly exposed through to the Unity API, you may have to write some sort of plugin or whatnot, as this user did for iOS.

Furthermore, nothing you can do is really going to stop the OS or hardware from throttling your CPU or GPU down if it thinks it needs do, e.g., due to thermal conditions.
> 2 votes

---
Tags: unity, android, optimization, frame-rate, profiler
---


# Question
Title: How would I prevent parts of my player model from displaying on the camera?
The "legs" of my playermodel are shown when looking down. I'm using the Unity First Person Controller template.

Character when in Scene view:

Character when looking down in Play mode:

# Answer
> 0 votes
You can use Layers to control what's visible to each camera.

First, create a layer for "FirstPersonHidden" objects, following the instructions in the docs.

For each object you want to hide, set its layer to this one using the **Layer** drop-down menu at the top-right of the Inspector.

Then, on your camera, open up the **Culling Mask** drop-down and ensure this layer is unchecked.

Now the marked objects will be hidden from your camera's view.

---
Tags: unity, c#, first-person-shooter
---


# Question
Title: Unity: How do I get the coordinates of the vertices of a blender mesh?
I have gameobjects in my scene called icospheres that I have made in Blender, and I am trying to get the coordinates of their vertices. Below is an image of my scene; each triangle is a separate gameobject, blender mesh and is called an icosphere:

Here is the code I am using:

```
    var meshFilter = icosphere.GetComponent<MeshFilter>();
    var vertices = meshFilter.mesh.vertices;
    GameObject.Find("Fauna Manager").GetComponent<FaunaManager>().PlaceFauna(tree, vertices[0], icosphere);
    GameObject.Find("Fauna Manager").GetComponent<FaunaManager>().PlaceFauna(tree, vertices[1], icosphere);
    GameObject.Find("Fauna Manager").GetComponent<FaunaManager>().PlaceFauna(tree, vertices[2], icosphere);

```

The bottom 3 lines of code call a function that should in theory place another gameobject on top of the 3 coordinates that have been calculated above, however this does not happen. The tree-placing functions work completely and have been tested so the problem is definitely with the coordinates. I printed out the coordinates and the length of the array that holds them. The array is of length 3 as it should be however the coordinates are completely off. The trees have been placed a long way away from the icosphere which means the coordinates are clearly wrong. Where have I gone wrong?

```
example of coordinates: -0.1, 0.0, -0.1
centre of icosphere for reference: -0.7431812, 0.4044746, -4.932096

```

Above you can see that the coordinates are well off

# Answer
It looks like you might not be transforming the vertices by the transformation of the object in the scene.

```
Vector3 worldPoint = icosphere.transform.TransformPoint(localPoint);

```

The vertices of a mesh are stored in object-local space. So you need to transform them through to world space if you want objects under a different parent to line up.

Alternatively, you can parent your trees to the mesh object and set their `localPosition` instead.
> 1 votes

---
Tags: unity, blender, coordinates
---


title: Raycaster calculation question

text:
# Question
Title: Raycaster calculation question
I am following this tutorial https://lodev.org/cgtutor/raycasting.html

> When deriving deltaDistX geometrically you get, with Pythagoras, the formula "sqrt(1 + (rayDirY * rayDirY) / (rayDirX * rayDirX))", but this can be simplified to abs(1 / rayDirX). \[thanks to Artem for spotting this simplification\] Similarly, deltaDistY is "sqrt(1 + (rayDirX * rayDirX) / (rayDirY * rayDirY))" which can be simplified to abs(1 / rayDirY). The variable perpWallDist will be used later to calculate the length of the ray.

In the calculation that involves Pythagoras, why is a "+1" involved? I thought the equation was a^2+b^2=c^2? I feel dense... Also, I do not understand how the simplification to abs(1/rayDirX) works.

# Answer
> 1 votes
I believe what is going on here is a rescale of the triangle. See: https://betterexplained.com/articles/rescaling-the-pythagorean-theorem/

---
Tags: mathematics, raycasting
---


# Question
Title: Affecting all instances of a GameObject at once
I want all instances of a prefab to change their velocity when one of them is clicked, and I think having each object constantly check a variable with a coroutine might not be the best solution. How can I reference all instances of the prefab in a script efficiently?

# Answer
Gather the instances into a collection as you instantiate them. Then you can iterate over all members of the collection anytime you want, with no search overhead.

```
public class MyType : MonoBehaviour {

    static List<MyType> allOfMyType = new List<MyType();

    void Awake() {
        allOfMyType.Add(this);
    }

    void OnDestroy() {
        allOfMyType.Remove(this);
    }

    public void DoSomethingToAllOfUs() {
        foreach(var instance in allOfMyType)
            DoSomethingTo(instance);
    }
}

```
> 5 votes

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


title: How to create soft gradient texture

text:
# Question
Title: How to create soft gradient texture
I'm currently testing out Unity 3D and one of the things I can not figure out, is how to create textures that are what I would describe as "Soft Gradient".

Here is an image of what I would describe the textures as "Soft Gradient"  If you look at the top of the hexagons (the grass). you can see that its not just one color, its a texture that is a "Soft Gradient".

Currently, this is what I have,

Does anyone have tips or can help my understand how to make my hexagon pillars look similar to the ones in the picture?

# Answer
> 2 votes
The gradients in the screenshot provided are probably not achieved by texturing in a different manner. It appears that the scene in the screenshot is making use of Global Illumination. This results in soft ambient shadows (Ambient Occlusion) where there are dense clusters of trees, holes, crevices, corners, etc. This is due to less ambient light being able to reach/escape these areas. If you happen to be using them, both Unity and Unreal have built-in GI options.

---
Tags: textures, rendering, terrain-rendering
---


# Question
Title: GPU (render time) increase if screen size increase
i create a simple 2d scene in unity 2017.3.1f1

I changed the **size (height and width)** in the **Game View** and proflie to see how it affects the rendering.. (below photo)

I saw that the rendering time increases by increasing size, and now if this happens when playing the game on a different resolution android phone, each The higher the resolution of the phone, the more likely it is to get gpu bound !???

And i do not understand **Cpu** graph in the two situations in above photo(lower GPU ---\> higher CPU !!!)

I tested my game on the "huawei mate 10 lite"(android device) with a resolution of 1080 x 2160 and it looks like there is a lot of rendering time.(a **simple** scene with only 5 sprite renderer)

(unity dosen't show **GPU profiling** when game run on android device and we can't check these...)

I did all the **optimizations** I heard, like:

DynamicBatching, Sprite Atlas , Quality Setting , sprite Texture Comprestion Override for Android.. What can be done to ensure that **rendering time** does not exceed a specified limit on different phones ??

# Answer
In your GPU there's a thing called fragment shader which gets executed for each pixel. Fragment shader does some calculation to determine the colour for a pixel. The complexity of this shader varies based on what you are trying to achieve. Generally It has to consider the lighting in the scene and everything that affects the look of the pixel.

so if you are running your game at 5x5 resolution then 25 fragments shader will get executed. You see, Processing takes time so the more pixel you will throw to the GPU the more fragment shader will get processed.

You should take a look into this awesome tutorial before jumping into profilers and stuff : https://learnopengl.com
> 1 votes

---
Tags: unity, android, optimization, gpu, profiler
---


title: Spritebatch and Shaperenderer

text:
# Question
Title: Spritebatch and Shaperenderer
When I am using the same spritebatch to draw texture and calling shaperenderer inside it, it is kind of misbehaving, like texture is not getting drawn or font is not getting drawn, Why is it happening?

For example(pseusdo code):

```
spritebatch.begin()
draw texture
shaperenderer.begin()
shaperenderer.end()
spritebatch.end()

```

but when I use it with different ends and begins it is drawing the way I want it to, but drawing so many spritebatches is reducing the performance of the phone.Reason I have to draw many spritebatches is because I want some texture to overlap on on some other shaperender's function.Any suggestions?

# Answer
> 5 votes
From this topic: http://badlogicgames.com/forum/viewtopic.php?t=8573&p=38930

You should try not to do the following: (Quote from one of the GDX creators)

```
batch.begin();
shapes.begin();

.. draw stuff from both ...

shapes.end();
batch.end();

```

And from me - **Don't use `ShapeRenderer` for drawing** \- it's for debugging purposes.

Instead of this create a 1x1px image with a white color and create a class like `CustomLine` which extends `Actor` and make it's `draw()` look like this:

```
public void draw(batch, parentalpha){
    batch.begin();
    batch.draw(smallpixelimage, getX(), getY(), getWidth(), getHeight());
    batch.end();
}

```

Just create an object of your new class `CustomLine`, add it to a stage/table or what you want and set it's size to 1x50 or something you like and you have your full-performance shaperenderer imitation ;)

But, if you really want a have a reason to use `ShapeRenderer` in your application, do it like:

```
batch.begin();
// draw graphics
batch.end();

shaperenderer.begin();
// draw shapes
shaperenderer.end();

```

and it will work.

# Answer
> 0 votes
Use the functions in the following order

```
shaperenderer.begin()
draw the shape
shaperenderer.end()

spritebatch.begin()
draw some texture
spritebatch.end()

```

---
Tags: libgdx, textures, fonts, spritebatch
---


# Question
Title: How to access internal data from separated rendering-layer?
I am currently rewriting a project I have been working on last year and I’m utterly stuck trying to "correctly" separate the game-logic from its representation. I know why this is beneficial and I sort of get how to build the representation into its own subsystem but if you actually encapsulate all the game-states into a different object or even library, how can you draw the scene?

Example:

Say we are working on the Super Mario game. There would perhaps be some Mario-object that encapsulates the different states Mario can enter (e.g. Small, Big, Fire-shooting, Mounted, …). These states are not purely visual since Mario’s movement-speed or damage-handling depends on this.

However, the way Mario is drawn also depends on this very state. So how would the rendering-layer know which sprite to bring onto the screen?

Pretty much everything the game-logic does causes some sort of animation, sound, or other output. In a way, having the drawing-logic mixed with the internals seems to be the cleanest since they really do belong together.

If you do separate the game-logic from its representation, there needs to be a way to access the data. What’s the best way to do that? I could think of these:

1. Data-binding by using some Event-system

Every time some state in the logic-layer changes, it could publish some event to which all other parts of the game can subscribe to. Upon receiving an Event, they can update themselves and load the appropriate animations.

However, this feels like we’re removing the responsibility of drawing the state onto the screen just to add the responsibility of firing an Event, which might actually be messier: There would be Events for each entity and each state, every spell that can be cast, every changed movement-parameter, plus every started, finished and interrupted attack – the list is huge compared to a function that “just renders the internal state”.

Also, there is a lot of bookkeeping to be done since each Event needs to manage a list of subscribers, which would probably be an Interface resulting in many indirect calls, which might cause a performance-hit as well.
2. Access the data from the rendering-layer

The representation-layer could just query the state, either by simple Getters or a complex Entity-Component-System where the data would be accessed plainly, anyway.

It still feels wrong to open up the (encapsulated) state like this, but it seems to be cleaner approach. In another post, I saw the use of the visitor-pattern, which sort of does this as well, but then there would be a Draw()-method on the game-object again, which sort of defeats the purpose, doesn't it?

Any input is highly appreciated cause I really want to stop thinking about it and just get into coding again. :D

Thank you so much!

# Answer
Both method A and B are feasible.

While an event system is the best way to decouple components, keep in mind that such systems tend to create a lot of overhead. The event handling and dispatching itself creates overhead and you might end up duplicating data in multiple layers of your architecture which takes additional memory and might cause a few bugs due to the additional complexity involved.

A much more efficient way is to simply have the game mechanics directly expose any state required by the rendering system, so the rendering system can operate on the original data. But this creates a tighter coupling between the rendering system and the gamestate.

An in-between solution could be to create another layer between the gamestate and the rendering system: the animation system. This system knows the state of the game mechanics and uses them to determine which spriteID to use for each object in the game on each frame. For example, when `mario.hasStar == true` it alternates between spriteIDs from the original spritesheet and spriteIDs from the alternative colors spritesheet each frame.

The rendering system then reads the spriteID the animation system came up with, determines the corresponding resource, and renders it.

As David Wheeler once said:

> All problems in computer science can be solved by another level of indirection... Except for the problem of too many layers of indirection.
> 1 votes

---
Tags: c++, architecture, animation, rendering
---


# Question
Title: Prevent Unity from crashing your computer?
Recently, I made a very dumb mistake that caused Unity to crash my computer. I could move the mouse sometimes, but everything else became completely unresponsive, leading to me having to shut off my PC.

What happened: I had an object, let's say an arrow, that could collide with another object, let's call it spawner. When the arrow collides with the spawner, it's supposed to destroy the arrow that activated the spawner. The spawner would then, as the name might imply, spawn more arrows. The problem was that I forgot to temporarily disable to collision on the newly spawned arrows, meaning that as soon as they would spawn inside the spawner's collision box, they'd spawn more arrows, and those arrows would spawn more arrows, and those arrows would... you get the idea. It was a very stupid mistake I realized the moment I hit play, but it was too late.

Now, I know that was entirely my fault, but I was wondering if you could prevent Unity from sending your PC into a coma like that? (Besides not making a dumb mistake like that, of course...) I'll be honest, I kind of expected Unity would have some sort of fail safe for this kind of error. Is there a way to limit the object count for example?

# Answer
> 1 votes
There is far more than one way to put Unity into an infinite loop which freezes both the game and the editor. So limiting the maximum number of objects (if that's actually possible, I don't think it is) would only protect you from a very small subset of possible mistakes.

But you can use a trick built into Windows to prevent Unity from using all of your CPU cores. The other cores are then still able to serve any other tasks, like handling the Windows UI system.

While Unity is running:

1. Open the Windows task manager with `Ctrl`+`Shift`+`Esc`
2. Go to the "Details" tab
3. Right-click on the Unity process
4. Select "Set Affinity..."
5. Uncheck one of your CPU cores

---
Tags: unity
---


# Question
Title: How can I exit an Unreal game with a specific exit code?
How could I quit out of a Unreal game with a specific exit code? In Unity you can just `Application.Quit(exitCode);` but I could not find anything regarding Unreal.

I know you can use the QuitGame-node or `FGenericPlatformMisc::RequestExit(false);` in C++ but without the custom exit code that I am looking for.

Any ideas?

# Answer
> 1 votes
You can always call `std::exit` with the desired code.

Unreal doesn't seem to provide an API to set the game's exit code directly, perhaps because not all target platforms can usefully do anything with the exit code and/or not all target platforms should really permit user termination (outside of the OS).

You can confirm this by looking at, say, `LaunchWindows.cpp` (link requires GitHub access to the Unreal Engine, which is free with registration with Epic) as UE 4.21. You can see that the return value of `WinMain` is driven by `GuardedMain` which in turn is driven by `FEngineLoop::Init()`, which only ever returns the constants `0` or `1`. You can reasonably conclude that since

* there is no code during the regular shutdown path handling any sort of user-defined exit code on at least one platform and
* Unreal itself does not call `std::exit` and
* Where Unreal calls platform-specific termination calls (like `PostQuitMessage`) it always provides a constant to the function, never a user-supplied exit code

that the code doesn't contain an abstraction for handling user-supplied exit codes.

---
Tags: c++, unreal-4
---


# Question
Title: Can't change materials of model from FBX
I was used 5.x before, and that version when I loaded FBX, Unity generated each material automatically, so I can change them like assigning textures or change shader.

And now I switched to 2017.3, and when I imported FBX, now Unity didn't generate materials anymore. I can see the properties of each material but every parameter is locked. It seems materials are inside of model and can't change like animation clips.

Some of model has multiple materials, so I can't generate manually and assign them. I'm creating mobile game so I really need to change the shader to mobile shader, not standard(PBR).

How to change materials of model from FBX in Unity 2017.3? Note that model created from Blender 2.7c and exported as FBX.

# Answer
I can't change default material directly, however I can make a new material and use instead, I can edit them from inspector. Or I can remap the material or for legacy support, Unity also have functionality to export all internal materials so I can edit them.
> 1 votes

# Answer
Inside the import settings inspector for your model, change from "Use Embedded Materials" to "Use External Materials (Legacy)".

You will then have a Materials Folder to modify.
> 3 votes

# Answer
You can change model prefab material, by selecting material avalible in assets. As I good understand your problem that should be what you need.
> -1 votes

---
Tags: unity, fbx, materials
---


# Question
Title: How to transfer an object from one state / form to another
I want to do a similar cooking meal like in the game "Overcooked". Where do you cook a variety of dishes.

I can not grasp the idea of how it is implemented or where to start. You take an object (vegetable), interact with the necessary "changers" (cutting, cooking). At the end of the process - you replace the model and go further?

What do I need to know? What to use? What to google?

I will be glad to any help.

# Answer
There are basically two ways to do this.

1. When you replace a "raw onion" with a "chopped onion" you `Destroy` the "raw onion" game object and then `Instantiate` a new "chopped onion" game object.
2. It's actually the same game object all the time, from being delivered to getting served. It just changes its appearance. You can do that by replacing the `.sprite` of the `SpriteRenderer` of the object or by using an Animator to transfer it from one appearance to another.
> 1 votes

---
Tags: unity
---


# Question
Title: OpenGL orthographic projection rendering quarter of screen
I'm trying to set up an orthographic projection so I can draw a rectangle using screen coordinates, but even if I draw a rectangle using the width/height of the window, it only fills a quarter of the window. Am I doing something wrong with glOrtho?

Relevant code: (width/height refers to window dimensions)

```
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, width, height, 0.0f, -1.0f, 1.0f);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glTranslatef(0.0f, 0.0f, 0.0f);
glBegin(GL_QUADS);
glVertex2i(0, 0);
glVertex2i(width, 0);
glVertex2i(width, height);
glVertex2i(0, height);
glEnd();

```

Output looks like this:

I am targeting OpenGL 2.1 if that matters.

# Answer
> 1 votes
I think I figured this out. I am calling glViewport with the window dimensions, but I believe it should be the framebuffer dimensions. In my case, the framebuffer was four times the size of the window.

I corrected the code as follows: (I'm using GLFW to manage windows)

```
glfwGetFramebufferSize(glfwWindow, &backingWidth, &backingHeight);
glViewport(0, 0, backingWidth, backingHeight);

```

---
Tags: opengl, projection, projection-matrix
---


# Question
Title: StateMachineBehaviour.OnStateExit is called before StateMachineBehaviour.OnStateEntered is called
When I start my game I get null-references in my OnStateExit of objects that are initialized in the OnStateEntered. After this it goes smooth, so it only occurs at startup before any conditions for statechanges are met.

How come? My understanding is that OnStateExit is always preceded by OnStateEntered.

My StateBehaviour

```
public class DuckStateBehaviour : BaseStateBehaviour {

    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        base.OnStateEnter(animator, stateInfo, layerIndex);
        mMovement.BeginDuck();
    }

    public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        if (mMovement != null) mMovement.EndDuck();
        base.OnStateExit(animator, stateInfo, layerIndex);
    }
}

public class BaseStateBehaviour : StateMachineBehaviour {

    protected Transform mTransform = null;
    protected Rigidbody2D mRigidBody = null;
    protected IMovement mMovement = null;

    public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        mTransform = animator.gameObject.GetComponent<Transform>();
        mRigidBody = animator.gameObject.GetComponent<Rigidbody2D>();
        mMovement = animator.gameObject.GetComponent<IMovement>();

        Debug.Assert(mTransform != null);
        Debug.Assert(mRigidBody != null);
        Debug.Assert(mMovement != null);
    }

}

```

# Answer
In case you have a transition, one state can start and the other can still be executing (updating): So yes, they can happen in the "wrong" way.
> 2 votes

---
Tags: unity, state
---