# Question
Title: How can I record gameplay footage as a video within Unity?
I am building a traffic simulator in Unity. I need to record my game as a video, so that I can use the video for machine learning purposes. I used fraps for the same but didn't find it worked for me since it's not within Unity. How can I make a video recording of the gameplay?

# Answer
> 2 votes
It's going to be difficult.

You'll need to find screen-recording software with an API so it can be activated by a client application.

Bandicam ( http://www.bandicam.com/ ) appears to have a basic screen capture API . The APIs are in C/C++ but in theory you could call the C API from a C#/.NET application.

Your user will need Bandicam installed and you'd be restricted to Windows platforms only.

It would be great to activate ShadowPlay or the other vendor-supported capture systems have APIs, but right now I'm not aware of any. You would have thought that Windows 10's Game Capture feature had an SDK, but I can't see any reference to one.

https://www.bandicam.com/company/sdk/bandi\_capture\_library/help/Chapter3.html

# Answer
> 0 votes
I have somewhat simplistic solution that I have used to make videos in this question....

To record screen I am using Iceream screen recorder (*Not affiliated in any way just a happy user*)

it allows you to select and record section on the screen so if you're up for manual this might just do it

# Answer
> 0 votes
You can use Unity API to do this. No need for any 3rd party. Unity renders a frame on its own, why would you need something to render it again or store the rendered texture from memory outside it, when you can do this inside C#? Right, no need to do this. But why is this so hard? Why can't I just take this texture? I don't really have the right answer to this because I'm not an expert on GPU. But as far as I know, even though GPU has memory, it deletes everything from there very often, I guess every frame. (Please if you understand this topic about GPU much more than I do, explain it in comments, I'm very thankful for this).

This Unity forum is dedicated to this question: How to access rendered depth buffer properly?

Unity allows to render the camera manually: Camera Render.

**With Some Code:**

Also, if this is or not VR, this thread would be definitely helpful and will save a lot of time looking for the performance hits: Real-Time Image Capture In Unity.

```
// Setup a camera, texture and render texture
Camera cam = ...;
Texture2D tex = ...;
RenderTexture rt = ...;

// Render to RenderTexture
cam.targetTexture = rt;
cam.Render();

// Read pixels to texture
RenderTexture.active = rt;
tex.ReadPixels(rectReadPicture, 0, 0);

// Read texture to array
Color[] framebuffer = tex.GetPixels();

```

Here is the code from Unity documentation on how to store render to png.

```
// We should only read the screen buffer after rendering is complete
yield return new WaitForEndOfFrame();

// Create a texture the size of the screen, RGB24 format
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);

// Read screen contents into the texture
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex.Apply();

// Encode texture into PNG
byte[] bytes = tex.EncodeToPNG();
Object.Destroy(tex);

// For testing purposes, also write to a file in the project folder
File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);

```

---
Tags: unity, video, screen-recording
---


# Question
Title: Why is my RigidBody2D not moving in Unity?
My problem is when I am pressing `A` or `D`, the player does not move. It is very stupid I am sure as you are, but I can not find what I am doing wrong. I could have achieved the effect I want with the help of `transform.translate()`, but I would like immensely to get what is misunderstood by me in the case.

Here is my code:

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

public class MovementController : MonoBehaviour
{
    public float runningSpeed;
    public Rigidbody2D playerBody;

    void Update ()
    {
        if(Input.GetKey("d"))
        {
            print("Right");
            moveRight();
        }
        else if (Input.GetKey("a"))
        {
            print("Left");
            moveLeft();
        }
    }

    private void moveLeft()
    {
        playerBody.AddForce(Vector2.left * (runningSpeed * Time.deltaTime), ForceMode2D.Force);
    }

    private void moveRight()
    {
        playerBody.AddForce(Vector2.right * (runningSpeed*Time.deltaTime), ForceMode2D.Force);
    }
}

```

Here is a screenshot of my editor:

# Answer
> 0 votes
Here is a solution. Unity considers Mass of 10 to be very large. First I tried to apply a very great force, like 10 thousand and noticed that `RigidBody2D` actually moves a little bit. Then I decreased Mass to 0.5 and voila I got a needed effect!

# Answer
> -1 votes
Your force depends linearly on "runningSpeed", so if the initial velocity is zero, it will stay zero. Try to give a different intial speed or change your force.

---
Tags: unity, 2d, physics, movement
---


# Question
Title: Controlling a fighter jet's altitude using device accelerometer
1. When I hit an object, my Fighter is supposed to fall to the Ground but because of the Accelerometer, I can still move it up and down even though it died. The Scroller on the x-Axis though stops.
**Question: (FIXED)** How can I make the Accelerometer stop, after I've been hit, and make the Fighter accelerate to the ground (in absence of the accelerometer, all by itself)?
2. When I move the Fighter up and down, the transition from "moving up" to "moving down" isn't smooth. It seems like it lags.
**Question:** How can I Increase the Sensitivity of my Accelerometer?
3. Also, when I tilt the phone further, the velocity stays the same.
**Question:** How can I increase the velocity, in relation to the tilt degree?

The code is below:

**Accelerometer Code:**

```
float accelY = Gdx.input.getAccelerometerY();

if (Gdx.input.getAccelerometerY() < 5){
   velocity.y = -40;
}

if (Gdx.input.getAccelerometerY() > 5){
   velocity.y = 40;
}

```

**When Fighter hits an Object and dies:**

```
public void die() {
    isAlive = false;
    velocity.y = 0;
    acceleration.y = 460;
}

```

# Answer
Check if the player is alive before applying the input.

```
  float accelY = Gdx.input.getAccelerometerY();

  if(isAlive) {
      if (Gdx.input.getAccelerometerY() < 5){
          velocity.y = -40;
      }
      if (Gdx.input.getAccelerometerY() > 5){
          velocity.y = 40;
      }
}

```
> 1 votes

# Answer
Why do you update the velocity of your fighter directly from the accelerometer? You should instead update its acceleration. By doing this, the movements will be smooth.

This is also the reason why the velocity stays the same if you tilt the phone further: you are always setting the velocity to + or - 40.
> 1 votes

# Answer
For 2 and 3 I would try to multiply like so:

```
Scaling = 1.2f;

If(Gdx.input.getAcceleratorY() < 5){
  Velocity.y = (Gdx.input.getAcceleratorY()*scaling)*(-1);
}else if(Gdx.input.getAcceleratorY() >= 5)
  Velocity.y = Gdx.input.getAcceleratorY()*scaling;
}

```

Try different values for scaling (probably has to be greater than 1). This should result in a more sensible, smoother and faster moving of your fighter.
> 0 votes

---
Tags: java, libgdx, mobile, motion-control, accelerometer
---


# Question
Title: AI: how can i detect if "i am under attack"?
I'm developing an AI. How can i detect if "I am under attack ?" so i can take a decision (flee and cover etc).

For under attack in mean something to check following conditions:

* if a bullet hit me or something near me

Thanks

# Answer
As you didn't precisely said what you call "under attack" I can see a few possibilities :

* If you have a health bar, you are under attack when it lowers. It is a very generic solution and it does not cover the cases when you hurt yourself by falling for instance, but it is very simple to implement. You just have to wait for HP variable to change as described in this Unity question.
* Check for collisions between your AI collider and specific weapons colliders such as bullets, swords, etc. I don't know anything about your project so those are suppositions. Look at what @Chris McFarland said.
* You can check for ennemies within a certain radius, it feels very intuitive and your AI won't wait for being hurt to react. You can use Physics.OverlapSphere for this purpose. More on this in this question.
> 2 votes

# Answer
As a rough idea:

When a bullet hits something, perform a Physics.OverlapSphereNonAlloc call (or if 2D, Physics2D.OverlapCircleNonAlloc) that checks for the layer that your creatures use, using the collision position as the center point with your desired radius.

For all nearby creature colliders found, you could have an `OnHeardSomethingNearby` method for each creature to call.
> 2 votes

# Answer
Are you using a state machine at all? You could have a regular check to update the AI state when an event is called, and have the state machine use an attached listener for the event within a radius. It's a bit more work, but it's extensible and very functional. Plus it makes it easy to use a branching tree for reactions depending on the event that occurs (duck, find cover, return attack, etc.) as well as reacting appropriately if the attack stops and enough time has gone by (return to patrolling, search and wait, etc.).
> 0 votes

---
Tags: unity, ai
---


# Question
Title: In Unity, how to get reference of descendant?
I'm trying to get descendant game object, not a child. Let's assume that I have a GameObject and it's hierachy looks like this:

```
Weapon
- Hands
- metarig
  - upper_arm.L
  - upper_arm.R
    - forearm.L.001
      - hand.L.001
        - weapon.L.001
          - AttackDetection(!)
- Sword

```

I want to access "AttackDetection" from Weapon(Root) in script. But when I try this:

```
void Start() {
    attackDetectionGObject = this.transform.Find("AttackDetection").gameObject;
}

```

It fails with this:

> NullReferenceException: Object reference not set to an instance of an object

Looks like transform.Find just looking up it's own child, not descendant. I try to find way to solve this problem, but there's nothing I found.

Any advice will be very very appreciate it.

# Answer
> 8 votes
Yes, `transform.Find(name)` will only look in the direct children of the current transform. But if you want to get a child deeper in the hierarchy, you can use slashes to describe the complete path. So `transform.Find("Weapon/metarig/upper_arm.R/forearm.L.001/hand.L.001/weapon.L.001/AttackDetection")` should work.

An alternative might be to use `getComponentInChildren` to target a component unique to the object you need (or `getComponentsInChildren` to get all matching components from child-objects). These methods will iterate the whole object-hierarchy of the object you call them on. The advantage of this solution is that it is more robust in case you change your object setup and that it works when you only know the exact setup at runtime. The drawback is that it is also slower, especially when you run it on a very large branch of your object-tree. But if you do this only once in your `Start` method of a long-living object, performance shouldn't matter that much.

# Answer
> 2 votes
If you want to stick to the search via string, you can use a simple recursive method like this:

```
using UnityEngine;

public static class FindInChildren {

    public static Transform Find(this Transform parent, string name) {

        var searchResult = parent.Find(name);

        if (searchResult != null)
            return searchResult;

        foreach (Transform child in parent) {
            searchResult = child.Find(name);
            if (searchResult != null)
                return searchResult;
        }

        return null;
    }
}

```

You can use the `FindInChildren.Find(nameString)` any time to search the full children hierarchy of a game object.

But beware that using `Transform.Find` or `GameObject.Find` should be avoided as much as possible, because it's quite slow (and `GameObject.FindWithTag` is faster, even though it searches the whole hierarchy) and searching items by string arguments is a bad practice anyway.

The best way, as suggested by Philipp, is to use `GetComponentInChildren<T>`, and attaching to the game objects you want to be found a script (it can be empty) with name `T`.

Remember, as a final note, that `Find` returns any game object, active or inactive, whereas `GetComponentInChildren<T>` by default doesn't: you need to use `GetComponentInChildren<T>(true)` in order to search for components in both active and inactive game objects.

# Answer
> 0 votes
You can also use `Transform#GetChild(int)` to get the Nth child of the transform.

So getting your AttackDetection object in this case would be:

```
Transform ad;
ad = transform.GetChild(1).GetChild(1).GetChild(0).GetChild(0).GetChild(0).GetChild(0);
attackDetectionGObject = ad.gameObject;

```

(Splitting things across lines so it fits within the display width here on SE).

But this only works for *statically arranged hierarchies,* that is, Hands will always come before metarig, etc. But for something like a humanoid player where you as the developer know that you're not going to be rearranging things, it's a nice shortcut. You can even combine it with `Transform.Find(string)` when the layout goes from static to dynamic. I use a mix myself in my own projects, though I typically use a `.Find` for the last step so that the code remains readable (that is, answering my future self's question: "*which* object is that again?").

The advantage is that Transform hierarchies are stored in memory like arrays, so accessing the Nth element has complexity O(1) and is much, *much* faster than a `.Find` lookup.

---
Tags: unity, transformation
---


# Question
Title: Stopping a reflecting raycast/linerender laser
**Update**: *Doing some more experimenting... it's not the early break that's causing the problem in the slightest. It does the same thing if I set the reflections to more than 2 and have no if or break in there.*

*So, I need to rethink this whole thing from scratch and try to find a better tutorial, I guess.*

I'm working on a game for a game jam (I asked, asking for help is permitted :-)) involving lasers that reflect off of mirrors that are adjusted by the player to make the laser hit a target. Thanks to some tutorials, I managed to get the lasers to reflect, but they reflect off of everything and won't stop unless I manually set a number of reflections to stop at.

I've tried adding an if statement to break the reflection loop if it doesn't hit a mirror, as you'll see in the code, but it just results in a laser going off on a weird angle after hitting the non-mirror target.

I should add that I'm very new at this. I'm basically figuring things out as I go for this game jam. So, I know it's probably a simple mistake, or maybe I followed the completely wrong tutorial, but I just can't see it.

Can anybody please point me to the mistake?

```
void Update()
{
    //clamp the number of reflections between 1 and int capacity
    nReflections = Mathf.Clamp(nReflections, 1, nReflections);
    //cast a new ray forward, from the current attached game object position
    ray = new Ray(goTransform.position, goTransform.forward);

    //represent the ray using a line that can only be viewed at the scene tab
    Debug.DrawRay(goTransform.position, goTransform.forward * 100, Color.magenta);

    //set the number of points to be the same as the number of reflections
    numPoints = nReflections;

    //make the lineRenderer have that number of points
    lineRenderer.positionCount = numPoints;
    //Set the first point of the line at the current attached game object position
    lineRenderer.SetPosition(0, goTransform.position);

    for (int i = 0; i <= nReflections; i++)
    {
        //If the ray hasn't reflected yet
        if (i == 0)
        {
            //Check if the ray has hit something
            if (Physics.Raycast(ray.origin, ray.direction, out hit, 100))//cast the ray 100 units at the specified direction
            {
                //the reflection direction is the reflection of the current ray direction flipped at the hit normal
                direction = Vector3.Reflect(ray.direction, hit.normal);
                //cast the reflected ray, using the hit point as the origin and the reflected direction as the direction
                ray = new Ray(hit.point, direction);

                //Draw the normal - can only be seen at the Scene tab, for debugging purposes
                Debug.DrawRay(hit.point, hit.normal * 3, Color.blue);
                //represent the ray using a line that can only be viewed at the scene tab
                Debug.DrawRay(hit.point, direction * 100, Color.magenta);

                //Print the name of the object the cast ray has hit, at the console
                //Debug.Log("Object name: " + hit.transform.name);

                //if the number of reflections is set to 1
                if (nReflections == 1)
                {
                    //add a new vertex to the line renderer
                    lineRenderer.positionCount = ++numPoints;
                }

                //set the position of the next vertex at the line renderer to be the same as the hit point
                lineRenderer.SetPosition(i + 1, hit.point);

            }
        }
        else // the ray has reflected at least once
        {
            //Check if the ray has hit something
            if (Physics.Raycast(ray.origin, ray.direction, out hit, 100))//cast the ray 100 units at the specified direction
            {
                //the refletion direction is the reflection of the ray's direction at the hit normal
                direction = Vector3.Reflect(direction, hit.normal);
                //cast the reflected ray, using the hit point as the origin and the reflected direction as the direction
                ray = new Ray(hit.point, direction);

                //Draw the normal - can only be seen at the Scene tab, for debugging purposes
                Debug.DrawRay(hit.point, hit.normal * 3, Color.blue);
                //represent the ray using a line that can only be viewed at the scene tab
                Debug.DrawRay(hit.point, direction * 100, Color.magenta);

                //Print the name of the object the cast ray has hit, at the console
                // Debug.Log("Object name: " + hit.transform.name);

                //add a new vertex to the line renderer

                lineRenderer.positionCount = ++numPoints;

                //set the position of the next vertex at the line renderer to be the same as the hit point
                lineRenderer.SetPosition(i + 1, hit.point);
            }
        }

        if (hit.collider.tag != "Mirror")
        {
            break;
        }
    }
}

```

Screenshot from my prototype of the extra reflection. It should not reflect off of that cube, and especially not at that weird angle (the foreground object is my primitive laser model, shooting off to the right):

# Answer
A user on itch.io (adroitconceptions) helped me figure out the problem: The logic and code was completely messed up. The code he helped me update now works perfectly.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent (typeof(LineRenderer))]
public class RayCastReflection : MonoBehaviour
{
    //this game object's Transform
    private Transform goTransform;
    //the attached line renderer
    private LineRenderer lineRenderer;
    //a ray
    private Ray ray;
    //a RaycastHit variable, to gather informartion about the ray's collision
    private RaycastHit hit;
    //reflection direction
    private Vector3 direction;
    //the number of reflections
    public int nReflections = 2;
    //max length
    public float maxLength = 100f;
    //the number of points at the line renderer
    private int numPoints;
    //private int pointCount;
    void Awake ()
    {
        //get the attached Transform component
        goTransform = this.GetComponent<Transform> ();
        //get the attached LineRenderer component
        lineRenderer = this.GetComponent<LineRenderer> ();
    }
    void Update ()
    {
        //clamp the number of reflections between 1 and int capacity
        nReflections = Mathf.Clamp (nReflections, 1, nReflections);
        ray = new Ray (goTransform.position, goTransform.forward);
        //start with just the origin
        lineRenderer.positionCount = 1;
        lineRenderer.SetPosition (0, goTransform.position);
        float remainingLength = maxLength;
        //bounce up to n times
        for (int i = 0; i < nReflections; i++) {
            // ray cast
            if (Physics.Raycast (ray.origin, ray.direction, out hit, remainingLength)) {
                //we hit, update line renderer
                lineRenderer.positionCount += 1;
                lineRenderer.SetPosition (lineRenderer.positionCount - 1, hit.point);
                // update remaining length and set up ray for next loop
                remainingLength -= Vector3.Distance (ray.origin, hit.point);
                ray = new Ray (hit.point, Vector3.Reflect(ray.direction, hit.normal));
                // break loop if we don't hit a Mirror
                if (hit.collider.tag != "Mirror")
                    break;
            } else {
                // We didn't hit anything, draw line to end of ramainingLength
                lineRenderer.positionCount += 1;
                lineRenderer.SetPosition (lineRenderer.positionCount - 1, ray.origin + ray.direction * remainingLength);
                break;
            }
        }
    }
}

```
> 1 votes

# Answer
Right now your code is "raycast hit something: reflect unconditionally." If you want it to only reflect off mirrors you need to add some code:

```
//...
        //Check if the ray has hit something
        if (Physics.Raycast(ray.origin, ray.direction, out hit, 100))//cast the ray 100 units at the specified direction
        {
            //the refletion direction is the reflection of the ray's direction at the hit normal
            direction = Vector3.Reflect(direction, hit.normal);
            //cast the reflected ray, using the hit point as the origin and the reflected direction as the direction

            //NEW!
            //if the ray hit a mirror, reflect! Otherwise do nothing.
            if(hit.transform.name == "Mirror") {
                ray = new Ray(hit.point, direction);
            }
            else {
                i = 9999; //not the best, see additional comments
            }
            //Draw the normal - can only be seen at the Scene tab, for debugging purposes
            Debug.DrawRay(hit.point, hit.normal * 3, Color.blue);
            //represent the ray using a line that can only be viewed at the scene tab
            Debug.DrawRay(hit.point, direction * 100, Color.magenta);

            //Print the name of the object the cast ray has hit, at the console
            // Debug.Log("Object name: " + hit.transform.name);
            //add a new vertex to the line renderer
            lineRenderer.positionCount = ++numPoints;
            //set the position of the next vertex at the line renderer to be the same as the hit point
            lineRenderer.SetPosition(i + 1, hit.point);
        }
//...

```

By setting `i` to 9999, it means that the code will treat this loop as the last one, it will finish drawing this portion of the line, then terminate. This isn't the best way to do this, but it leaves your code laid out the same way it already was. If the `if(hit == "mirror")` section is moved to the end of its parent section, then we can do `else { break; }` instead, which will break out of the for-loop early.

You'll have to do this in both halves of your update loop, as you have a "if hasn't yet bounced" versus "has previously bounced" sections which are largely identical.

Code is also assuming your mirrors are named "Mirror" which they may not be, and using tags would be better. Limits of my being able to write functional code that explains is intent without knowing what your scene looks like.
> 1 votes

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


# Question
Title: Fixed distance between character and ground whatever slope value
I am working on character moving on any ground meaning whatever slope degree ,the result i got is the character does not moving on just shake in his place the following the code i wrote

```
public float speed = 1;
bool isMoving;
Transform childPosition;
Rigidbody rb;

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

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

    if (Input.GetAxis("Horizontal") > 0)
    {
        rb.velocity = new Vector3(1f, rb.velocity.y, rb.velocity.z);
    }
    else
    if (Input.GetAxis("Horizontal") < 0)
    {
        rb.velocity = new Vector3(-1f, rb.velocity.y, rb.velocity.z);
    }
    else
    transform.position += transform.forward * Time.deltaTime * speed;

    detectRoad();
}
private void detectRoad()
{
    Ray ray = new Ray(transform.position, -transform.up);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit))
    {
        transform.rotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
    }
    if (hit.distance < 0.6f)
    {
        transform.position += transform.up * Time.deltaTime;
    }
    else
    if (hit.distance > 2f)
    {
        transform.position += -transform.up * Time.deltaTime;
    }
}
   `

```

This animated gif is about what I want:

# Answer
Thanks for everyone who tried to help me I found the answer how to make **Fixed distance between character and ground** the following is the answer :

```
Ray ray = new Ray(transform.position,-transform.up);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit)) {
        transform.rotation = Quaternion.FromToRotation(transform.up,hit.normal)*transform.rotation;
        targetDir = (transform.position - hit.point).normalized;
        transform.position = hit.point +  targetDir* 1f;
    }

```

that's worked with me ,i hope that's working with each one facing this problem
> 0 votes

# Answer
To be able to keep your distance fixed from the ground, you can do something like this:

```
//Pseudocode (this means it won't work if you copy and paste,
//implement the correct code on your own using this idea)

public float _fixedDist;

void Update
{
   var hitinfo;
   Raycast(from transform.position, towards vector3.down, out hitinfo);
   var hitpoint = hitinfo.point;
   var desiredY = hitpoint.y + _fixedDist;
   transform.y = desiredY;
}

```

---

Note:

Do not modify Transform of a GameObject if it has a Rigidbody component on it. Instead you can set the position or rotation through Rigidbody component.

This is because, when you modify the Transform of a Rigidbody attached GameObject, the physics engine must "recalculate" the colliders, which is an expensive operation.

Also, inside FixedUpdate, you should use fixedDeltaTime instead of deltaTime.
> 0 votes

---
Tags: unity, 3d, character, moving-platforms
---


title: 2D stop on collision

text:
# Question
Title: 2D stop on collision
So, this is the code I have right now:

```
if (keysPressed.Count() > 0)
        {
            switch (keysPressed[0])
            {
                case Keys.W:
                    {
                        characterStats.Velocity.Y += velocityCahge*(-1);
                        break;
                    }
            }
        }

        for (int i = 0; i < 2; i++)
        {
            if (Rectangle.Intersects(anotherRectangle))
            {
                characterStats.Velocity.X *= -1;
                characterStats.Velocity.Y *= -1;
            }
        }

       characterStats.position.X += Velocity.X;
       characterStats.position.Y += Velocity.Y;

```

The problem with this, is that sometimes, after collision, when pressing button to go in opposite direction from the collided sprite, the character starts going inside the sprite, in the opposite direction to where the button should move him. I know, that it happens cause of that \*= -1, but how do i prevent that?

# Answer
I believe the problem with your collision is that the character's rectangle continues to be within the other rectangle.

And if that's the case, then the solution would be too figure out the intersection width/height and and subtract it from the character's position so that they are popped out of the rectangle when they intersect.

For the image below, the code would be something like:

```
for (/* every rectangle to potentially collide with */)
{
    if (/* rectangle intersects character */)
    {
        /* calculate dx and dy */

        characterStats.position.X -= dx;
        characterStats.velocity.X *= -1;

        /* do similar process for Y */
    }
}

```
> 1 votes

---
Tags: c#, xna, 2d, collision-detection
---


# Question
Title: Constraining camera bounds within bounds based on Unity UI object dimensions
I have a perspective camera which has bounds which I wish to constrain within larger bounds. All the bounds are calculated in world space.

The code for containing the camera within the constraining bounds is straightforward:

```
        var camRect = this.cameraComponent.GetCameraWorldRect();
        var correction = Vector3.zero;

        if (camRect.xMin < constrainingRect.xMin)
        {
            correction.x += Mathf.Abs(constrainingRect.xMin - camRect.xMin);
        }

        if (camRect.xMax > constrainingRect.xMax)
        {
            correction.x -= Mathf.Abs(constrainingRect.xMax - camRect.xMax);
        }

        if (camRect.yMin < constrainingRect.yMin)
        {
            correction.y += Mathf.Abs(constrainingRect.yMin - camRect.yMin);
        }

        if (camRect.yMax > constrainingRect.yMax)
        {
            correction.y -= Mathf.Abs(constrainingRect.yMax - camRect.yMax);
        }

        this.cameraComponent.transform.position += correction;

```

This can be visualized as:

The problem I am facing is that I have a UI object that is covering the right hand side of the screen and I am uncertain how to correctly calculate the width of the UI object so that the constrained camera bounds can take it into account.

The camera that is drawing the UI object is configured as follows:

The camera that is being constrained is configured as follows:

Apart from the layer, the parameters which affect the rendering of the objects for each camera configuration are the same.

The UI object has the following configuration with a Canvas Renderer:

This is how I am currently attempting to calculate to width of the UI object but given that the UI is being rendered using a perspective camera I wasn't too certain that ScreenToWorldPosition was correct.

```
    private float CalculateMenuWidth()
    {
        // Generate padding to account for the side menu
        var canvas = LevelEditor.Instance.Menu.GetComponentInParent<Canvas>();
        var menuRect = LevelEditor.Instance.Menu.GetComponent<RectTransform>();
        var menuRectMax = menuRect.rect.max * canvas.scaleFactor;
        var menuRectMin = menuRect.rect.min * canvas.scaleFactor;

        if (this.cameraComponent.orthographic)
        {
            return Mathf.Abs(this.cameraComponent.ScreenToWorldPoint(menuRectMax).x - this.cameraComponent.ScreenToWorldPoint(menuRectMin).x);
        }

        // Perspective camera requires distance for ScreenToWorldPoint
        var distance = Mathf.Abs(this.cameraComponent.transform.position.z);

        return Mathf.Abs(this.cameraComponent.ScreenToWorldPoint(new Vector3(menuRectMax.x, 0f, distance)).x - this.cameraComponent.ScreenToWorldPoint(new Vector3(menuRectMin.x, 0f, distance)).x);
    }

```

However, the size of menu returned by the method above appears to be too large.

How can I correctly calculate the width of the UI object so it appears that the camera constraints do not allow the camera to travel past the UI object?

EDIT: I've added a link to a Unity project which is the minimal working example for reproducing the issue.

https://www.dropbox.com/s/mq36mfqz5wvvsch/CameraConstraintGUIIssue.zip

The camera can be controlled with WASD to translate and the Shift key will speed up the movement.

The camera is constrained inside the checkerboard. An offset is created so that the camera should stop moving to the right once the right edge of the checkerboard is adjacent to the left edge of the menu. Unfortunately, I can't seem to calculate the size of the menu correctly so this occurs.

The code for constraining the camera and calculating the menu size is in EditorCamera.cs.

Edit2:

The constraint from KingDolphin

The constraint I am attempting to calculate (quoted from above, *An offset is created so that the camera should stop moving to the right once the right edge of the checkerboard is adjacent to the left edge of the menu.*):

# Answer
# **EDIT:**

To fix the problem shown in Edit2, a slightly more complicated process has to happen.

So the big problem that makes calculating the width mildly complicated is that you have two different cameras: a UI camera, and the actual camera that we want to constrain.

This is totally fine, but the math becomes slightly more annoying.

The reason that it's slightly more complicated is that directly converting the `menuRect` corners into world coordinates converts it based off of the UI camera which is a far larger camera (in terms of FOV).

So what we have to do is scale the size of the `menuRect` down to the size of the constrained camera.

To do this, we have to use *viewport coordinates*.

The viewport is the only thing that the two cameras share 100% of the time.

Which means that the viewport coordinates for the UI camera are the exact same for the constrained camera.

This allows us to convert coordinates with respect to the UI camera into different coordinates with respect to the constrained camera.

First, we have to get the `worldSpaceCoords` of the `menuRect` as before:

```
var worldSpaceCorners = new Vector3[4];
menuRect.GetWorldCorners(worldSpaceCorners);

```

Then, we have to loop through each corner and convert each corner into viewport coordinates **RELATIVE TO THE UI CAMERA**.

```
for (var i = 0; i < 4; i++)
{
    var viewport1 = uiCamera.WorldToViewportPoint(worldSpaceCorners[i]);
}

```

And finally, we have to convert the viewport coordinate back into a world coordinate **RELATIVE TO THE CONSTRAINED CAMERA**.

```
for (var i = 0; i < 4; i++)
{
    var viewport1 = uiCamera.WorldToViewportPoint(worldSpaceCorners[i]);

    worldSpaceCorners[i] = this.cameraComponent.ViewportToWorldPoint(viewport1);
}

```

So the final result is:

```
private float CalculateMenuWidth()
{
    var menuRect = GameObject.Find("Panel").GetComponent<RectTransform>();
    var uiCamera = GameObject.Find("UICamera").GetComponent<Camera>();

    var worldSpaceCorners = new Vector3[4];
    menuRect.GetWorldCorners(worldSpaceCorners);

    for (var i = 0; i < 4; i++) {
        // Transform to viewport from UI camera
        var viewport1 = uiCamera.WorldToViewportPoint(worldSpaceCorners[i]);

        // Transform from viewport to space using our camera
        worldSpaceCorners[i] = this.cameraComponent.ViewportToWorldPoint(viewport1);
    }

    return Mathf.Abs(worldSpaceCorners[2].x - worldSpaceCorners[0].x);
}

private void ContainWithin(Rect rect)
{
    // Make sure camera zoom fits inside level
    // ...

    // Create padding around the map so the UI buttons don't obscure it for ray casting, viewing, etc.
    var paddingRight = this.CalculateMenuWidth();
    // Left, bottom, top
    // ...

    this.cameraRect = this.cameraComponent.GetCameraWorldRect();
    var correction = Vector3.zero;

    if (this.cameraRect.xMax > rect.xMax + paddingRight)
    {
        correction.x -= this.cameraRect.xMax - (rect.xMax + paddingRight);
    }

    // Left, bottom, top
    // ...

    this.cameraComponent.transform.position += correction;
}

```

# **OLD:** (scroll up for updated answer/explanation)

Okay, I think you've overcomplicated calculating the width of the UI object, especially since you want it in world coordinates.

All it takes is simply getting the world coordinates of the UI object using

```
var menuRect = GameObject.Find("Panel").GetComponent<RectTransform>();

var worldSpaceCorners = new Vector3[4];
menuRect.GetWorldCorners(worldSpaceCorners);

```

And then very simply subtracting the x-coordinates of the opposite corners

```
return Mathf.Abs(worldSpaceCorners[2].x - worldSpaceCorners[0].x);

```

This is how to correctly calculate the width, but I noticed another problem (at least with the example project you gave).

When calculating the 'correction' vector; the code should be like this:

```
var correction = Vector3.zero;

if (this.cameraRect.xMin < rect.xMin + paddingLeft)
{
    correction.x -= this.cameraRect.xMin - (rect.xMin + paddingLeft);
}

if (this.cameraRect.xMax > rect.xMax - paddingRight)
{
    correction.x -= this.cameraRect.xMax - (rect.xMax - paddingRight);
}

if (this.cameraRect.yMin < rect.yMin + paddingBottom)
{
    correction.y -= this.cameraRect.yMin - (rect.yMin + paddingBottom);
}

if (this.cameraRect.yMax > rect.yMax - paddingTop)
{
    correction.y -= this.cameraRect.yMax - (rect.yMax - paddingTop;
}

```

For why – I'll focus on just the xMax if-statement. Hopefully, this (terrible) drawing illustrates how it works:

Basically, the if statement needs to see if the right side of the rect (`cameraRect.xMax`) is farther right (greater than) the farthest position that it can be.

The farthest position it can be without the UI is `rect.xMax`. So, to calculate the farthest position with the UI is `rect.xMax - width of UI` (paddingRight).

Now to move the cameraRect to the position just before its maximum position, you need to calculate the dx to move it by.

And the dx is simply the difference between its current position (`cameraRect.xMax`) and the farthest right position (`rect.xMax - paddingRight`).

So, the `correction.x` (dx) is `cameraRect.xMax - (rect.xMax - paddingRight)`

This same idea can be applied to the left, top, and bottom.

Hopefully, this solves your issue and explains it adequately.
> 1 votes

---
Tags: unity, c#, camera, gui
---


title: Question about references

text:
# Question
Title: Question about references
I have an enemy game object and an item game object.

Enemies have an ItemDrops script attached. Items have a DisplayItemLabel script attached.

Attached to each enemy:

```
public class ItemDrops : MonoBehaviour
{
    public Transform itemPrefab;
    private EnemyHealth enemyHealth;

    private float originToGroundDistance;
    private Vector3 offset;

    private bool itemDropped;
    private bool numberGenerated;
    private float randomNumber;

    private ItemData itemData;
    public string nameOfDroppedItem;

    void Start()
    {
        enemyHealth = GetComponent<EnemyHealth>();

        itemData = GameObject.Find("Item Manager").GetComponent<ItemData>();
    }

    void Update()
    {
        //Initialized in Update instead of Start because enemy floats to 1.083333 on the Y-axis after some time after Start
        originToGroundDistance = transform.position.y - 0.25f;
        offset = new Vector3(0f, originToGroundDistance, 0f);

        if (enemyHealth.isDead && !itemDropped)
        {
            if (!numberGenerated)
            {
                RandomNumberGenerator();

                //Debug.Log(randomNumber);

                if (randomNumber < 1)
                {
                    SpawnItem(itemData.coin);
                }
            }
        }
    }

    private void RandomNumberGenerator()
    {
        numberGenerated = true;

        randomNumber = Random.value;
    }

    private void SpawnItem(Item item)
    {
        itemDropped = true;
        nameOfDroppedItem = item.itemName;

        Instantiate(itemPrefab, transform.position - offset, Quaternion.identity);
    }
}

```

Attached to each item:

```
public class DisplayItemLabel : MonoBehaviour
{
    private GameObject itemLabel;
    private Text itemNameText;

    void Start()
    {

        itemLabel = transform.Find("Canvas/Item Label").gameObject;
        itemNameText = itemLabel.GetComponentInChildren<Text>();

        itemNameText.text = "Item Name";

        itemLabel.SetActive(false);
    }

    void Update()
    {
        ClampLabelToItem();
    }

    private void ClampLabelToItem()
    {
        Vector3 offset = new Vector3(0f, 16f, 0f);

        Vector3 desiredPosition = Camera.main.WorldToScreenPoint(transform.position) + offset;
        itemLabel.transform.position = desiredPosition;

        itemLabel.SetActive(true);
    }
}

```

Item is not a child of enemy for multiple reasons I can think of. One is that enemies are destroyed when they are killed. With that said, how do I get the item to know who dropped it or get the enemy to know which item it dropped? MY GOAL is to get `itemNameText.text = "Item Name";` to say something like `itemNameText.text = itemDrops.NameOfDroppedItem;` but I can't use `GameObject.FindGameObjectWithTag("Enemy").GetComponent<ItemDrops>();` because it won't always grab the correct enemy and thus the correct ItemDrops script. I also can't set `DisplayItemLabel.itemNameText.text = nameOfDroppedItem` in the SpawnItem function because it wouldn't know which item's DisplayItemLabel script to get.

So clearly, I'm having issues with references. What should I do?

# Answer
> 1 votes
You see where you have this line:

```
Instantiate(itemPrefab, transform.position - offset, Quaternion.identity);

```

Instantiate *returns* an object, that being the object created. Know what you can do with it?

```
GameObject drop = Instantiate(itemPrefab, transform.position - offset, Quaternion.identity);
DisplayItemLabel label = drop.GetComponent<DisplayItemLabel>();
label.itemNameText.text = this.gameObject.name;

```

Ta da. You can pass data from the enemy script *to* the spawned object without having to rely on the persistence of the enemy.

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


# Question
Title: Unity not scrolling when mouse not over object
In Unity I am using a scroll view. It works semi-perfectly (had a lot of problems with it, don't like how the UI system works).

The content for my scroll view is a bunch of buttons aligned vertically with some spacing between them. The problem is that the scroll rect will only scroll if I'm hovering over one of the buttons. If the mouse is between two buttons, it won't scroll.

Here are some screenshots:

Also, you may see that I'm not using the standard Scroll Rect, mine is nothing special, just disabled the dragging that is stupid to be used on non-touch devices.

# Answer
> 3 votes
`ScrollView` by default has an `Image` component with a `RaycastTarget` enabled like on the image below.

In order to detect touch and clicks, `UI` elements need to have at least one component with `RaycastTarget` enabled.

Your `ScrollView` doesn't have the default Image background so it doesn't respond to clicks. Add `Image` component to your `ScrollView` so it looks like a background and tick `RaycastTarget`. Set it's color opacity to `0f` and voilà :)

---
Tags: unity, ui-design, scrolling
---


# Question
Title: How to make Line Renderer lines stay flat?
I've noticed that as I add more vertexes to a Line Renderer line the line twists and stops being a smooth line.

.GIF Here: https://i.stack.imgur.com/cfpe5.gif

All lines are on the same z level, even if I remove the materials the lines still seem to twist.

I have no idea why it does this, or how to go about resolving it, any suggestions?C#

# Answer
The problem is basically this:

The LineRenderer is trying to connect the red dot positions. It's creating the green vertices to make a mesh. So the top line segment looks great. But then the LineRenderer tries to be economical, it reuses the vertices from the end of one line segment in the end of the second line segment. When there's a sharp angle, you get the problem you're seeing. The second line segment is pinched at the intersection because its 'end cap' is not perpendicular with its other 'end cap'.

The solution is to create your own line renderer, and not make it so economical. You can do this by generating a dynamic mesh. The mesh will consist of a series of thin quads. For each line segment, you can compute the four corners of the quad by calculating the normal of the line and a specified line width:

```
Vector3 normal = Vector3.Cross(start, end);
Vector3 side = Vector3.Cross(normal, end-start);
side.Normalize();
Vector3 a = start + side * (lineWidth / 2);
Vector3 b = start + side * (lineWidth / -2);
Vector3 c = end + side * (lineWidth / 2);
Vector3 d = end + side * (lineWidth / -2);

```

Here, `a`, `b`, `c` and `d` make up the four corners of a single line segment, just like the green dots in the image above. These vertices would be added to the mesh, and you'd also add the indices to make the four vertices into two triangles (so, six indices would be added, a-b-c and b-d-c).

This can obviously get rather complex. I believe another reason Unity implemented their LineRenderer the way they did was because doing it that way avoids another problem, corners. When you start drawing each line segment you'll start to see where the two line segments come together and form an ugly joint. There are ways to deal with this by calculating the shared normal between both lines and updating their vertices to the shared normal, but this only partially solves the problem, since you can still easily end up with pinched lines. The most robust solution is to generate additional vertices at the joints to act as corners.
> 13 votes

# Answer
I had the same problem and I solve it adding more points to smooth edges its not an elegant solution but its simple and works. At least for me. I wrote a function to do this:

```
Vector3[] Generate_Points(Vector3[] keyPoints, int segments=100){
    Vector3[] Points = new Vector3[(keyPoints.Length - 1) * segments + keyPoints.Length];
    for(int i = 1; i < keyPoints.Length;i++){
        Points [(i - 1) * segments + i - 1] = new Vector3(keyPoints [i-1].x,keyPoints [i-1].y,0);
        for (int j = 1;j<=segments;j++){
            float x = keyPoints [i - 1].x;
            float y = keyPoints [i - 1].y;
            float z = 0;//keyPoints [i - 1].z;
            float dx = (keyPoints [i].x - keyPoints [i - 1].x)/segments;
            float dy = (keyPoints [i].y - keyPoints [i - 1].y)/segments;
            Points [(i - 1) * segments + j + i - 1] = new Vector3 (x+dx*j,y+dy*j,z);
        }
    }
    Points [(keyPoints.Length - 1) * segments + keyPoints.Length - 1] = new Vector3(keyPoints [keyPoints.Length-1].x,keyPoints [keyPoints.Length-1].y,0);
    return Points;
}

```
> 1 votes

# Answer
One way to solve this for opaque lines is to render a circle at each joint. The circle needs to have a diameter equal to the line width. This requires a few extra vertices to be rendered, but looks really nice. You also can then get rid of the shared normals between the joints.

This still requires that you write your own rendering code instead of using the Unity Line Renderer.

I made an asset that does just this at http://u3d.as/nFE
> 0 votes

# Answer
The way I avoided this is that I always set the z position to 0 in the LineRenderer.SetPosition() method. So instead of writing

`LineRenderer.SetPosition(i, myVector3);`

I wrote

`LineRenderer.SetPosition(i, new Vector3(myVector3.x, myVector3.y, 0));`

But that isn't the best solution as you will still get those strange lines. The best solution that I could think of was creating separate lines. That worked perfectly for me. Hope this helps you.
> 0 votes

---
Tags: c#, unity, 2d, lines
---


# Question
Title: Checking if Body is surrounded by other Bodies
I'm trying to make a game like Rampart as practice. I have gotten to the point where I want to check if the castle is surrounded by walls and decide whether to fill in the area and continue the game, but I have no idea how to do this. I have thought about ray-casting from the castle but it wouldn't work if there was a bend in the walls.

So any help or suggestions would be great!

# Answer
> 1 votes
I think easiest way to solve this is to use very simple maze solver tactic. That is the "wall follower".

* Find wall
* Put your hand on the wall, either left or right of you
* Keep hand on wall
* Start moving
* Never let go off the wall, if there is a turn, you turn with the wall and if its "dead end" you turn but you still keep your same hand on the same side ( ie. left or right of you )

Eventually, you will find your way out.

---

So, how does this help you? You have to check after every wall placement, if you can walk around the wall ( either inside or outside, does not matter ) by walking near the wall until you get back to your starting point. However, it's easier to follow from inside so you can check the location of you newly place wall and go tile by tile towards the castle and find empty spot. That way you know you should be inside the walls.

1. Place wall
2. Find open spot near the wall
3. Check where the wall is considering your position now ( up,left,down or right)

Then, for example if

4. Wall is below you
5. Move left
6. If there is wall below you, goto 5
7. if there is NO wall below you, there might be turn to down, so move down.
8. There should be wall on the right side now, if not break out and fail
9. Move down with the same logic.

---

Google for: wall follower algorithm or something like that, to find examples

Maze\_solving\_algorithm -wikipedia

Keep the hand on the wall.

# Answer
> 0 votes
Floodfill from the castle.

* If the fill reaches an edge of the map: castle is not surrounded by walls
* If the fill does not reach the edge of the map: castle is surrounded by walls

Alternatively, you could use a pathfinding algorithm to check if there is a path between the castle and a point that must be outside the walls.

---
Tags: libgdx, box2d
---


# Question
Title: Android Studio with libGDX doesn't recognize boolean
In my game, when the users clicks an image button, the value of a boolean changes and then the game is closed. I mean, if I want to restart the game, I click this image button, the game is closed and immediately is opened. However this doesn't happen because the value of the boolean is false and I don't know why at all.

Here is the code of the image-button:

```
    playagain.addListener(new ClickListener()
    {
        @Override
        public void clicked(InputEvent event, float x, float y)
        {
            interfaccia.rigioca();
            Gdx.app.exit();
        }
    });

```

And this is the code of the MainActivity:

```
public class MainActivity extends Activity implements MyGdxGame.GestioneClick, Serializable
{
MainActivity activity;
boolean start;
@Override
public void onCreate(final Bundle bundle)
{
    super.onCreate(bundle);
    setContentView(R.layout.layout);
    activity = this;
    findViewById(R.id.button).setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            startActivity();
        }
    });

}

@Override
public void onResume()
{
    super.onResume();
    if(start)
        startActivity();
}

@Override
public void menu()
{
    start=false;
}

@Override
public void rigioca()
{
    start=true;
}

public void startActivity()
{
    Intent intent = new Intent(MainActivity.this,AndroidLauncher.class);
    intent.putExtra("MainActivity",activity);
    activity.startActivity(intent);
}

}

```

As you can see, rigioca method is called and start sould be true. **I checked ALL with logs** and we can say that the value is true. Then resume method is called but start value is false! How is it possible? I also took away `start=false;` in menu method, but that isn't the problem. Why is this variable false!?

Note: onDestroy and onCreate aren't called but the activity is destroyed.

# Answer
(from chat)

You should not be restarting your entire program when you wish to restart your game. Instead reset the variables that control your game to their original state.

Take this game as an example:

In this example I reset the player's health (top left), the level (top right), and the abilities (bottom right) whenever the player pushes my 'reset' button.

The code looks something like this:

```
gameOver = false;
handler.clear();
director.reset();
level = 0;
timer = 0;
enemies = null;
shields = 0;
teleports = 0;

```

I simply reset all of the variables to what they were when the game started :)
> 2 votes

---
Tags: android, libgdx, android-studio
---


# Question
Title: Is this the correct implementation of a fixed timestep game loop?
```
public static void main(String[] args) {

        long newTime, delta, timeSince1Second, startTime, oldTime;
        long ticks = 0;
        double frameCap = 1000/60;
        double time_passed = 0;

        startTime = System.currentTimeMillis();
        oldTime = System.currentTimeMillis();
        while(true)
        {
            newTime = System.currentTimeMillis();
            delta = newTime - oldTime;
            timeSince1Second = newTime - startTime;
            currentTime = newTime;

            //update game based on dynamic time step here (if needed)

            //update loop (fixed time step)
            while(time_passed >= frameCap)
            {
                //update game logic (fixed time step update)
                time_passed = time_passed - frameCap; //resetting time_passed essentially to 0
                ticks++;
            }

            time_passed = time_passed + (double) delta; //time passed since start of loop

            //render here

            //frame rate counter
            if((timeSince1Second/1000) >= 1)
            {
                System.out.println(ticks+" frames per second");
                startTime = System.currentTimeMillis();
                ticks = 0;
            }
        }
} //end main function

```

This code has been written in java. I'd like to know if i'm missing anything here, because in the fixed time step update loop, if i display for example a window, and move the window around, the framerate will sometimes change until i stop moving the window around, which is kind of confusing to me. Is that normal? Or perhaps I might be missing something Guidance will be appreciated

# Answer
> 1 votes
Short answer: no, this is not correct.

1. `time_passed = time_passed + (double) delta;` should come *before* your fixed update loop. It's updating your store of time that needs to be simulated.

Imagine our game lagged for whatever reason, and it's been 30 ms since the last frame we displayed. That's enough to do two fixed update loops. But if we don't add that time before checking how many fixed update loops to do, then we don't react to the longer frame duration. Our game visually slows down because not enough simulation steps have occurred to keep up with the time that's passed. Then, in the *next* frame, that extra time is now present in `time_passed`, so all our catch-up steps are done then - even if the frame time delta for this next frame was much smaller. So now our game runs too fast for a frame. Overall we're keeping pace with real time, but we're doing it in a stutter-and-race-ahead way that does not maintain a smooth update rate under varying frame times.
2. You want to do your dynamic frame rate updates after your fixed updates.

These dynamic updates are often for visual and audio feedback that needs to be presented to the player "just in time" to reflect the state of the game. When you do these updates before your fixed simulation steps, you allow the game state to get ahead of this feedback state before it's rendered to the screen.

So, for example, imagine we have a spider character that uses inverse kinematics to match its legs to the ground it's clambering along. The movement of the character is handled in the fixed update step for consistency, but we don't need to do the IK for every step along the way - we just need to snap the legs to the terrain at the end, before we render the frame to present to the player. If we did this dynamic IK step before the fixed update step, then the spider could continue to move after we've tried to position the legs, leading to a mismatch by the time the frame is rendered.
3. Your section labelled `//frame rate counter` is not measuring frame rate (as in, number of cycles per second).

It's measuring the number of fixed update steps per frame. This is expected to fluctuate, due to variable frame rate and mismatches between your rendering frame rate and the `frameCap` you've set. (eg. If you're rendering at 90 FPS, you'd expect to bounce between 0 & 1 fixed steps per frame, in a 1:2 ratio overall, so that the game's fixed update steps 60 times per second)

To measure whether your fixed update loop is keeping up correctly, you'd want to compare your total fixed step count since the start of the game versus your total time since the start of the game, divided by `frameCap`. Your fixed step count should be the same as the floor of your time divided by the framerate. If it drops behind by 1.0 or more and catches back up, then it's not correctly maintaining a fixed frequency of updates relative to real time.

(Similarly, your `timeSince1Second` is not really measuring a time since 1 second into the game - it's a time since game start. Watch out for these comments and variable names - they're your reminders later about what the code is doing. If you leave yourself misleading notes, then you're liable to make mistakes the next time you come back to this code to reason about it or alter it.)

---
Tags: java, game-loop
---


# Question
Title: Why does my shader's Texture become unselected when I run my game?
I'd like to add a custom material to a line that I'm drawing in Unity (using Vectrosity). I'm using Unity's built-in "Unlit/Texture" shader. When I drag a texture from my Resources directory into the "Texture" slot in my shader, everything looks good:

But when I click play, the texture disappears:

and my line doesn't show up in my game. However, if I drag the texture to the shader's texture slot *after* I click play, the texture seems to "stick" and my line renders as expected:

But once I stop and start the game, the texture again disappears.

Why is Unity kicking out my texture when my game starts? Is there something wrong with my texture? I don't see any warnings or errors in the console. I've tried with numerous different textures, and they all do the same thing.

I'm using Unity 5.6.1f1.

# Answer
> 1 votes
It seems that some script is removing the texture from the material at runtime.

I suggest you check `Awake`, `OnEnable` and `Start` on your scripts, apart from an odd Unity bug, the culprit should be there somewhere.

You should search for a `Material` type variable, and then look if there's a `materialVariableName.mainTexture = someValue;`. When `someValue` is `null`, the material's texture is obviously reset.

Edit: I forgot, you should check for `materialVariableName.SetTexture("_MainTex", someValue);` too.

---
Tags: unity, shaders, textures, materials, lines
---


# Question
Title: Rotate Earth around sun, and moon around earth
**SOLVED:** I'm trying to rotate the moon around the earth.

Which this part of the code only the earth is rotated around the sun, how can I make the axis to be center of earth's object? I thought about translateF(2,0,0) which doesn't work. Here's the part :

```
glPushMatrix();
glRotated((GLdouble)ObjectRotatingAngle, 0.0, 1, 0.0);
glTranslatef(2, 0, 0);
glutSolidSphere(earthR, 100, 100);
glPopMatrix();

//glTranslatef(2, 0, 0);
glRotated((GLdouble)ObjectRotatingAngle, 0.0, 1, 0.0);
glColor3f(0.5, 0.5, 0);
glPushMatrix();
glTranslatef(2.5, 0, 0);
glutSolidSphere(moonR, 100, 100);
glPopMatrix();

```

And full code:

```
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include"GL/glut.h"

//global constants
#define ANIMATION_DELAY 20
#define PI 3.14

//function declerations
void drawingCB(void);
void reshapeCB(int width, int height);
void keyboardCB(unsigned char key, int x, int y);
void keyboardSpecialCB(int key, int x, int y);
void TimerCB(int value);
GLubyte *readBMP(char *imagepath, int *width, int *height);
GLuint generateTextures(char *imagepath);
void TerminationErrorFunc(char *ErrorString);

//globals
int ObjectRotatingAngle = 0;
int ViewPointAngle1 = 0, ViewPointAngle2 = 0;
int FOVy = 60;
int OnOff = 1;
float sunR = 0.7;
float earthR = 0.4;
float moonR = 0.25;

//textures gloabals
int BoxTextureIds[6];
#define SKY_RIGHT 0
#define SKY_LEFT  1
#define SKY_UP    2
#define SKY_DOWN  3
#define SKY_BACK  4
#define SKY_FRONT 5
int TeapotTextureId;

int main(int argc, char** argv)
{

    //initizlizing GLUT
    glutInit(&argc, argv);

    //initializing window
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(900, 100);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    glutCreateWindow("3D world");

    //enable depth testing
    glEnable(GL_DEPTH_TEST);

    //registering callbacks
    glutDisplayFunc(drawingCB);
    glutReshapeFunc(reshapeCB);
    glutKeyboardFunc(keyboardCB);
    glutSpecialFunc(keyboardSpecialCB);
    glutTimerFunc(ANIMATION_DELAY, TimerCB, 0);

    //specify textures and setting Specific texture parameters
    BoxTextureIds[SKY_RIGHT] = generateTextures("posx.bmp");
    BoxTextureIds[SKY_LEFT] = generateTextures("negx.bmp");
    BoxTextureIds[SKY_UP] = generateTextures("posy.bmp");
    BoxTextureIds[SKY_DOWN] = generateTextures("negy.bmp");
    BoxTextureIds[SKY_BACK] = generateTextures("posz.bmp");
    BoxTextureIds[SKY_FRONT] = generateTextures("negz.bmp");
    TeapotTextureId = generateTextures("tex3.bmp");

    //setting Global texture parameters
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); //determine how texture mapping interacts
                                                                //with shading modes. Can be: GL_MODULATE or GL_BLEND or GL_REPLACE
    glEnable(GL_TEXTURE_2D);

    //starting main loop
    glutMainLoop();
}

GLuint generateTextures(char *imagepath)
{
    GLubyte *ImageData;
    int width, height;
    GLuint TextureID;

    //reading the image
    ImageData = readBMP(imagepath, &width, &height);

    //Giving a texture ID
    glGenTextures(1, &TextureID);
    glBindTexture(GL_TEXTURE_2D, TextureID);

    //Assign Image as a texture
    glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, ImageData);

    //freeing image memory
    free(ImageData);

    //setting Specific texture parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // GL_REPEAT or GL_CLAMP
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // GL_LINEAR or GL_NEAREST
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    return TextureID;
}

void drawingCB(void)
{
    GLenum er;
    double D = 10;
    double d = 0.02;
    double R = 5;

    //clearing the background
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //initializing modelview transformation matrix
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    //setting viewing angle
    gluLookAt(R*cos((double)ViewPointAngle1*PI / 180), 4, R*sin((double)ViewPointAngle1*PI / 180), 0, 0, 0, 0, 1, 0);

    //drawing a box
    //right
    glBindTexture(GL_TEXTURE_2D, BoxTextureIds[SKY_RIGHT]);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex3f(+D - d, -D, -D);
    glTexCoord2f(1, 0); glVertex3f(+D - d, -D, +D);
    glTexCoord2f(1, 1); glVertex3f(+D - d, +D, +D);
    glTexCoord2f(0, 1); glVertex3f(+D - d, +D, -D);
    glEnd();
    //left
    glBindTexture(GL_TEXTURE_2D, BoxTextureIds[SKY_LEFT]);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex3f(-D + d, -D, +D);
    glTexCoord2f(1, 0); glVertex3f(-D + d, -D, -D);
    glTexCoord2f(1, 1); glVertex3f(-D + d, +D, -D);
    glTexCoord2f(0, 1); glVertex3f(-D + d, +D, +D);
    glEnd();
    //up
    glBindTexture(GL_TEXTURE_2D, BoxTextureIds[SKY_UP]);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex3f(-D, +D - d, -D);
    glTexCoord2f(1, 0); glVertex3f(+D, +D - d, -D);
    glTexCoord2f(1, 1); glVertex3f(+D, +D - d, +D);
    glTexCoord2f(0, 1); glVertex3f(-D, +D - d, +D);
    glEnd();
    //down
    glBindTexture(GL_TEXTURE_2D, BoxTextureIds[SKY_DOWN]);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex3f(-D, -D + d, +D);
    glTexCoord2f(1, 0); glVertex3f(+D, -D + d, +D);
    glTexCoord2f(1, 1); glVertex3f(+D, -D + d, -D);
    glTexCoord2f(0, 1); glVertex3f(-D, -D + d, -D);
    glEnd();
    //back
    glBindTexture(GL_TEXTURE_2D, BoxTextureIds[SKY_BACK]);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex3f(-D, -D, -D + d);
    glTexCoord2f(1, 0); glVertex3f(+D, -D, -D + d);
    glTexCoord2f(1, 1); glVertex3f(+D, +D, -D + d);
    glTexCoord2f(0, 1); glVertex3f(-D, +D, -D + d);
    glEnd();
    //front
    glBindTexture(GL_TEXTURE_2D, BoxTextureIds[SKY_FRONT]);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex3f(+D, -D, +D - d);
    glTexCoord2f(1, 0); glVertex3f(-D, -D, +D - d);
    glTexCoord2f(1, 1); glVertex3f(-D, +D, +D - d);
    glTexCoord2f(0, 1); glVertex3f(+D, +D, +D - d);
    glEnd();

    if (OnOff)
    {
        //rotating the object

        printf("ObjectRotatingAngle:%d, Viewing points angles: %d,%d\n", ObjectRotatingAngle, ViewPointAngle1, ViewPointAngle2);

        glBindTexture(GL_TEXTURE_2D, TeapotTextureId);
        glTexGenf(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);//GL_OBJECT_LINEAR GL_EYE_LINEAR GL_SPHERE_MAP
        glTexGenf(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
        glEnable(GL_TEXTURE_GEN_S);
        glEnable(GL_TEXTURE_GEN_T);
        glutSolidSphere(sunR, 100, 100);
        glDisable(GL_TEXTURE_GEN_S);
        glDisable(GL_TEXTURE_GEN_T);
    }
    glPushMatrix();
    glRotated((GLdouble)ObjectRotatingAngle, 0.0, 1, 0.0);
    glTranslatef(2, 0, 0);
    glutSolidSphere(earthR, 100, 100);
    glPopMatrix();

    //glTranslatef(2, 0, 0);
    glRotated((GLdouble)ObjectRotatingAngle, 0.0, 1, 0.0);
    glColor3f(0.5, 0.5, 0);
    glPushMatrix();
    glTranslatef(2.5, 0, 0);
    glutSolidSphere(moonR, 100, 100);
    glPopMatrix();

    //swapping buffers and displaying
    glutSwapBuffers();

    //check for errors
    er = glGetError();  //get errors. 0 for no error, find the error codes in: https://www.opengl.org/wiki/OpenGL_Error
    if (er) printf("error: %d\n", er);
}

void reshapeCB(int width, int height)
{
    float zNear, zFar;

    //define our ortho
    zNear = 1; zFar = 40;

    //update viewport
    glViewport(0, 0, width, height);

    //clear the transformation matrices (load identity)
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    //projection
    gluPerspective(FOVy, 1, zNear, zFar);
}

void keyboardCB(unsigned char key, int x, int y) {
    switch (key) {
    case 27:
        exit(0);
        break;
    case '+':
        FOVy = FOVy - 1;
        reshapeCB(glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT));
        glutPostRedisplay();
        break;
    case '-':
        FOVy = FOVy + 1;
        reshapeCB(glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT));
        glutPostRedisplay();
        break;
    case ' ':
        OnOff = !OnOff;
        break;
    }
}

void keyboardSpecialCB(int key, int x, int y)
{
    switch (key) {
    case GLUT_KEY_LEFT:
        ViewPointAngle1 = (ViewPointAngle1 + 360 - 1) % 360;
        glutPostRedisplay();
        break;
    case GLUT_KEY_RIGHT:
        ViewPointAngle1 = (ViewPointAngle1 + 360 + 1) % 360;
        glutPostRedisplay();
        break;
    case GLUT_KEY_UP:
        ViewPointAngle2 = (ViewPointAngle2 + 360 - 1) % 360;
        glutPostRedisplay();
        break;
    case GLUT_KEY_DOWN:
        ViewPointAngle2 = (ViewPointAngle2 + 360 + 1) % 360;
        glutPostRedisplay();
        break;
    }
}

void TimerCB(int value)
{
    ObjectRotatingAngle = (ObjectRotatingAngle + 360 + 1) % 360;

    // reassign to the timer event again
    glutTimerFunc(ANIMATION_DELAY, TimerCB, value);

    // call redisplay
    glutPostRedisplay();
}

// Function to load bmp file
// buffer for the image is allocated in this function, you should free this buffer
GLubyte *readBMP(char *imagepath, int *width, int *height)
{
    unsigned char header[54]; // Each BMP file begins by a 54-bytes header
    unsigned int dataPos;     // Position in the file where the actual data begins
    unsigned int imageSize;   // = width*height*3
    unsigned char * data;
    unsigned char tmp;
    int i;

    // Open the file
    FILE * file = fopen(imagepath, "rb");
    if (!file) {
        TerminationErrorFunc("Image could not be opened\n");
    }

    if (fread(header, 1, 54, file) != 54) { // If not 54 bytes read : problem
        TerminationErrorFunc("Not a correct BMP file\n");
    }

    if (header[0] != 'B' || header[1] != 'M') {
        TerminationErrorFunc("Not a correct BMP file\n");
    }

    // Read ints from the byte array
    dataPos = *(int*)&(header[0x0A]);
    imageSize = *(int*)&(header[0x22]);
    *width = *(int*)&(header[0x12]);
    *height = *(int*)&(header[0x16]);

    // Some BMP files are misformatted, guess missing information
    if (imageSize == 0)
        imageSize = *width**height * 3; // 3 : one byte for each Red, Green and Blue component
    if (dataPos == 0)
        dataPos = 54; // The BMP header is done that way

                      // Create a buffer
    data = malloc(imageSize * sizeof(GLubyte));

    // Read the actual data from the file into the buffer
    fread(data, 1, imageSize, file);

    //swap the r and b values to get RGB (bitmap is BGR)
    for (i = 0; i<*width**height; i++)
    {
        tmp = data[i * 3];
        data[i * 3] = data[i * 3 + 2];
        data[i * 3 + 2] = tmp;
    }

    //Everything is in memory now, the file can be closed
    fclose(file);

    return data;
}

void TerminationErrorFunc(char *ErrorString)
{
    char string[256];
    printf(ErrorString);
    fgets(string, 256, stdin);     // warning: unsafe (see fgets instead)

    exit(0);
}

```

**SOLVED:**

```
//The earth
glColor3f(0.4901, 0.8117, 0.6705);
glRotated((GLdouble)ObjectRotatingAngle, 0.0, 1, 0.0);
glTranslatef(2, 0, 0);
glutSolidSphere(earthR, 100, 100);

//Rotating the moon around the earth
glRotated((GLdouble)ObjectRotatingAngle * 2, 0, 1, 0.0);
glColor3f(0.5, 0.5, 0);
glPushMatrix();
glTranslatef(0.5, 0, 0);
glutSolidSphere(moonR, 100, 100);
glPopMatrix();

```

# Answer
```
//The earth
glColor3f(0.4901, 0.8117, 0.6705);
glRotated((GLdouble)ObjectRotatingAngle, 0.0, 1, 0.0);
glTranslatef(2, 0, 0);
glutSolidSphere(earthR, 100, 100);

//Rotating the moon around the earth
glRotated((GLdouble)ObjectRotatingAngle * 2, 0, 1, 0.0);
glColor3f(0.5, 0.5, 0);
glPushMatrix();
glTranslatef(0.5, 0, 0);
glutSolidSphere(moonR, 100, 100);
glPopMatrix();

```
> 0 votes

---
Tags: opengl, transformation, c
---


# Question
Title: Change all boolean parameters of an Animator in Unity
How can I change all boolean parameters of an animator to `false`?

Here is a solution which I found:

```
foreach (AnimatorControllerParameter parameter in playerAnimator.parameters)
{
    playerAnimator.SetBool(parameter.name, false);
}

```

The problem with this solution is that I will get a warning in console if my parameter in `Animator` is not a boolean. I would not like to be getting that. So, I need somehow to being able to take only parameters of type boolean.

# Answer
> 5 votes
Just add a check:

```
foreach (AnimatorControllerParameter parameter in playerAnimator.parameters) {
    if (parameter.type == AnimatorControllerParameterType.Bool)
        playerAnimator.SetBool(parameter.name, false);
}

```

---
Tags: unity, animation
---


title: How to draw HUD in DirectX12?

text:
# Question
Title: How to draw HUD in DirectX12?
I would like to draw reference frame to see how my camera moves around scene. I want these arrows to always be on the top of other geometry. How can I achieve it?

I think I need to disable depth test for this draw calls. Should I use just another PSO with changed `DepthStencilState`?

---

EDIT: Well, it works for me like that.

```
// opaquePsoDesc defined somewhere above
D3D12_GRAPHICS_PIPELINE_STATE_DESC opaqueHudPsoDesc = opaquePsoDesc;
opaqueHudPsoDesc.DepthStencilState.DepthEnable = false;
THROW_IF_FAILED(g_device->CreateGraphicsPipelineState(&opaqueHudPsoDesc, IID_PPV_ARGS(&psos_["opaque_HUD"])));

```

And then before drawing your HUD you can:

```
commandList->SetPipelineState(psos_["opaque_HUD"].Get());

```

I'll leave this answer here, in case someone will need it.

---

Well, that works fine if you don't want depth test for the HUD objects.

# Answer
The DirectX 12 state model is that you create distinct Pipeline State Objects (PSOs) for every combination of state, render target configuration, and shaders you use in your application. You can share root signatures or change them as well. While creating PSOs and root signatures is expensive, setting them is very fast.

Generally for HUDs you draw the background and scene, and then draw the text over the top of that. The choice of color is important to ensure the HUD is visible. Such text ignores the depth test.

* For MSAA or post-processing, you render the scene to an offscreen render target fully, resolve/post-process it to the render target and *then* draw the HUD before presenting--often at this point you don't even have a depth/stencil buffer.
* With HDR rendering on 4K UHD displays, you typically use double the nits of the scene for the text.

> See DirectX Tool Kit for DirectX 12 and in particular the `SpriteFont` and `SpriteBatch` classes.
> 1 votes

---
Tags: hud, directx12
---


title: Travel over step angle

text:
# Question
Title: Travel over step angle
http://www.gamasutra.com/blogs/AdamWinkels/20140220/211306/DevLog\_7\_Learning\_How\_to\_Walk.php

Following the link above I have been able to get my character to move and rotate very smoothly over angled surfaces up-to 80 degrees. Anything over that and it begins to clip and wobble when traveling down the surface. The spiders rotation only reaches half of the desired angle. So at 85 degrees it only rotates to 42.5. Going up is a mess, but I have not implemented the fix for that from the link above, so I am less worried about that. Any suggestions?

```
private float RayDuration = 0;
private float RayAngle = 5f;
private float RayLength;
Vector2 MovementDirection;
float OffSetY  = 5;
float OffSetX = .5f;
int GroundMask = 1 << 8;

 void Start()
{
    SpiderRect = GetComponent<RectTransform>();
    RayLength = SpiderRect.rect.height;
}

private void TouchHeld(CustomEvent customEvent)
{

    if (Input.mousePosition.x > 400)
    {
        MovementDirection = transform.right;
    }
    else
    {
        MovementDirection = -transform.right;
    }

    Vector2 transformUp = transform.up;
    Vector2 position = transform.position;

    Vector2 rightRayPosition = new Vector2(transform.position.x + OffSetX, transform.position.y + OffSetY);
    Quaternion rightOffSetAngle = Quaternion.AngleAxis(-RayAngle, new Vector3(0, 0, 1));
    Vector2 rightRayAngle = rightOffSetAngle * Vector2.down ;

    Vector2 leftRayPosition = new Vector2(transform.position.x - OffSetX, transform.position.y + OffSetY);
    Quaternion leftOffSetAngle = Quaternion.AngleAxis(RayAngle, new Vector3(0, 0, 1));
    Vector2 leftRayAngle = leftOffSetAngle * Vector2.down;

    RaycastHit2D rightHit = Physics2D.Raycast(rightRayPosition, rightRayAngle, RayLength, GroundMask);
    RaycastHit2D leftHit = Physics2D.Raycast(leftRayPosition, leftRayAngle, RayLength, GroundMask);

    #region move
    if (rightHit && leftHit)
    {

        Debug.DrawRay(rightRayPosition, rightRayAngle, Color.red, RayDuration);
        Debug.DrawRay(rightRayPosition, rightHit.normal, Color.green, RayDuration);

        Debug.DrawRay(leftRayPosition, leftRayAngle, Color.yellow, RayDuration);
        Debug.DrawRay(leftRayPosition, leftHit.normal, Color.magenta, RayDuration);

        Vector2 averagePoint = (leftHit.point + rightHit.point) / 2;
        Debug.DrawRay(averagePoint, -transform.up, Color.cyan, RayDuration);

        Vector2 averageNormal = (leftHit.normal + rightHit.normal) / 2;
        Debug.DrawRay(averagePoint, averageNormal, Color.cyan, RayDuration);

        Quaternion targetRotation = Quaternion.FromToRotation(Vector3.up, averageNormal);
        Quaternion finalRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, 10);
        transform.rotation = Quaternion.Euler(0, 0, finalRotation.eulerAngles.z);

        transform.position = Vector2.MoveTowards(transform.position, averagePoint + MovementDirection, .15f);
    }
    else
    {
        Debug.Log("What");
    }

```

# Answer
Thanks to DMGregory for the sage advice. I needed to get my vectors into the correct world space coordinates . The working code is below, it needs clean up but it works like a champ.

```
private float RayDuration = 0;
private float RayAngle = .5f;
private float RayLength;
Vector2 MovementDirection;
Vector2 OffSetYVector;
float OffSetY;
float OffSetX = 5f;
int GroundMask = 1 << 8;
RectTransform SpiderRect;

```

void Start() {

```
    SpiderRect = GetComponent<RectTransform>();
    RayLength = SpiderRect.rect.height;
    OffSetY = RayLength;
}

```

private void TouchHeld(CustomEvent customEvent) {

```
    if (Input.mousePosition.x > 400)
    {
        MovementDirection = transform.right;
    }
    else
    {
        MovementDirection = -transform.right;
    }

    Vector2 transformUp = transform.up;
    Vector2 transformRight = transform.right;
    Vector2 position = transform.position;
    OffSetYVector = new Vector2(0, transform.position.y + OffSetY);

    Vector2 rightRayPosition = transform.TransformPoint(new Vector2(OffSetX, OffSetY));
    Quaternion rightOffSetAngle = Quaternion.AngleAxis(-RayAngle, new Vector3(0, 0, 1));
    Vector2 rightRayAngle = rightOffSetAngle * -transformUp;

    Vector2 leftRayPosition = transform.TransformPoint(new Vector2(-OffSetX, OffSetY));
    Quaternion leftOffSetAngle = Quaternion.AngleAxis(RayAngle, new Vector3(0, 0, 1));
    Vector2 leftRayAngle = leftOffSetAngle * -transformUp;

    RaycastHit2D rightHit = Physics2D.Raycast(rightRayPosition, rightRayAngle, RayLength, GroundMask);
    RaycastHit2D leftHit = Physics2D.Raycast(leftRayPosition, leftRayAngle, RayLength, GroundMask);
    #region move
    if (rightHit && leftHit)
    {

        Debug.DrawRay(rightRayPosition, rightRayAngle, Color.red, RayDuration);
        Debug.DrawRay(rightRayPosition, rightHit.normal, Color.green, RayDuration);

        Debug.DrawRay(leftRayPosition, leftRayAngle, Color.yellow, RayDuration);
        Debug.DrawRay(leftRayPosition, leftHit.normal, Color.magenta, RayDuration);

        Vector2 averagePoint = (leftHit.point + rightHit.point) / 2;
        Debug.DrawRay(averagePoint, -transform.up, Color.cyan, RayDuration);

        Vector2 averageNormal = (leftHit.normal + rightHit.normal) / 2;
        Debug.DrawRay(averagePoint, averageNormal, Color.cyan, RayDuration);

        Quaternion targetRotation = Quaternion.FromToRotation(Vector3.up, averageNormal);
        Quaternion finalRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, 10);
        transform.rotation = Quaternion.Euler(0, 0, finalRotation.eulerAngles.z);

        transform.position = Vector2.MoveTowards(transform.position, averagePoint + MovementDirection, .15f);
    }
    else
    {
        Debug.Log("What");
    }
    #endregion

```
> 1 votes

---
Tags: unity, c#, 2d, physics, angles
---


# Question
Title: Read from OpenGL texture to Bitmap in C#
I want to read a texture pixels from texture id (associated with some FBO) to bitmap object in opengl (opentk) in c#
But it throws an exception says:

```
System.AccessViolationException occurred
  HResult=0x80004003
  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
  Source=OpenTK

```

The code:

```
public Bitmap GetTexture(int AttachmentIndex)
        {
            if (AttachmentIndex > fbo_colorBuffer.Count - 1)
                throw new IndexOutOfRangeException();

            Bitmap bitmap = new Bitmap(width, height);
            BitmapData bits = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            BindToRead(ReadBufferMode.ColorAttachment0 + AttachmentIndex);
            GL.ReadPixels(0, 0, width, height, OpenTK.Graphics.OpenGL.PixelFormat.Rgb, PixelType.Float, bits.Scan0);
            bitmap.UnlockBits(bits);

            return bitmap;
        }

public void BindToRead(ReadBufferMode Mode)
        {
            GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, fbo_id);
            GL.ReadBuffer(Mode);
        }

```

# Answer
**You're attempting to write past the end of a buffer**.

First of all, you're specifying your bitmap with `PixelFormat.Format32bppRgb` \- this is a 32 bit-per-pixel format with 8 bits for each of R, G and B and the remaining 8 unused. Documentation link.

Then when you do the readback you read as `PixelFormat.Rgb` and `PixelType.Float`. This is a 96 bit-per-pixel format with each of R, G and B being a 32-bit float.

So the image data you read back overruns the buffer you have specified to read back into.

To fix, change one of them to use the same format as the other.
> 0 votes

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


title: Why is this null?

text:
# Question
Title: Why is this null?
Every enemy object has an ItemDrops script and every item has a DisplayItemLabel script.

In SpawnItem(), you'll see that I'm trying to set itemNameText.text to "hello"; I'm using a string literal to eliminate some variables, but eventually I'd do something like SpawnItem(Item item) and set itemNameText.text to item.itemName;

The Problem:

In the SpawnItem function, When I debug the variable 'drop', I get the item game object. When I debug the variable 'displayItemLabel', I get the DisplayItemLabel component attached to drop. No issues here. But, when I debug 'displayItemLabel.itemNameText', I get Null. Why is this happening? I've commented out the line where I set the text in SpawnItem, but I get the exception regardless. I've also tried rearranging the order of the lines in SpawnItem and I still get the exception. I've tried removing the SetActive(false) stuff in DisplayItemLabel, and the same problem occurs. Lastly, I've tried to set the reference of ItemNameText more directly (without a dependency on itemLabel). I'm not really sure where to look next.

Attached to each Enemy game object:

```
public class ItemDrops : MonoBehaviour
{
    public Transform itemPrefab;
    private EnemyHealth enemyHealth;

    private float originToGroundDistance;
    private Vector3 offset;

    private bool itemDropped;
    private bool numberGenerated;
    private float randomNumber;

    private ItemData itemData;
    public string nameOfDroppedItem;

    void Start()
    {
        enemyHealth = GetComponent<EnemyHealth>();

        itemData = GameObject.Find("Item Manager").GetComponent<ItemData>();
    }

    void Update()
    {
        //Initialized in Update instead of Start because enemy floats to 1.083333 on the Y-axis some time after Start
        originToGroundDistance = transform.position.y - 0.25f;
        offset = new Vector3(0f, originToGroundDistance, 0f);

        if (enemyHealth.isDead && !itemDropped)
        {
            if (!numberGenerated)
            {
                RandomNumberGenerator();

                //Debug.Log(randomNumber);

                if (randomNumber < 1)
                {
                    SpawnItem();
                }
            }
        }
    }

    private void RandomNumberGenerator()
    {
        numberGenerated = true;

        randomNumber = Random.value;
    }

    private void SpawnItem()
    {
        itemDropped = true;

        GameObject drop = Instantiate(itemPrefab, transform.position - offset, Quaternion.identity).gameObject;
        DisplayItemLabel displayItemLabel = drop.GetComponent<DisplayItemLabel>();

        Debug.Log(displayItemLabel); // SHOWS DisplayItemLabel SCRIPT
        Debug.Log(displayItemLabel.itemNameText); // BUT THIS IS NULL
        Debug.Log(displayItemLabel.itemNameText.text); // NullReferenceException

        //displayItemLabel.itemNameText.text = "hello";
    }
}

```

Attached to each Item game object:

```
public class DisplayItemLabel : MonoBehaviour
{
    private GameObject itemLabel;
    public Text itemNameText;

    void Start()
    {
        itemLabel = transform.Find("Canvas/Item Label").gameObject;
        itemNameText = transform.Find("Canvas/Item Label/Item Name Text").gameObject.GetComponent<Text>();
        //itemNameText = itemLabel.GetComponentInChildren<Text>();

        itemLabel.SetActive(false);
    }

    void Update()
    {
        ClampLabelToItem();
    }

    private void ClampLabelToItem()
    {
        Vector3 offset = new Vector3(0f, 16f, 0f);

        Vector3 desiredPosition = Camera.main.WorldToScreenPoint(transform.position) + offset;
        itemLabel.transform.position = desiredPosition;

        itemLabel.SetActive(true);
    }
}

```

# Answer
Because `Start()` is queued for execution, instead of being executed during `Instantiate`. If you want an initialization function to run during `Instantiate`, you need to use `Awake()`. And if I recall correctly, even `Awake` will only run if the gameObject is instantiated in an enabled state. Or you could write your own initialization function, which you call manually after `Instantiate`.

Personally, I sometimes to work around this by using a Factory and an Object Pool, and thus initialize objects without relying on Unity's Awake/Enable/Start functions.
> 2 votes

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


# Question
Title: Picking a 2D Box Collider with the mouse in Unity
I have a scene with a bunch of 2D doors that have 2d Box Colliders (no trigger) on them and that live on a Canvas. I would like to be able to click on them with the mouse, but have had no luck.

Following this earlier topic: (2D) Detect mouse click on object with no script attached , I did the following:

```
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity);
        if (hit)
        {
            Debug.Log(hit.collider.gameObject.name);
        }
    }

```

However, (hit) is always null. I have no RigidBody2D objects in my scene, because I only need mouse selection, not any interaction between objects.

In the inspector I the green box collider but clicking within it in the scene (not the inspector, obviously) runs the MouseButtonDown() code but still no Raycast hit.

What else could I be missing?

To reduce this to its simplest, you can do the following:

* Create a new 2D scene with a canvas
* Add two 100x100 Images to the Canvas
* Add a Boxcolllider2D to each image
* Now what script is required to detect mouse clicks within them?

# Answer
> 1 votes
You should create Buttons instead of Images if you are working in Canvas. There you can assign image and events.

# Answer
> 1 votes
I am not sure what is wrong with your script as it seems fine, are you sure you have setup your images properly? I have the following setup in my inspector with the following code and it works.

```
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity);
        if (hit)
        {
            Debug.Log(hit.collider.gameObject.name);
        }
    }
}

```

Another solution is to put a component on each door and inherit from IPointerClick\Down\UpHandler

Like this:

```
using UnityEngine;
using UnityEngine.EventSystems;

public class DoorViewController : MonoBehaviour, IPointerClickHandler
{
    public void OnPointerClick(PointerEventData eventData)
    {
        Debug.Log("Clicked on: " + gameObject.name);
    }
}

```

For more advanced things you might want to look at:

IPointerInputModule - I would link but the rules of this site are very draconian.

# Answer
> 0 votes
If you are open to having a script on the game object using the built in method OnMouseDown() works great to detect when clicked or tapped.

```
void OnMouseDown()
{
    // do stuff
}

```

---
Tags: unity, 2d, collision-detection
---


# Question
Title: Unity detecting edge of mesh or end of mesh
I'm trying to create procedurally generated tiles and I've reached a point where I need to figure out the boundaries of the mesh or the outer vertices of the mesh.

```
    RaycastHit hit;
    if (Physics.Raycast(bound[ i ].v2, Vector3.forward, out hit)) {
    if (hit.distance > 2) {

```

I've tried raycasting all the vertices, but still can't get the vertices of the edge. The mesh does have a collider. any help on how i would go about this is appreciated, Thanks.

# Answer
> 1 votes
Have you seen this post about getting the outer/edge vertices from a Mesh? http://answers.unity3d.com/questions/1019436/get-outeredge-vertices-c.html

# Answer
> 0 votes
If your mesh will always be a rectangle you could use the MeshCollider, or more specifically `MeshCollider.bounds.extents` but that will only return 1/2 the width, length and height, not the vertices.

Depending on what you need to accomplish or the environment you are creating, this may work. If not, let us know what you plan on doing with the data after you get it and that may help clear things up.

---
Tags: unity, c#, 3d, procedural-generation, mesh
---


# Question
Title: Import Blender model into Unity with Textures
I tried a very straightforward import of the Monk model from https://opengameart.org/content/monk into Unity 5.6.1f1, and ended up with no color/texture on the model. Why?

# Answer
> 1 votes
Apparently Blender has numerous ways of associating textures with meshes. This particular model had UV Maps associated, but had assigned the textures some other way rather than via the UV map.

1. I unpacked all the images from the blend file into external files using the External Data menu under the File menu.
2. I make sure those are in the Textures directory under the location where I will import the blend file in Unity.
3. I went into Edit mode on each component of the model in Blender (3 main components: Hair, Head, Body), selected all the faces, and changed the selected image to the appropriate value in the UV Map editor, even if it looked like it was already correct for the head.
4. Save the Blend file.

Then when I import the model into Unity, the textures are already assigned. All I have left to do is assign the occlusion and normal maps.

I still think Unity could do a much better job of importing Blend files. For one thing, it'd be nice it there were a warning message about the textures being packed if it doesn't want to import packed textures. And for another, it'd be nice if it could pick up textures that were associated with a mesh regardless of whether it came in via the UV map or some other association. And it would be nice if it could support the normal maps and occlusion maps associated with the mesh.

# Answer
> 2 votes
Remember the steps (sequence should be followed):

1. First Import your texture (copy) in your unity Project
2. Then, Import your model (copy) in you unity project.

Remember what the **unity official docs (HOWTO-ImportObjectBlender)** said about blender import requirement Requirements

1. You need to have Blender version 2.60 or later (in some earlier versions of Blender the FBX export was broken).
2. **Textures and diffuse color are not assigned automatically. Manually assign them by dragging the texture onto the mesh in the Scene View in Unity.**

---
Tags: unity, textures, blender, import
---


# Question
Title: How can I prevent cheating in a distributed multiplayer game?
A problem I've been thinking about recently is how it might be possible to create a multiplayer game without a centralised game server.

Is it possible to distribute "server" responsibilities across players? I feel like it would be too easy for modified/hacked clients to change the multiplayer experience, are there any ways around this?

# Answer
For some games it is possible. Take chess, for example. Can you cheat at online chess without the opponent noticing? Cheating at chess is hard, because the game:

1. has no hidden information
2. is deterministic (no randomness involved)
3. is only about making the right decisions. Reflexes or precision don't matter.

When your opponent says they just moved their king from a3 to f1, your game client can recognize that this is an illegal move and reject it. The only possible cheat left is AI assistance (which actually is a serious issue for competitive chess, by the way). But there is really no workaround for that unless you force players into a controlled environment. A while ago I asked a question about how to design a game as AI-unfriendly as possible, but didn't get really good answers. So I am not going to cover this issue.

While there is no good way to get around the third requirement, you can get around the first and second by using some applied cryptography.

Take battleship, for example. How can you verify that your opponent didn't cheat by lying about their fleet layout? Have each player calculate a cryptographic hash of their layout at the start of the game and send it to the opponent. At the end of the game when the complete layout of the enemy is revealed, you can verify if the hash matches the layout. You might want to add some bytes of random data to the data from which the hashes are calculated (also to be revealed at the end of the game) to prevent the opponent from brute-forcing your fleet layout when you've reached the endgame and the number of possible positions is low enough to allow that.

The same method can also be used if you want some randomness in your game, because randomness is essentially hiding of information from all players.

Before you start the game, have both players create a long list of random bits (more than you will need for the complete game). Use a cryptographically secure RNG seeded from an unpredictable entropy source. Again, have the player hash their lists and exchange the hashes for post-game verification. During the game, use these two lists as one-time pads for each other. When you need a random bit, have each player reveal the next bit from their list, XOR the bits with each other, and use the result. This gets you a random number which both players contributed to but none could predict. Again, at the end of the game, send your complete list to the opponent so they can verify the hash and confirm you didn't lie during the game.

---

But how do you deal with players you catch cheating?

In a game with more than two players which follows above guidelines, everyone knows when a player cheated. So they can simply all disconnect from that player and continue the game without them. There is no practical difference between someone ragequitting because they can't stand losing or being kicked for cheating.

But what about a two-player game where the clients can't agree on who cheated? This is actually not unlikely to happen if both clients aren't aware that they are playing different versions of the game. This is essentially equivalent to a rule dispute in a tabletop game. If you can't come to an agreement, the only solution is to abort the game and call it inconclusive. Again, equivalent to a ragequit. Who is the quitter from your perspective depends on how guilty you feel.
> 4 votes

---
Tags: multiplayer, anti-cheat, peer-to-peer
---


title: Solid outline around block

text:
# Question
Title: Solid outline around block
I'm creating a minecraft clone (for practice), and I'm trying to implement a feature in which the block that the player is looking at has a block outline. The way I do this is just by creating a GL\_LINES mesh that covers the edges of the block, and then translating it to the block position. I'm using the LibGDX framework to do this - the outline ends up producing a ModelInstance.

It partially works, but this is what it looks like:

As you can see, some of the pixels are getting rendered, but some aren't. My theory is that this is because of the depth buffer - because the line is intersecting with the face, some of the pixels don't get rendered. So my question is, how can I ensure that the outline gets rendered solidly?

# Answer
Well, I think that is because the lines are exactly where the faces are. Try making the box of lines a fraction bigger than the block itself.
> 1 votes

---
Tags: libgdx, graphics, outline
---


# Question
Title: Why does my line disappear against a white image?
A GIF is worth a 10002 words:

Why does the rainbow-colored line disappear when it is displayed against the white image?

A few more details: The line is a Vectrosity line that is rendered using Unity's built-in Unlit/Transparent shader. The white square in the background is a RawImage that displays a pure white PNG texture. The line is closer to the camera in the scene, but it is disappearing when it is rendered on top of the white RawImage behind it.

If I change my line's material to use the Unlit/Color shader, the line shows up as expected:

I'm using Unity 5.6.1f1.

# Answer
> 2 votes
It should be because the alpha channel of the line is set to 0, so the `Unlit/Transparent` shader effectively makes it invisible when there're other objects rendered behind it.

You should see it if you select the `Unlit/Texture` shader, or if you set the Alpha channel of the line to 1.

---
Tags: unity, shaders, textures, rendering, materials
---