# Question
Title: How do you develop the model matrix for an object?
This might be a misunderstanding on my part but let me give you my superficial understanding of Model-View-Projection pipeline and different coordinate systems. Then I will ask a question.

As we know, we might have many models in our scene. You might load vertex attributes for each using a model loader etc. When you load the coordinates, these are in *object space* or *model space*. So they describe the object wrt a local frame. We use model matrix to transform this to world space shared by all models, a global frame let's say.

After this, we are in a huge world space. We might think this as an endless *Euclidean 3D space*. Here coordinates may have any value. Somewhere in the world, we have a camera and these objects in the world have different coordinates wrt. camera's frame. This is where *view matrix* comes into play. After applying this transformation, coordinates are in view space. In the OpenGl world, we think like the camera lies at the origin. We specify a view frustum and we do (actually delay) the clipping etc.

After this we apply *projection matrix* and transform this viewing pyramid into a cube that spans `[-1, 1]` in all the axes. This is homogeneous coordinates and we do perspective divide, clipping etc. This is my view of the whole thing, roughly.

The question is, we have routines to generate view and projection transformations given the required parameters. But how about the model matrix? For example, I load a bunny model stored in an OBJ file. It might have a coordinate value like `(32.657, -12.545, 8.444)`. In which space are these coordinates? If it's in the model space, what is the best strategy to develop a model matrix to put this object into world space? Another OBJ model of same bunny might have coordinates all lying in `[-1, 1]` range for example. Does this mean this object is already transformed with an MVP? Are those model matrices related to only skeletal, hierarchical models?

I think this is a strange question so I don't see this really mentioned anywhere. But this bugs me, leaves me with a superficial understanding of whole matter. I want to truly understand.

# Answer
Your understanding is correct:

* The *model* matrix moves from model space to world space.
* The *view* matrix moves from world space to view space.
* The *projection* matrix moves from view space to clip space.

> In which space are these coordinates?

Coordinates in model files are in model (or "object") space.

> If it's in the model space, what is the best strategy to develop a model matrix to put this object into world space?

You do this when you decide you're going to render a particular *instance* of the model somewhere, oriented and scaled in some way. In the general sense you create a *translation matrix* based on the X, Y and Z in world space you want the object to appear, a *rotation matrix* based on how you want to orient the object in the world and a *scaling matrix* based on how you want to scale the object (if at all) and concatenate all three of these as appropriate via matrix multiplication.

You will generally create one such model matrix *per instance* you're going to draw in the world (whereas you'd probably create the view and projection matrices only once per frame).

> Another OBJ model of same bunny might have coordinates all lying in \[-1, 1\] range for example. Does this mean this object is already transformed with an MVP?

No. It just means it's smaller (unless of course you choose to *assume* it's already transformed, which you can do, but that is of limited practical use).

From your commentary:

> For example, to develop a translation matrix I need to look at object space coordinates, then I could say, "oh I can trasnlate x-axis by -20, that could put this object here". But this assumes I should be fully aware of the object space coordinates of each model.

No, it doesn't assume that. What is assumed in the transition from object to world space is that the you "place" the origin of the object in model space at the desired point in the world; that the model was authored so that the object-space coordinate (0,0,0) is a reasonable placement point for the object. For a humanoid character, for example, you might expect that (0,0,0) is centered under the model's feet.

The three basic transformation matrices are "about the origin," so (for example) a translation of (X, Y, Z) in a model matrix will put the point at (0,0,0) in object space at (X, Y, Z) in world space.

If this assumption that the model is built around a reasonable (0,0,0) point is not true... if for example somebody created a model of a human character and the feet were at (-43, 200, 2) for some reason.. then yes, you'd need to know this offset from the actual model space origin to the placement point. There is no way to algorithmically determine this offset for arbitrary geometry, so any content pipeline that is building models in this (*very strange*) fashion will generally either also make sure to export that offset in some form, or possibly only be used in a constrained set of circumstances where additional context allows one to algorithmically determine the offset. This is uncommon, however, and you're more likely to see models built around a reasonable origin for placement.
> 1 votes

# Answer
When a model was created in 3d space , the vertex position were defined in Local space initially, but most DCC app will associate a transform node to the shape(use to generate the vertex in local space in maya) of the model , user can move the model in world space by it's transform node, the transform node is a 4\*4 matrix behind , also called model matrix , the final position of the model in world space is it's local position multiply by model matrix. If you export this transformd model to a new app such like unity ,it was in local space initially (Although it was not in the orgin ), all the vertex are live in the local space, The same as maya or other DCC, unity will assosiate a transform component to the model, transform component represents the model matrix of the model ,the final vertex position in the scene is the local coordinates multiply by the model matrix. When you use load the geometry into shader, it only load the local coordinates of the vertex ,so you should multiply the model matrix(reprent transform component) to the model manually to convert it into unity world space coordinates
> 0 votes

---
Tags: opengl, transformation
---


# Question
Title: How do you upload an AudioClip to a server in Unity?
My current approach is to take an AudioClip, turn it into a byte array, then put it into an UploadHandler, attached to a UnityWebRequest, to send a POST request to a server.

Right now, when I pass through an AudioClip to my ConvertAudioToByteArray() function I essentially get back a byte array full of NULL characters. This seems to happen when I use the GetData method on the clip parameter, as a bunch of 0s print out when I Debug.Log the foreach loop of floatArrayOfClip. When I send out a post request to my dev server I get a ProtocolError on the client side.

I believe I have tested everything. The audioClip argument is a microphone recording and is working correctly. Dev server is working correctly. The program is connecting successfully to the dev server.

Using Unity 2021.3.

Thanks in advance.

=======

EDIT: It looks like the GetData method returns an array full of NULL characters if the AudioClip it is used on is compressed. Microphone recordings in unity are .ogg (compressed audio) format apparently.

Is there a way to get the float values out of an AudioClip without using I/O operations or the GetData method?

=======

```
public void initiateCoroutine(AudioClip audioClip)
{
    StartCoroutine(postRequest(audioClip));
}

IEnumerator postRequest(AudioClip audioClip)
{
    // convert audio to byte array
    byte[] byteArray = ConvertAudioToByteArray(audioClip);

    // create UWW and handler, and attach handler to UWW
    UnityWebRequest uwr = new UnityWebRequest("-CORRECT URI-", "POST");
    UploadHandler uploader = new UploadHandlerRaw(byteArray);
    uwr.uploadHandler = uploader;

    yield return uwr.SendWebRequest();

    if (uwr.result == UnityWebRequest.Result.ConnectionError)
    {
        Debug.Log(uwr.error);
    }
    else if (uwr.result == UnityWebRequest.Result.ProtocolError)
    {
        Debug.Log(uwr.error);
        Debug.Log("PROTOCOL");
    }
    else if (uwr.result == UnityWebRequest.Result.DataProcessingError)
    {
        Debug.Log(uwr.error);
        Debug.Log("PROCESSING");
    }
    else
    {
        Debug.Log(uwr.result);
        Debug.Log(uwr.downloadHandler.text);
    }
}

private static byte[] ConvertAudioToByteArray(AudioClip clip)
{
    // get user recording and convert user recording into a float array
    var floatArrayOfAudioClip = new float[clip.samples];
    clip.GetData(floatArrayOfAudioClip, 0);

    // Create buffer stream
    MemoryStream stream = new MemoryStream();
    BinaryWriter writer = new BinaryWriter(stream);

    // Populate audio clip floats into buffer stream
    foreach (var sample in floatArrayOfAudioClip)
    {
        writer.Write(sample);
    }

    byte[] bytes = stream.ToArray();

    return bytes;
 }

```

# Answer
> 1 votes
After testing, your code for obtaining byte arrays is valid, and the problem may be in the place of uploading data.

This byte array may not be all `0`. Due to the sample format, there is a high probability that a section of the array (for example, the first 500) will have a value of `0`. Maybe you use a debugging tool to view it and mistakenly think it is all `0`.

You can use the following code to detect the proportion of `0` in the array:

```
byte[] bytes = stream.ToArray();
CountZero(bytes);
...

private static void CountZero<T>(T[] array) where T : IEquatable<T>
{
    var count = 0;
    foreach (var item in array)
    {
        if (item.Equals(default(T)))
        {
            count++;
        }
    }
    Debug.Log(1f * count / array.Length);
}

```

From my testing, this scale value decreases over time as expected, starting from the recording.

UnityWebRequest.Result.ProtocolError shows that it is an error as defined by the connection protocol. For the HTTP protocol, response codes `4xx` and `5xx` mean errors.

You can find the specific error code with UnityWebRequest.responseCode.

And find the meaning of the code on wiki/List\_of\_HTTP\_status\_codes.

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


# Question
Title: Easing curve, find next position given current position and delta time?
I'm want to animate an object using an ease out curve, where it moves fast at time `alpha = 0` and slow at `alpha = 1` from position `y1` to `y2`.

However, the object may start at an arbitrary `y` position with an unknown `alpha`, and I need it to follow the same curve regardless.

In Unreal Engine there is this relevant built-in helper function `InterpEaseOut(const T& y1, const T& y2, float Alpha, float Exp)`, but I don't have the starting `alpha` value. (Note that I don't need specifically this curve formula.)

How can I solve this?

# Answer
> 0 votes
So long as y1 and y2 are distinct, you can recover alpha with an inverse lerp:

$$\begin{align} y &= (1 - \alpha) y\_1 + \alpha * y\_2\\ y &= y\_1 + \alpha (y\_2 - y\_1)\\ y - y\_1 &= \alpha (y\_2 - y\_1)\\ \frac {y - y\_1 } {y\_2 - y\_1} = \alpha \end{align}$$

This gives us a linear measure of progress from y1 (0% = 0) to y2 (100% = 1). Note that this does not yet factor in the non-linear relationship between time and position, this is just measuring what ratio of the distance we've covered in space.

We can then apply any easing function we want to it. Let's say we use this easing formula:

$$\alpha = 1 - (1 - \frac t {\text{duration}})^n$$

We can take its inverse to recover the time value at which we would reach this value for alpha:

$$\begin{align} \alpha &= 1 - (1 - \frac t {\text{duration}})^n\\ 1 - \alpha &= (1 - \frac t {\text{duration}})^n\\ (1 - \alpha)^{\frac 1 n} &= 1 - \frac t {\text{duration}}\\ 1 - (1 - \alpha)^{\frac 1 n} &= \frac t {\text{duration}}\\ \text{duration} \cdot \left(1 - (1 - \alpha)^{\frac 1 n}\right) &= t \end{align}$$

Now you can add your time delta to t (clamp it so it does not exceed the total ease duration), and run this back through your easing formula to get the alpha value for the next position along the curve.

---
Tags: mathematics, animation, easing
---


# Question
Title: AStar taking care of collisions for a rectangle
How can I explore a path with A\* (or another) by taking care of a rectangle collision ?

I have a 2d map, where I know for each coordinate if it is an obstacle :

For example, dark tiles are not traversable :

I use A\* algorithm to find path, where for a given point, all around successor are possible with a variable cost. There is a visual example (game is top view):

How can I make a A\* (or other) algorithm taking care of obstacles for a (for example) vehicle ?. In the previous image example, a man can use this path, but tank. should not

# Answer
> 2 votes
You can generate a different graph for a different kind of unit.

For example a graph for humans, a graph for land vehicles, a graph for water vehicles, and so on.

And there is no change to the algorithm. The difference is that each graph is created considering the space and the type of terrain that the kind of unit requires.

And yes, that means it would be convenient to have some standard spacing so you don't have to create graph for each individual unit type, but you can reuse them for similar unit types.

*For clarity: A square grid is a kind of graph, and this approach is not limited to square grids.*

---
Tags: path-finding
---


# Question
Title: How to change from gameplay camera to menu camera when colliding with a game object?
I want to know how to change which camera is outputting to the screen when colliding with another game object in Unity.

I'm making platformer, and at the end of the level I want to switch from the player camera to the game menu camera (since they're in the same scene).

# Answer
> 1 votes
Here's a more flexible way to do it with a reusable, general purpose trigger script:

```
[RequireComponent(typeof(Collider2D))]
public class Trigger2DEvents : MonoBehaviour {
    [SerializeField] private UnityEvent onTriggerEnter;
    [SerializeField] private UnityEvent onTriggerExit;

    private void Awake() {
        var collider = GetComponent<Collider2D>();
        Assert.IsNotNull(collider);
        Assert.IsTrue(collider.isTrigger);
    }

    private void OnTriggerEnter2D(Collider2D collision) {
        onTriggerEnter.Invoke();
    }

    private void OnTriggerExit2D(Collider2D collision) {
        onTriggerExit.Invoke();
    }
}

```

Attach that script to a GameObject with a 2D collider with "is trigger" selected. Then add two event listeners to the "On Trigger Enter" event - one that disables the game camera, and one that enables the menu camera.

You can reuse this component to set up other game events that are activated by triggers, without having to write code each time.

# Answer
> 0 votes
Make an empty game object and give it a 2D collider with "Is Trigger" checked, so it can detect when an object enters its area without making it bounce off.

Add a script like this to that object:

```
public class CameraTrigger : MonoBehaviour {

    public Camera cameraToActivate;

    // Delete the two "2D" instances if your platformer is 3D.
    void OnTriggerEnter2D(Collider2D other) {
        // You can add code here to check what "other" object
        // entered our trigger, and abort if it's not the right one.
        // But a better solution is to put this trigger volume on
        // a physics layer that collides *only* with the right object(s).

        // Turn off the currently active main camera
        // (first enabled camera in scene with the "MainCamera" tag)
        Camera.main.gameObject.SetActive(false);

        // Turn on the designated camera set in the inspector.
        cameraToActivate.gameObject.SetActive(true);
    }
}

```

Populate the `cameraToActivate` variable to point to the menu camera you want to turn on.

Make sure the camera you want to turn off has the "MainCamera" tag.

To switch back, do the opposite: use `SetActive()` to turn the menu camera off, and the gameplay/player camera back on.

To make sure you don't have two cameras active at once, you can start the game with one of them inactive (untick the checkbox at the top of the inspector when selecting the camera object in the scene), or add a method to auto-disable one on start-up:

```
void Start() { cameraToActivate.gameObject.SetActive(false); }

```

Basics like this are covered in almost every beginner Unity tutorial, so I recommend working your way through a few more introductory guides to ensure you have the fundamentals down.

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


# Question
Title: Whats the best way to handle large amounts of animations in unity for unique units?
So atm im working on a game where we need many different units each with their own animation set. Is there a way to automate this process? or do we have to create blend trees manually with each animation set. Or can you populate blend trees programatically by using resources folder and doing a prefix keeping the animations with a uniform name. Maybe im overthinking this lol.

# Answer
Using Animator Override Controller, you can easily swap animations without the need of creating a new animators.
> 1 votes

# Answer
According to the comments, all those automatically generated animator controllers would use the same logic but with different animations.

In that case it's a good idea to just use a single animator controller and instead create an Animator Override Controller for each unit.

Animator override controllers are assets which reference an existing animator controller, and replace the actions of individual states with different ones. You can then go to the animator of your unit and assign that override controller to the Animator just like you would assign a real animator controller.

The animator will then use the logic of the animator controller referenced by the override controller, but use the actions defined in the override controller.
> 1 votes

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


# Question
Title: Detect collision occurring on a parent CharacterController from a child object
I'm creating an audio script for my character and it changes the sounds based on the textures it is walking on.

Said character uses a Character Controller component from Unity and I thought of using it to detect collision using `ControllerColliderHit`. However, my char has a parent that has it while the character itself that has the animator doesn't.

How can I call `ControllerColliderHit` using the parent `CharacterController`? Or if there's another better way of doing this, I would appreciate it.

# Answer
Use a Unity Event to relay the message anywhere you want.

```
using UnityEngine.Events;

public class ControllerEventRelay : MonoBehaviour {

    public UnityEvent<ControllerColliderHit> onColliderHit;

    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        onColliderHit?.Invoke(hit);
    }
}

```

Put this script on the parent that has the character controller, then use the event to wire it up to any function accepting a `ControllerColliderHit` argument on any component on any object you like. You can even wire up multiple listeners to all respond to each individual collision event.

It looks like this in the Inspector:

Click the "+" button to add a new listener, and select the object that has the function you want to invoke. Then select the component that has that function from the drop-down, and select the function from the "Dynamic ControllerColliderHit" section at the top. Any `public` instance method accepting a `ControllerColliderHit` as its sole argument will show up as an option to choose here.

You can also add listeners in code:

```
onColliderHit.AddListener(functionToCall);

```
> 1 votes

---
Tags: unity, c#, physics, character-controller
---


# Question
Title: I can only access the latest instantiated clone. The script only works with the latest instance
I tried to implement a way of attacking. Fire the spear, then retract it. Just like Thor's hammer. But when I fire multiple spears, I can only retract the latest fired one. I don't know what the insight problem is here. Please help. And if there's any better solution to realize this mechanic would be great.

The code on hand for firing

```
public class retractArrow : MonoBehaviour
{
    public Transform cam;
    public Transform launchPoint;
    public Transform playerPos;
    public bool isRetracting;
    public float throwPower;
    public GameObject arrow;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Throw();
        }
        else if (Input.GetKeyDown(KeyCode.G))
        {
            isRetracting = true;
        }
        else if (Input.GetKeyUp(KeyCode.G))
        {
            isRetracting = false;
        }
    }

    private void FixedUpdate()
    {
        if (isRetracting)
        {
            RA.instance.Retract(playerPos);
        }
    }

    private void Throw()
    {
        GameObject projectile = Instantiate(arrow, launchPoint.position, cam.rotation);
        Rigidbody rb = projectile.GetComponent<Rigidbody>();
        Vector3 forceDirection = cam.transform.forward;

        RaycastHit hit1;
        Physics.Raycast(cam.position, cam.forward, out hit1, 500f);
        forceDirection = (hit1.point - launchPoint.position).normalized;
        rb.AddForce(forceDirection * throwPower, ForceMode.Impulse);
    }
}

```

The code on the spear to retract:

```
public class RA : MonoBehaviour
{
    public Rigidbody rb;
    public bool isRetracting;
    public float retractPower;
    public static RA instance;

    // Start is called before the first frame update
    void Start()
    {
        instance = this;
        rb = GetComponent<Rigidbody>();
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            Destroy(gameObject);
        }
    }

    public void Retract(Transform playerPos)
    {
        Vector3 directionTOhand = playerPos.position - transform.position;
        rb.velocity = (directionTOhand.normalized * retractPower);
    }
}

```

# Answer
> 1 votes
The reason you can only retract the latest spear fired is that you're only referencing the latest instantiated one:

```
public static RA instance;

```

A static field belongs to the type itself (here, `RA`) rather than to a specific object (each spear). This means there's one and only one `instance` variable in your `RA` class, regardless of the number of spears instantiated.

Every time you instantiate a spear, `instance` references to it, losing its previous value (i.e. a reference to the second-to-last spear instantiated).

---

Since *your character* is throwing spears, it would be a good idea to also delegate it to manage how many spears are there to be retracted. You can do so by tracking the thrown spears using a stack data structure:

* The last spear to be thrown is the first one to be retracted.
* Destroyed spears can be removed from the stack (they no longer exist).

Implementation of a stack can be whatever you see fits your needs. For example, it could be a List where you always add to the end (when throwing) and remove from the end (when retracting), while removing at any position in case of destroyed spears.

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


# Question
Title: Change key setting from qwerty to azerty in Unity
How can I change the default key for walking with the player in Unity. At this moment I can do this with `A`, `W`, `D` and `S` *(or something)*. But because I work with an azerty keyboard, I'll change it to `Z`, `Q`, `S` and `D`. How can I do this (only for the game)?

# Answer
In the editor choose Edit → Project Settings → Input and change there the size of array or just change the values.
> 3 votes

# Answer
To switch to AZERTY keyboard:

### Input Manager

Unity -\> Edit -\> Project Settings -\> Input Manager

* Horizontal: "q" instead of "a"
* Vertical: "z" instead of "w"

### Shortcuts

* Unity -\> Edit -\> Shortcuts -\> 3D Viewport: choose Forward Z, Left Q, Down A
> 2 votes

---
Tags: unity, keyboard
---


# Question
Title: How can I calculate the translation used for rotating an object with a quaternion in Unity, to use for OpenGL?
In Unity, whenever I rotate an object, it also performs a translation. If I simply try to draw a quad with the quaternion used in Unity, it appears off because of that missing translation unity applies. I can 'replicate' it by performing each step in openGL in the same order that Unity does:

* scale first,
* (translation offset)
* rotate Z
* (translation offset)
* rotate X
* (translation offset)
* rotate Y
* (translation offset)
* and final translation

My question is, given a quaternion that will be applied to a quad to rotate it, how can I also calculate this final translation that needs to be applied to the quad to mimic the behavior exhibited in Unity? Apologies if my methodology, terminology isn't the best. I welcome any advice and filling of knowledge gaps I might be displaying.

## Examples:

In Unity, I simply change the position / scale / rotation in editor. Values for rotation displayed are simply Euler angles like how unity represents them in the editor.

(Notice the Y rotation before and after applying a y 290 degree Euler on it)

\[

This raylib (wrapping OpenGL calls) replicates the behavior perfectly

```
void Draw3DBillboardRecUnity(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector2 size, Vector3 eulerAngles, Vector3 scale, Color tint) {
    rlPushMatrix();

       Vector3 camPos = camera.position;
       Vector3 camTar = camera.target;
       Vector3 camUp = camera.up;
       // get the camera view matrix
       Matrix mat = MatrixInvert(MatrixLookAt(camPos, camTar, camUp));
       // peel off just the rotation
       Quaternion quat = QuaternionFromMatrix(mat);
       mat = QuaternionToMatrix(quat);

       // apply just the rotation
       rlMultMatrixf(MatrixToFloat(mat));

       // draw the billboard
       float width = size.x / 2;
       float height = size.y / 2;
       // initial spot
       rlScalef(1, 1, 1);
       rlTranslatef(width, height, 0);

       // null out position experiment
   //    position = Vector3Zero();

       float positionOffsetX = position.x - width * 0.5;
       float positionOffsetY = position.y - height * 0.5;
       Vector3 positionOffsetVector;
       positionOffsetVector.x = positionOffsetX;
       positionOffsetVector.y = positionOffsetY;
       positionOffsetVector.z = position.z;
       Vector3 positionOffsetVectorInverse = Vector3Negate(positionOffsetVector);

       // apply scaling first
       if (vectorAvailable(scale)) {
           rlScalef(scale.x, scale.y, scale.z);
           if (vectorAvailable(position))
               rlTranslatef(positionOffsetVector.x, positionOffsetVector.y, positionOffsetVector.z);
           else
               rlTranslatef(-width, -height, 0);
       }

       // apply rotation
       if (rotVectorAvailable(eulerAngles)) {

           // prepare yourself
           rlTranslatef(positionOffsetVector.x, positionOffsetVector.y, positionOffsetVector.z);

           if (eulerAngles.z > 180) {
               // eh questionable
               rlTranslatef(positionOffsetVector.x, positionOffsetVector.y, positionOffsetVector.z);
               rlRotatef(180 - (eulerAngles.z - 180), 0, 0, 1);
               rlRotatef(180 - (eulerAngles.z - 180), 0, 0, 1);
               rlTranslatef(positionOffsetVectorInverse.x, positionOffsetVectorInverse.y, positionOffsetVectorInverse.z);
           } else {
               rlTranslatef(positionOffsetVector.x, positionOffsetVector.y, positionOffsetVector.z);
               rlRotatef(eulerAngles.z, 0, 0, 1);
               rlTranslatef(positionOffsetVectorInverse.x, positionOffsetVectorInverse.y, positionOffsetVectorInverse.z);
           }

           rlTranslatef(positionOffsetVector.x, positionOffsetVector.y, positionOffsetVector.z);
           rlRotatef(eulerAngles.x, -1, 0, 0);
           rlTranslatef(positionOffsetVectorInverse.x, positionOffsetVectorInverse.y, positionOffsetVectorInverse.z);

           if (eulerAngles.y > 180) {
               // greater than 180
               rlTranslatef(positionOffsetVector.x, positionOffsetVector.y, positionOffsetVector.z);
               rlRotatef(eulerAngles.y, 0, -1, 0);
               rlTranslatef(positionOffsetVectorInverse.x, positionOffsetVectorInverse.y, positionOffsetVectorInverse.z);
           } else {
               // less than 180
               rlTranslatef(positionOffsetVectorInverse.x, positionOffsetVectorInverse.y, positionOffsetVectorInverse.z);
               rlRotatef(eulerAngles.y, 0, -1, 0);
               rlTranslatef(positionOffsetVector.x, positionOffsetVector.y, positionOffsetVector.z);
           }

           // inverse
           rlTranslatef(positionOffsetVectorInverse.x, positionOffsetVectorInverse.y, positionOffsetVectorInverse.z);
       }

       // apply transformation last
       if (vectorAvailable(position)) {
           rlTranslatef(positionOffsetVector.x, positionOffsetVector.y, positionOffsetVector.z);
       }

       Color color = tint;

       rlCheckRenderBatchLimit(6);

       rlSetTexture(texture.id);

       // draw quad
       rlBegin(RL_QUADS);
       rlColor4ub(tint.r, tint.g, tint.b, tint.a);

       rlTexCoord2f((float)source.x / texture.width, (float)(source.y + source.height) / texture.height);
       rlVertex3f(-width, -height, 0);  // Bottom Left Of The Texture and Quad

       rlTexCoord2f((float)(source.x + source.width) / texture.width, (float)(source.y + source.height) / texture.height);
       rlVertex3f(+width, -height, 0);  // Bottom Right Of The Texture and Quad

       rlTexCoord2f((float)(source.x + source.width) / texture.width, (float)source.y / texture.height);
       rlVertex3f(+width, +height, 0);  // Top Right Of The Texture and Quad

       rlTexCoord2f((float)source.x / texture.width, (float)source.y / texture.height);
       rlVertex3f(-width, +height, 0);  // Top Left Of The Texture and Quad

       rlEnd();
       rlSetTexture(0);
       rlPopMatrix();
}

```

With this result:

However this code that simply applies the quaternion, does not.

```
void Draw3DBillboardRecAlmost(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector2 size, Vector3 eulerAngles, Vector3 scale, Color tint) {
    Vector2 sizeRatio = { size.x, size.y };

    Quaternion tQuat = QuaternionFromEuler(eulerAngles.x*DEG2RAD, eulerAngles.y*-DEG2RAD, eulerAngles.z*-DEG2RAD);

    Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up);

    Vector3 right = { matView.m0, matView.m4, matView.m8 };
    Vector3 up = { matView.m1, matView.m5, matView.m9 };

    // rotate both up + right vectors to achieve same effect like unity
    up = Vector3RotateByQuaternion(up, tQuat);
    right = Vector3RotateByQuaternion(right, tQuat);

    Vector3 rightScaled = Vector3Scale(right, sizeRatio.x/2);
    Vector3 upScaled = Vector3Scale(up, sizeRatio.y/2);

    Vector3 p1 = Vector3Add(rightScaled, upScaled);
    Vector3 p2 = Vector3Subtract(rightScaled, upScaled);

    Vector3 topLeft = Vector3Scale(p2, -1);
    Vector3 topRight = p1;
    Vector3 bottomRight = p2;
    Vector3 bottomLeft = Vector3Scale(p1, -1);

    // Translate points to the draw center (position)
    topLeft = Vector3Add(topLeft, position);
    topRight = Vector3Add(topRight, position);
    bottomRight = Vector3Add(bottomRight, position);
    bottomLeft = Vector3Add(bottomLeft, position);

    rlCheckRenderBatchLimit(4);

    rlSetTexture(texture.id);

    rlBegin(RL_QUADS);
        rlColor4ub(tint.r, tint.g, tint.b, tint.a);

        // Bottom-left corner for texture and quad
        rlTexCoord2f((float)source.x/texture.width, (float)source.y/texture.height);
        rlVertex3f(topLeft.x, topLeft.y, topLeft.z);

        // Top-left corner for texture and quad
        rlTexCoord2f((float)source.x/texture.width, (float)(source.y + source.height)/texture.height);
        rlVertex3f(bottomLeft.x, bottomLeft.y, bottomLeft.z);

        // Top-right corner for texture and quad
        rlTexCoord2f((float)(source.x + source.width)/texture.width, (float)(source.y + source.height)/texture.height);
        rlVertex3f(bottomRight.x, bottomRight.y, bottomRight.z);

        // Bottom-right corner for texture and quad
        rlTexCoord2f((float)(source.x + source.width)/texture.width, (float)source.y/texture.height);
        rlVertex3f(topRight.x, topRight.y, topRight.z);
    rlEnd();

    rlSetTexture(0);
}

```

With this result (notice it missing the translation)

How can I get the below code to work like the above test case?

# Answer
You are not drawing a built-in Unity Quad (a `Mesh` drawn with a `MeshRenderer`, whose pivot is at its center). You are drawing a `Sprite` with a `SpriteRenderer`. This terminology is important - you've waited this long for an answer because you used words that describe a completely different problem.

That `Sprite` has its pivot placed somewhere other than the center of the shape - you can inspect this in the Sprite Editor to verify this.

This is being masked because in you've configured your Scene View to show the hot point in the center of the shape, rather than at the true location of the pivot. (This would have been easier to spot if you hadn't cropped that setting out of your screenshot) We can't see where the pivot of the sprite actually is in these screenshots, so we have to infer it for now. You can change this setting in the top-left of the Scene View tab:

The pivot determines the object's local origin point - the point whose local coordinates are (0, 0, 0), and whose world coordinates are `transform.position`. That's the point the object rotates around when you change its Euler angles. Here that origin is at -2.42 on the x, somewhere around the left edge of the visible frame. So when we rotate around that point, it swings left like a door opening on a hinge at the left side of the screen, instead of pirouetting in the middle of the screen.

There's still no translation being applied. The sprite's local origin, its pivot, is staying where it always was.

Your raylib code does not replicate this off-center pivot. You construct your quad symmetrically: `topLeft` is -1 * `bottomRight` and similarly for `topRight` and `bottomLeft`. So you've placed the pivot, the local origin, in the center of the quad. It's that mismatch that causes the difference in behaviour you're observing.

You can instead construct your quad in Raylib something like this:

```
    up = Vector3RotateByQuaternion(up, tQuat);
    right = Vector3RotateByQuaternion(right, tQuat);

    // No division by 2 - we'll use these vectors at their full width/height size.
    Vector3 rightScaled = Vector3Scale(right, sizeRatio.x);
    Vector3 upScaled = Vector3Scale(up, sizeRatio.y);

    Vector3 topLeft = upScaled;
    Vector3 topRight = Vector3Add(rightScaled, upScaled);
    Vector3 bottomRight = rightScaled;
    Vector3 bottomLeft = {0, 0, 0};

    // Translate points to the pivot point (position)
    topLeft = Vector3Add(topLeft, position);
    topRight = Vector3Add(topRight, position);
    bottomRight = Vector3Add(bottomRight, position);
    bottomLeft = Vector3Add(bottomLeft, position);

```

Here we've put the local origin - the pivot - on the bottom-left corner. So as you rotate, the left edge won't move, serving as the hinge. You can accomplish intermediate effects by sliding all four points by some multiple of `right`.
> 0 votes

---
Tags: unity, opengl, quaternion
---


title: XNA Rotate Vector2 around Origin

text:
# Question
Title: XNA Rotate Vector2 around Origin
I have a Rectangle and a Vector2 position, my sprite is being drawn at this position. The rectangle is meant to be a collision system with the cursor, when I rotate my sprite around the origin and stuff in a draw call

```
public virtual void Draw(SpriteBatch spriteBatch)
{
    spriteBatch.Draw(texture, position, null, Color.White, rot, Origin, SCALEFACTOR, SpriteEffects.None, 0f);
}

```

It works fine, my object is rotated, at it's centre, by Pi/2, or whatever I put in. However, rotating the rectangle isn't as easy, I read almost every stack overflow question on this problem and still haven't found a fix. I then followed a youtube guide, this is the resulting code for rotating a rectangle.

```
private void RotateItem(float rotation)
{
    rot += rotation;
    UpdateRectangle();
}

private void UpdateRectangle()
{
    Vector2 tl = Vector2.Transform(Vector2.Zero, transform);
    Vector2 tr = Vector2.Transform(new Vector2(scaledWidth, 0), transform);
    Vector2 bl = Vector2.Transform(new Vector2(0, scaledHeight), transform);
    Vector2 br = Vector2.Transform(new Vector2(scaledWidth, scaledHeight), transform);

    Vector2 min = new Vector2(FindSmallest(tl.X, tr.X, bl.X, br.X), FindSmallest(tl.Y, tr.Y, bl.Y, br.Y));
    Vector2 max = new Vector2(FindBiggest(tl.X, tr.X, bl.X, br.X), FindBiggest(tl.Y, tr.Y, bl.Y, br.Y));

    rectangle = new Rectangle((int)min.X, (int)min.Y, (int)(max.X - min.X), (int)(max.Y - min.Y));
}

private void UpdateTransformMatrix()
{
    transform = Matrix.CreateTranslation(new Vector3(-Origin, 0))
                * Matrix.CreateRotationZ(rot)
                * Matrix.CreateTranslation(new Vector3(position, 0));
}

```

The width + height don't seem to change until I click on the box (which isn't even drawn properly over the sprite because Origin + and doesn't seem to rotate at all tbh)... I'll show you an example https://gyazo.com/c045b844f306a0ea25f48a0d45127f21

And this is my full draw code + including the rectangle's rectTex

```
public virtual void Draw(SpriteBatch spriteBatch)
{
    spriteBatch.Draw(texture, position, null, Color.White, rot, Origin, SCALEFACTOR, SpriteEffects.None, 0f);
    if (ShowRectangle)
        spriteBatch.Draw(rectTex, rectangle, null, Color.White, rot, Vector2.Zero, SpriteEffects.None, 0f);
}

```

# Answer
> 0 votes
Okay, after a few more hours of fiddling around and referencing, I somehow managed to fix it. It was a matter of order in which I Update the transform matrix and update the rectangle and where I did so. Now it kind of works, however, after X amount of rotates, the height gets set to 0 and the rectangle ceases to exist... I'll post my new Updates and stuff so people who look at this in the future can see

```
public virtual void Update(GameTime gameTime, MouseState _currState, MouseState _prevState, ref Item controlItem)
{
    ClickCheck(_currState, _prevState, ref controlItem);
    if (controlItem == this)
    {
        int diffX = _currState.X - _prevState.X;
        int diffY = _currState.Y - _prevState.Y;
        position.X += diffX;
        position.Y += diffY;
        UpdateTransformMatrix();
        UpdateRectangle();
    }
}

```

```
public Item(Texture2D inTex)
{
    texture = inTex;
    position = new Vector2(400,400);
    scaledWidth = (int)(texture.Width * SCALEFACTOR);
    scaledHeight = (int)(texture.Height * SCALEFACTOR);
    rectangle = new Rectangle((int)position.X,(int)position.Y,scaledWidth, scaledHeight);
    Origin = new Vector2(scaledWidth / 2, scaledHeight / 2);
    UpdateTransformMatrix();
}

```

```
protected void ClickCheck(MouseState _currentState, MouseState _prevState, ref Item controlItem)
{
    Rectangle mouseRect = new Rectangle(_currentState.X, _currentState.Y, 1, 1);
    if (rectangle.Intersects(mouseRect) &&
        _currentState.LeftButton == ButtonState.Pressed)
        {
            controlItem = this;
            return;
        }
     if (rectangle.Intersects(mouseRect) &&
                _currentState.RightButton == ButtonState.Released && _prevState.RightButton == ButtonState.Pressed)
        {
             RotateItem((float)Math.PI / 2);
             UpdateTransformMatrix();
             UpdateRectangle();
        }

        controlItem = null;
}

```

```
private void RotateItem(float rotation)
{
    rot += rotation;
    UpdateRectangle();
}

```

```
private void UpdateRectangle()
{
    Vector2 tl = Vector2.Transform(Vector2.Zero, transform);
    Vector2 tr = Vector2.Transform(new Vector2(scaledWidth, 0), transform);
    Vector2 bl = Vector2.Transform(new Vector2(0, scaledHeight), transform);
    Vector2 br = Vector2.Transform(new Vector2(scaledWidth, scaledHeight), transform);

    Vector2 min = new Vector2(FindSmallest(tl.X, tr.X, bl.X, br.X), FindSmallest(tl.Y, tr.Y, bl.Y, br.Y));
    Vector2 max = new Vector2(FindBiggest(tl.X, tr.X, bl.X, br.X), FindBiggest(tl.Y, tr.Y, bl.Y, br.Y));

    rectangle = new Rectangle((int)min.X, (int)min.Y, (int)(max.X - min.X), (int)(max.Y - min.Y));
}

private void UpdateTransformMatrix()
{
    transform = Matrix.CreateTranslation(new Vector3(-Origin / 1.7f, 0))
                * Matrix.CreateRotationZ(rot)
                * Matrix.CreateTranslation(new Vector3(position, 0));
}

```

# Answer
> 0 votes
Collisions on rotated axes is not a simple as rotated rectangles, unless the the rotation is common among all possible colliders, at that point rotate the camera and leave the drawing and collisions alone.

For square or close to square objects, use a circle or Manhatten distance to approximate the collision distance, fudge size as needed, smaller for enemy and characters, larger for bonus or collectable items.

To make sure I answer the the question as asked: To properly rotate a rectangle for collisions(i.e. for Intersect() to work, it requires axis alignment.), the bounds must grow to fit the out-most extents(bounds) of the rotated object. Rotating the rectangle off axis is not helpful. All rectangle intersection code assumes common axes, since they are defined by top-left and width and height on the common axes.

Yes, with four raycasts per object pair of rotated "rectangles"(source point, end point, and +- deviations, orthogonal width or height...), rays, point(or line) line intersections can be costly.

Due to the curse of dimensionality, this is the preferred method in three+ dimensions, when combined with octree or BVH, or other culling methods.

In 2D AABB, axis aligned bounding boxes, is the most efficient general collision method for 2D collisions. (I tend to use a more memory intensive grid or quadtree structure for spacial optimizations, but that is not appropriate for rotated items of arbitrary size.)

The main problem is broad culling, your UpdateRectangle() method produces the axis aligned largest `rectangle`.

Once an overlap is detected, use the `Rectangle.Intersect()` method to narrow the search area. This area is small enough for a more complex method like pixel overlap check, or recursive bounds checks, that takes a small amount time to fit within the time budget.

# Answer
> -1 votes
i've seen that you rotate the image and the collision, in fact you Don't need to do it with the collision box;

Simply switch width and height of it will work because all you do is 90° rotations.

c# function that could work in this case:

```
// assuming your collision rectangle is called colRect
public void rotateCollisionRectangle()
{
    // here i Simply switch height and width
    colRect = new Rectangle(colRect.height, colRect.width);
    rot += Math.Pi / 2;
}

```

also your rectangle when drawn appear a bit Strange, i experienced similare thing when the width was negative. If it's the case, offset the rectangle x and y and say that height and width are positive

---
Tags: xna, rotation, monogame, xna-4.0, linear-algebra
---


# Question
Title: How to deal damage every 2 seconds while enemy is touching the player, rather than every frame?
I have made an up and down movement RPG prototype and I wanted to have a fighting system.

I made it so that the enemy follows the player and that I get damage every time he collides with me. The problem was that he only gave me damage once and would have to stop colliding with me, to attack again. I fixed that by changing `OnCollisionEnter2D` to `OnCollisionStay2D`, but now he attacks every frame, which makes him way too strong.

I already asked some people how to change it and they said you could do it with coroutines. The thing is that I have no idea how to code that and it gets even more complicated, because the enemy is constantly touching the player (When you're not dodging). I would be really happy if someone could help me with that

EnemyAttack.cs:

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

public class EnemyAttack : MonoBehaviour
{
    [SerializeField] private GameObject Player;
    [SerializeField] private int timer;
    public int damage;
    public PlayerHealth playerHealth;
    public float AttackCooldown;
    public float WaitForSecondsRealTime;
    float PlayerHealthh;

    private void OnCollisionStay2D(Collision2D collision) {
        if(collision.gameObject.tag == "Player") {
            playerHealth.TakeDamage(damage);

        }
    }
}

```

# Answer
I wouldn't use a coroutine for this - just tracking the time since the last attack is enough.

```
public class EnemyAttack : MonoBehaviour
{
    public int damage;
    public PlayerHealth playerHealth;
    public float attackCooldown;

    float _lastAttackTime;

    private void OnCollisionStay2D(Collision2D collision) {
        // Abort if we already attacked recently.
        if (Time.time - _lastAttackTime < attackCooldown) return;

        // CompareTag is cheaper than .tag ==
        if(collision.gameObject.CompareTag("Player")) {
            playerHealth.TakeDamage(damage);

            // Remember that we recently attacked.
            _lastAttackTime = Time.time;
        }
    }
}

```

The advantage here is that we don't have to allocate and construct a new `Coroutine` instance. Just updating a float is dirt cheap. Subtracting float timestamps is not entirely precise, but for values that don't need sub-millisecond precision like an attack cooldown on the order of a half-second or more, this is "good enough".

But if you really want to do it with a coroutine, you can do it like this:

```
public class EnemyAttack : MonoBehaviour
{
    public int damage;
    public PlayerHealth playerHealth;
    public float attackCooldown;

    Coroutine _attackInProgress;
    int _playerContacts;

    private void OnCollisionEnter2D(Collision2D collision) {

        if(collision.gameObject.CompareTag("Player")) {
            _playerContacts++;
            if (_attackInProgress == null)
                 _attackInProgress = StartCoroutine(AttackLoop);
        }
    }

    private void OnCollisionExit2D(Collision2D collision) {

        if(collision.gameObject.CompareTag("Player")) {
            _playerContacts--;
        }
    }

    private IEnumerator AttackLoop() {
        while(_playerContacts > 0) {
            playerHealth.TakeDamage(damage);

            // You can construct this once and cache it if you like.
            yield return new WaitForSeconds(attackCooldown);
        }
        _attackInProgress = null;
    }
}

```

I've used the `_playerContacts` counter to exit the coroutine instead of calling `StopCoroutine` in `OnCollisionExit` for a couple of reasons:

* It preserves the cooldown even if we briefly separate and re-collide, instead of short-circuiting and letting another attack through early.
* It correctly handles cases where the player or enemy have multiple colliders (and so might get an exit message for one pair of colliders while another pair is still touching).
> 0 votes

# Answer
Use the following code to match the one off code, no co-routines required.

**Note the damage time is now in terms of seconds, so adjust the values accordingly.** I suggest damage/600 as a starting point.

This change entirely removes the FPS dependency that your original code had, and makes the attack speed machine independent.

I would add some random variation to increase replay value, as indicated in the commented line (adjust values as needed):

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

public class EnemyAttack : MonoBehaviour
{
    [SerializeField] private GameObject Player;
    [SerializeField] private int timer;
    public int damagePerSecond;
    public PlayerHealth playerHealth;
    public float AttackCooldown;
    public float WaitForSecondsRealTime;
    float PlayerHealthh;

    private void OnCollisionStay2D(Collision2D collision) {
        if(collision.gameObject.CompareTag("Player")) { # attributed to DMGregory as faster.
            If (!player.Dodge) playerHealth.TakeDamage(Time.deltaTime * damagePerSecond);
//If (!player.Dodge)
//   playerHealth.TakeDamage(Time.deltaTime * (damagePerSecond * Random.Range(.9f, 1f));
//else
//   playerHealth.TakeDamage(Time.deltaTime * (damagePerSecond * Random.Range(.1f, .4f);
        }
    }
}

```
> 0 votes

---
Tags: unity, c#, 2d, collider, coroutines
---


title: Cube moving in a laggy way

text:
# Question
Title: Cube moving in a laggy way
The movement on its own works perfectly fine, the problem is just that when I move diagonal, then the cube (the Player) is kinda lagging around and you can see its pixels moving to the edges of it. The whole map is kinda being rotated 20°. I would be very thankful for a little help on this!

```
using UnityEngine;

public class BetterMovement: MonoBehaviour  {

   //Public Variables
   public float moveSpeed;
   public Rigidbody2D rb;

   //Private Variables
   private Vector2 moveDirection;

   void Update() {
       ProcessedInputs();
   }

   void FixedUpdate() {
       Move();
   }

   void ProcessedInputs() {
       float moveX = Input.GetAxisRaw("Horizontal");
       float moveY = Input.GetAxisRaw("Vertical");
       moveDirection = new Vector2(moveX, moveY);
   }

   void Move() {
      rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
   }

}

```

# Answer
> 0 votes
I just figured it out on myself, it was basically because of the CameraFollow I was using. The speed of the camera was way to slow, so I guess it had to kinda do weird teleporting stuff. However I simply fixed it by changing the camerafollow speed to a higher number (In my situation 0.125 --\> 1).

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


# Question
Title: Player goes through obstacles with colliders
My Player just goes through stuff he actually shouldnt be able to go trough like enemies or map borders, which all have collider components attached to them.

It's really annoying because I haven't changed anything and sice yesterday, but it isn't working anymore. It's especially annoying because Enemies cant even hit me anymore.

Is there a better way to use colliders? I would be really thankful for some help on that. If you need more specific infos just write comment.

# Answer
The problem was simply because my `Rigidbody2D` was set to be Kinematic, which led to it being totally immune to physics interaction, meaning it could not collide with anything.

To fix this issue, just set your `Rigidbody2D` (back) to Dynamic.
> 1 votes

---
Tags: unity, collision-detection, collider
---


# Question
Title: Object goes straight through game object without colliding
The "shot" is supposed to collide with the left bumper and then be destroyed, but the shot goes right through it. Both objects have a box collider.

The following is the code I am using:

```
#pragma strict
var speed : int = 2;
var collided_with : GameObject;

function Update () {
    transform.Translate(Vector3(-1 * speed * Time.deltaTime, 0, 0));
}

function OnCollisionEnter (col : Collision) {
    if (collided_with.tag == "Left") {
        Destroy(gameObject);
    }
}

```

I have made sure that all the tags are assigned correctly and that there are no spelling errors. The variable collided\_with is also assigned to the left bumper. What am I doing wrong?

# Answer
`Collider` is only one piece of the puzzle -- it detects a collision -- but each object in the collision should also have a `Rigidbody` attached if you want an actual collision response.

Also, depending on the speed, you may need CCD \- Continuous Collision Detection.
> 3 votes

# Answer
You should consider using a RigidBody on some of your objects. There are 3 types of collision detection for a RigidBody component. Discrete is fastest, but it can result in the "bullet through paper" problem that you are having.

https://docs.unity3d.com/Documentation/ScriptReference/Rigidbody-collisionDetectionMode.html
> 0 votes

# Answer
Maybe you should check if your rigidbody is set to kinematic, because if it is, then its immune to collision input. Which could then lead to this problem you are facing. To fix it simply set you rigidbody to dynamic.
> 0 votes

---
Tags: unity, collision-detection, javascript
---


# Question
Title: What is the process of making a chracter creator like black desert in godot/unity?
example

I get the point of switching heads or other body part models as long as they are all attached to the same bones then the animations will work, but what about changing the color of lips, eyelashes, skin, armor? those games don't have 100 different UV per model, they only have the body UV, the head one, the eye UV so 3 at most since the armor UV replaces the body UV

Plus those types of games also give access to momentary bones that change the shape of the mesh giving almost complete control over shaping a character, it not something new, Tera and Aion did it back in 2006-2007.

it's actually very common in Eastern games but almost no one does it for western games, I can't even find any tutorial that goes in depth into this or someone working on it at least showcasing the workflow

# Answer
> 0 votes
> but what about changing the color of lips, eyelashes, skin, armor? those games don't have 100 different UV per model, they only have the body UV, the head one, the eye UV so 3 at most since the armor UV replaces the body UV

You can change the colors with shaders, controlled by shader parameters (I mean: uniforms).

For example, have the shader add a color only in areas defined by a texture (you can have additional textures and query them with the same UVs).

Since you only need one channel as mask to decide where to apply a color, you can define multiple areas in the same texture by using the different color channels. Furthermore the value of the channel can control intensity of the color.

You might want to have the base color be gray-scale, and apply the color by multiplication. So you change the hue and saturation, but keep the brightness of the base color gray-scale.

*You might also be interested in doing hue rotation in shader.*

It is also common that different cloth pieces reuse are the same mesh and same UV but with different texture (taking advantage of alpha transparency and scissors).

Also be aware that you can have bone attachments. I mean, other meshes that follow the transformation of the bones but are not part of the character mesh. Which you can use for armor, weapons and accessories.

---

> Plus those types of games also give access to momentary bones that change the shape of the mesh giving almost complete control over shaping a character, it not something new, Tera and Aion did it back in 2006-2007.

No momentary bones. Don't change the skeleton structure in runtime. However you can have extra bones in the skeleton that are not used by the animation. Yet you can allow these extra bones to deform the mesh, and you can allow the player to pose them.

Be aware that your animations won't work (well or at all) if you have a different skeleton. So even allowing the player to stretch the bones is problematic. If you need to support something like that you will need a proper animation retargeting solution.

However, I suspect what you are referring to is something else: have multiple base meshes (all with the same vertex count and topology), and combine interpolate them linearly by weights controlled by the player (with sliders). This modifies the mesh (moves the vertex around), not the skeleton. *See also blend shapes.*

---
Tags: graphics-programming, character
---


# Question
Title: How to implement "Auto Generate Animation" and "Visualize" buttons in custom Button inspector?
I extended the Button class with my own variables. I also had to create an Editor script since Unity manually draws the Button's fields into the Inspector. I just need to know what the functions that are called by these two buttons in the Inspector:

I've googled the topic and nothing came up in my results.

I'm on Unity 2022

# Answer
> 1 votes
I happened to use the `Window > Analysis > IMGUI Debugger` to inspect the buttons. Fortunately, the call trace to which function is called.

Also, since there's a `SelectableEditor`, I don't have to re-serialize all the properties of the button. I just extend my custom editor class from `SelectableEditor` like so:

```
[CustomEditor(typeof(CustomScript))]
public class CustomEditor : SelectableEditor
{
    SerializedProperty customVar;

    protected override void OnEnable()
    {
        base.OnEnable();

        // add code here. for example:
        customVar = serializedObject.FindProperty("animateType");
    }

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        // add code here. for ex.
        EditorGUILayout.PropertyField(customVar);

        serializedObject.ApplyModifiedProperties();
    }
}

```

---
Tags: unity, c#, unity-ui, editors
---


# Question
Title: When moving the "camera" should one move the projection matrix or move the world?
I'm making my own game engine as an exercise and I've gotten really confused with what I've read so far.

When I want to move my camera do I simply just move the world or move the position of the camera?

OpenGl tutorials and scratchapixel state that you move the world and not the camera. But that really confuses me wouldn't it be simpler to just move the camera instead of for example applying millions of additions in worlds as big as minecraft? What about VR headsets? Those have 2 cameras how do they do it?

Is there something I'm missing or it just works like this?

# Answer
OpenGL and Scratchapixel do not state that you need to move the world. The editors of the documents you are referring to spent a great deal of time explaining the process in detail and you are simplifying it down to a statement that doesn't make much sense out of its context.

* you have objects say in world space. I am not even talking about the object-to-world transform here.
* then you have the camera. You need to move the camera around in world space to frame part of the set. This gives you the `cam to world` matrix.

When you are ready to render, what you do is this:

1. you transform the vertices of the scene objects using the `world to cam` matrix, which as you have noted, is the invert of the `cam to world` matrix. This has for effect of moving the vertices in front of the camera (what you refer to as moving the world), as if the camera had never been moved from its default position (centered around the world origin looking down the z-axis). We say that the vertices are then in camera space.

Think of it that way: "you move the entire block (the geometry + the camera), so the camera returns to its default position. Because the scene and the camera moved together, what you see through the camera isn't changing. But the benefit of this transformation is that the maths for projecting the vertices onto the camera screen (step 2) are greatly simplified (mostly a matter of dividing the x and y coordinates of the vertices by their z-coordinate. But we use the perspective projection matrices because it does a little bit more than that for us: it takes into account the frame aspect ration, field of view and remap the depth of the vertices to 0-1 in a non-linear fashion. That's why we use the perspective projection instead of a simple z division).
2. then you project the vertices that are in camera space at this stage, into screen space using the perspective projection matrix. This leads to transforming points that are original 3D coordinates into screen coordinates (2D points, aka position on the flat screen + eventually a depth value if you need it).

In a real-time graphics pipeline (in the shader), this generally looks like this:

```
vec3 vertex_in_screen =
    perspective_mat *
    world_to_camera_mat *
    vertex_in_world_space;

```

When you mean that *we move the world in front of the camera* you assume item 1. in the process described above.

In this order. I hope this can help you understand the process. I think this is very well defined and explained in the references you are pointing to.
> 1 votes

# Answer
First, the matrix in question is the "view matrix," which yields the scene coordinates relative to the camera. The "projection matrix" is responsible for the actual warping of the objects as a function of distance to give the perspective projection from which we see the world with our eyes/cameras.

In my mind, the "move the world, not the camera" is a false dichotomy. Ultimately, the job of the graphics pipeline is to get arbitrary scene coordinates mapped onto pixel coordinates.

Consider an orthographic projection that maps the screen to a region that is 100 meters wide (say, for a top-down 2D game). If this camera is at x = 0m, an object at x = -50m will be at the left edge of the screen, and an object at x = +50m will be at the right edge of the screen. The orthographic projection matrix takes care of actually turning the range of \[-50, +50\] meters into (X, Y) pixel coordinates.

If you have an object at x=1500m, and a camera at x=1550m, you need to map the position of the object to the left edge of the screen regardless of which way you slice the problem. The simplest way to achieve this is to simply subtract the camera position from the object position, which leaves you with the object's position relative to the camera (in this case, x = -50m). In that sense, there really isn't such a thing as "moving the camera," because whatever overall transformation you use still have to map the scene to the screen in an equivalent manner. You could encode the transformation in the projection matrix instead of the view matrix, but they're still multiplied together to yield the same final result. Thus, whether you're moving the world or moving the camera is more a matter of semantics than a practical one.

And yes, every single one of the millions of vertices on-screen need to be subject to this transformation. GPUs are designed to take advantage of the fact that transforming all these vertices is a highly parallelizable workload, and are able to do that enormous amount of math in the very short time in between frames.
> 1 votes

# Answer
You move the world because there is no camera.

The camera is a useful analogy in tutorials, but it's important to understand that an analogy is all that it is: it doesn't actually exist in any 3D API.

When people talk about "moving the camera" what they're really doing is taking that camera transform and applying the inverse of it to everything in the world. Instead of, for example, moving a camera forward by 10 units, what really happens is that the world moves backwards by 10.

This isn't a lot of work for a GPU. Each object you draw will typically have a single concatenated MVP (model-view-projection) which contains everything needed to position and orient the object in the world and on the screen. The per-vertex operation is just a simple vector/matrix multiplication.
> 1 votes

# Answer
If your aim is to see how things look relative to a camera perhaps you could think of it like splitting the task into two steps, first being computing how things are positioned relative to it and its orientation and the second being computing how objects look relative to the camera in this standardized coordinate space. Then the second part could be solved once for all positions so to speak.

If your camera is really weird and works differently in different positions of your world, I guess you can't split it up like this and need some kind of nonlinear function which takes both the camera and object to compute how things would look.
> 0 votes

# Answer
You always move the world.

As stated above, the camera itself is just an idea that helps you abstract the concept of view, movement, etc. Therefore sometimes you may have multiple "cameras" (or vectors in space for that matter) to help you switch your view of the world.
> 0 votes

---
Tags: camera, maps, projection, projection-matrix
---


# Question
Title: What transformation is occuring in Unity to the child with a sprite renderer, when adjusting the parent's z scale?
When I adjust the child's z scale, nothing happens normally. but the parent makes the child appear stretched

UPDATE: Here are my examples

This is the child inside of the scaled parent.

And this is the parent:

Notice when I set the parent's scale back to 1,1,1, the child is scaled

And notice when I scale the child (with the parent back at the default 1.5, 1.5, 1.5 scale) on the Z axis, nothing changes

And notice how when the parent's z axis scale is set back to 1, the child is also transformed (indicating that z scale axis changes on the parent change the child, but z scale axis changes on the child don't really have an effect)

# Answer
> 0 votes
The z-axis of a sprite is its "depth". But sprites don't have "depth", because they are two-dimensional. If you want to make the sprite "wider" or "higher", then you need to change the scale of its x or y axis respectively.

Now you might wonder "If z-scale doesn't matter for sprites, then why does changing the z-scale of the parent affect where and how the child appears?". The answer is that the child has a local position and a local rotation. When you scale a parent, then that scaling factor is also applied to the local position and rotation of the child.

When you place the child 2 units away from the parent, and then double the scale of the parent, the child will appear 4 units away from the parent.

When you rotate a child by 45° on the x-axis so its apparent height on the screen is only half of what it usually is, and then double the scale of the parent, it will appear 22.5° rotated.

In order to better understand the concept of parent and child transforms in 3d (and yes, you are building a 3d game here, because you are rotating things on the x and y axis), you might want to experiment a bit with boxes in a 3d scene. Create a hierarch of parented boxes. Change the positions, scales and rotations of the boxes relative to the parent so they appear as separate objects on the screen. Then move, scale and rotate the parent. What do you see?

---
Tags: unity
---


# Question
Title: Replace Input.GetKey(KeyCode.Mouse0) with New Input System
I was implementing the new Input system for my game, when I saw that I still had a script in my player that wouldnt allow me to start the scene, because the script still operated with the old input manager. Its probably just because I literally ask him to do so, in line 24, I think. I was still wondering if someone could tell me, how to actually use the new input system for this script and how I would have to change the script for it. And also btw I actually want to use it with an xbox one controller, if that would change anthing. Heres the script:

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

public class PlayerAttack : MonoBehaviour{

private float timeBtwAttack;
public float startTimeBtwAttack;
PlayerControls controls;
public Transform attackPos;
public LayerMask whatIsEnemies;
//public Animator camAnim;
//public Animator playerAnim;
public float attackRangeX;
public float attackRangeY;
public int damage;

void Update(){

    if(timeBtwAttack <= 0){

        if(Input.GetKey(KeyCode.Mouse0)){
            //camAnim.SetTrigger("shake");
            //playerAnim.SetTrigger("attack");
            Collider2D[] enemiesToDamage = Physics2D.OverlapBoxAll(attackPos.position, new       Vector2(attackRangeX, attackRangeY), 0, whatIsEnemies);
            for (int i = 0; i < enemiesToDamage.Length; i++) {
                enemiesToDamage[i].GetComponent<Enemy>().TakeDamage(damage);
            }
            timeBtwAttack = startTimeBtwAttack;
        }

} else  {
    timeBtwAttack -= Time.deltaTime;
 }

}void OnDrawGizmosSelected(){

        Gizmos.color = Color.black;
        Gizmos.DrawWireCube(attackPos.position, new Vector3(attackRangeX, attackRangeY, 1));

  }
}

```

# Answer
If you want a quick&dirty drop-in replacement:

```
if( Mouse.current.leftButton.wasPressedThisFrame ) {

```

However, that's not how the new input system is supposed to be used. The old input system was based on the philosophy that you poll the state of the input devices during `Update`. The new input system is based on events. You don't ask the system what's the input state; the system tells you that an input event occurred by calling a callback method. But doing it like that requires that you completely rethink the way you handle input in your game.

What you usually have in a project using the new input system is:

1. An Input Actions asset which allows you to define semantic input actions (like "shoot") and then assign multiple controls to them (like left mouse button, Gamepad button X, keyboard keys Space and x and pressing the touchscreen).
2. A bunch of handler-methods on various scripts which are supposed to be called when one of those semantic input actions happens
3. A PlayerInput component which links semantic actions to the handler-methods.

But explaining the whole thing from start to finish would be yet another Unity new input system tutorial. Others have already created enough of those which are easy to find with your preferred search engine. Or you could read the manual which also offers a pretty good introduction into how to use the system efficiently.
> 0 votes

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


# Question
Title: How to properly port 30 FPS physics with integers to 60 FPS and maybe floats?
I've inherited a code base in which everything is coded to run at 30 FPS and uses integers.

I would like to upgrade the frame rate to 60 FPS, naturally I thought about using floats but it ain't that easy to do so. I created a git branch and tried to port what appeared to made sense to use float but it ended up catastrophic, things would fly everywhere on the screen, presumably because of rounding issues...

Then I considered why simply not keeping integers as that would be simpler but also not introduce subtle bugs that will be hard to track.

This is an example of how the code is, many things are updated against frame rate ratios:

```
playerShip.ThrustMagnitude += Timing.Instance.FR15 + 1;

```

I came up with the following which works well in some cases but not all:

```
playerShip.ThrustMagnitude += Timing.Scale(Timing.Instance.FR15 + 1, deltaTime);

```

The helper class in its entirety:

```
public sealed class Timing : Singleton<Timing>
{
    public static double OriginalFrameRate { get; } = 1.0d / 30.0d;
    public int FR6 { get; } = 6;
    public int FR7 { get; } = 7;
    public int FR10 { get; } = 10;
    public int FR15 { get; } = 15;
    public int FR30 { get; } = 30;
    public int FR32 { get; } = 32;
    public int FR40 { get; } = 40;
    public int FR50 { get; } = 50;
    public int FR60 { get; } = 60;

    public static int Scale(int value, double deltaTime, int? decimals = null, MidpointRounding? rounding = null)
    {
        var result = deltaTime / OriginalFrameRate * value;

        if (decimals.HasValue)
        {
            var digits = decimals.Value;

            if (rounding.HasValue)
            {
                result = Math.Round(result, digits, rounding.Value);
            }
            else
            {
                result = Math.Round(result, digits);
            }
        }
        return (int)result;
    }
}

```

The main problem I have is that it doesn't work when values are very small, yaw and roll for instance work well because they have large values, but the pitch for instance does not because its range is very small.

Say you have a value of 30 at 30 FPS, `X / 30 == 1`, but at 60 FPS it results in `X / 60 == 0`.

What approach can you suggest to tackle this problem?

# Answer
Your complaint is that small magnitude deltas no longer work properly after doubling the frame rate.

There's at least two ways out. The second seems more attractive.

1. Scale them up so they are larger magnitude, operate on the scaled values, and scale down appropriately when rendering.
2. Keep the old frame rate. That is, for a small magnitude update, skip the update unless the low order bit(s) are zero. In the case of using a 30 FPS model when rate is 60, that is just a matter of asking whether current frame number is even.
> 1 votes

---
Tags: physics, frame-rate
---


title: How to abstract VAO as a class in c++

text:
# Question
Title: How to abstract VAO as a class in c++
I read the khronos docs on Vertex Array Objects, and it says that VAOs do not copy any data but refer to VBOs and EBOs/IBOs. So i created an abstraction class vbo which creates a vertex buffer from a list of vertices. The vbo class destructor calls gldeletebuffer on the vbo. Now i am creating a vao class, which takes in a vbo in setvbo functiin. But if i am just copying the renderer\_id of the vbo, then when the vbo is deleted, the destructor calls gldeletebuffer on the vbo, which is being used by the vao. The vbo basically outlives the vao. What is the correct object oriented way to abstract a VAO class?

# Answer
I do it like this:

```
class VAO {

 public:

  VAO() = default;
  VAO(const VAO& other) = delete;
  VAO(VAO&& other) { *this = std::move(other); }
  ~VAO() { if (m_id) glDeleteVertexArrays(1, &m_id); }
  VAO& operator=(const VAO& other) = delete;
  VAO& operator=(VAO&& other) {
    if (this != &other) {
      if (m_id) glDeleteVertexArrays(1, &m_id);
      m_id = std::exchange(other.m_id, 0);
    }
    return *this;
  }

  /**
   * @brief Binds the VAO.
   */
  void bind() const { glBindVertexArray(m_id); }

  /**
   * @brief Specifies how OpenGL should interpret the vertex buffer data whenever a draw call is made.
   * @param vbo The vertex buffer object to be binded.
   * @param layout Specifies the index of the generic vertex attribute to be modified. Must match the layout in the shader.
   * @param components Specifies the number of components per generic vertex attribute. Must be 1, 2, 3, 4.
   * @param type Type of the data.
   * @param stride Specifies the byte offset between consecutive generic vertex attributes.
   * @param offset Specifies a offset of the first component of the first generic vertex attribute in the array in the data store.
   * @param normalize Specifies whether fixed-point data values should be normalized.
   */
  void linkAttrib(const VBO& vbo, GLuint layout, GLuint components, GLenum type, GLsizei stride, void* offset, GLboolean normalize = GL_FALSE) const;

  /**
   * @brief Specifies how OpenGL should interpret the vertex buffer data whenever a draw call is made. IT DOESN'T BIND ANYTHING!
   * @param layout Specifies the index of the generic vertex attribute to be modified. Must match the layout in the shader.
   * @param components Specifies the number of components per generic vertex attribute. Must be 1, 2, 3, 4.
   * @param type Type of the data.
   * @param stride Specifies the byte offset between consecutive generic vertex attributes.
   * @param offset Specifies a offset of the first component of the first generic vertex attribute in the array in the data store.
   * @param normalize Specifies whether fixed-point data values should be normalized.
   */
  void linkAttribFast(GLuint layout, GLuint components, GLenum type, GLsizei stride, void* offset, GLboolean normalize = GL_FALSE) const;

  /**
   * @brief Generates the vertex array buffer.
   */
  void genVertexArray();

  /**
   * @brief Unbinds the VAO.
   */
  void unbind() const { glBindVertexArray(0); }

 private:

  GLuint m_id {};
};

```

Also the VBO class:

```
class VBO {

 public:

  VBO() = default;
  VBO(const VBO& other) = delete;
  VBO(VBO&& other) { *this = std::move(other); }
  ~VBO() { if (m_id) glDeleteBuffers(1, &m_id); }
  VBO& operator=(const VBO& other) = delete;
  VBO& operator=(VBO&& other) {
    if (this != &other) {
      if (m_id) glDeleteBuffers(1, &m_id);
      m_id = std::exchange(other.m_id, 0);
    }
    return *this;
  }

  /**
   * @brief Binds the VBO.
   */
  void bind() const { glBindBuffer(GL_ARRAY_BUFFER, m_id); }

  /**
   * @brief Generates the buffer for the VBO.
   */
  void genBuffer();

  /**
   * @brief Sets up the data for the buffer.
   * @param vertices A pointer to an array of floats to use as data.
   * @param size The size in bytes of the data.
   * @param usage The usage type, default GL_STATIC_DRAW.
   */
  void setup(const GLfloat* vertices, GLsizeiptr size, GLenum usage = GL_STATIC_DRAW);

  /**
   * @brief Sets up the data for the buffer.
   * @tparam T Things stored *contiguously* in memory.
   * @param vertices A pointer to an array of Ts to use as data.
   * @param size The size in bytes of the data.
   * @param usage The usage type, default GL_STATIC_DRAW.
   */
  template <typename T>
  void setup(const T* vertices, GLsizeiptr size, GLenum usage = GL_STATIC_DRAW) {
    glBindBuffer(GL_ARRAY_BUFFER, m_id);
    glBufferData(GL_ARRAY_BUFFER, size, vertices, usage);
    glCheckError();
  }

  /**
   * @brief Sets up the data for the buffer.
   * @tparam T You might want this to some numeric, vector, etc type for good result,
   * @param vertices A std::vector of something to use as data.
   * @param usage The usage type, default GL_STATIC_DRAW.
   */
  template <typename T>
  void setup(const std::vector<T>& vertices, GLenum usage = GL_STATIC_DRAW) {
    glBindBuffer(GL_ARRAY_BUFFER, m_id);
    glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(T), vertices.data(), usage);
    glCheckError();
  }

  /**
   * @brief Sets up the data for the buffer avoiding the cost of reallocating
   *  the data store.
   * @tparam T Things stored *contiguously* in memory.
   * @param vertices A pointer to an array of Ts to use as data.
   * @param size The size in bytes of the data.
   * @param offset The offset into the buffer object's data store where data
   *  replacement will begin, measured in bytes.
   */
  template <typename T>
  void setupSubData(const T* vertices, GLsizeiptr size, GLintptr offset = 0) {
    glBindBuffer(GL_ARRAY_BUFFER, m_id);
    glBufferSubData(GL_ARRAY_BUFFER, offset, size, vertices);
    glCheckError();
  }

  /**
   * @brief Sets up the data for the buffer avoiding the cost of reallocating
   *  the data store.
   * @tparam T You might want this to some numeric, vector, etc type for good result,
   * @param vertices A std::vector of floats to use as data.
   * @param offset The offset into the buffer object's data store where data
   *  replacement will begin, measured in bytes.
   */
  template <typename T>
  void setupSubData(const std::vector<T>& vertices, GLintptr offset = 0) {
    glBindBuffer(GL_ARRAY_BUFFER, m_id);
    glBufferSubData(GL_ARRAY_BUFFER, offset, vertices.size() * sizeof(T), vertices.data());
    glCheckError();
  }

  /**
   * @brief Unbinds the VBO.
   */
  void unbind() const { glBindBuffer(GL_ARRAY_BUFFER, 0); }

 private:

  GLuint m_id {};
};

```

As you see, I don't save any vbo id in the vao.
> 1 votes

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


# Question
Title: Unity Editor 2021.3.3+ full screen in editor mode
How do you make play mode take up the full screen in Unity Editor?

N.B. There are various scripts for making the editor Maximize take up the full screen (without the unity top bar), but these do not seem to work for Unity 2021.

# Answer
You can use a Unity Store asset called "**Fullscreen Editor**".

No idea why Unity hasn't got Fullscreen yet but only "Maximize On Play". It's very helpful if you're working on UI stuff cause you can test the game in Fullscreen without building the game, at least that's what i'm doing. And you can maximize **any** Unity Editor window with it's shortcuts, and supports multiple screens.

Also i noticed some weird "scaling" isues? when using "Maximize On Play" when working on the UI, because in 1920x1080 (FullHD) "Maximize On Play" scales the game to x0.84 due to not being totaly Fullscreen.
> -1 votes

---
Tags: unity
---


# Question
Title: C++ Chess Game Program sending/receiving UCI commands from Stockfish.exe using CreateProcess()?
```
#include "Game.h"

#include <Windows.h>

void Game::GameLoop()
{
    StartStockfish();

    while(!quit)
    {

    }
}

void Game::StartStockfish()
{
    saAttr.nLength=sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle=TRUE;
    saAttr.lpSecurityDescriptor=NULL;

    hStdinWrite=GetStdHandle(STD_INPUT_HANDLE);
    hStdoutRead=GetStdHandle(STD_OUTPUT_HANDLE);

    // Start the Stockfish process

    ZeroMemory(&si,sizeof(si));
    si.cb=sizeof(si);
    ZeroMemory(&pi,sizeof(pi));

    si.hStdError=GetStdHandle(STD_ERROR_HANDLE);
    si.hStdOutput=GetStdHandle(STD_OUTPUT_HANDLE);
    si.hStdInput=GetStdHandle(STD_INPUT_HANDLE);
    si.dwFlags|=STARTF_USESTDHANDLES;

    // Create pipe for the child process's standard input
    if(!CreatePipe(&hStdinRead,&hStdinWrite,&saAttr,0))
    {
        printf("CreatePipe failed (%d).\n",GetLastError());
        return;
    }

    // Create pipe for the child process's standard output
    if(!CreatePipe(&hStdoutRead,&hStdoutWrite,&saAttr,0))
    {
        printf("CreatePipe failed (%d).\n",GetLastError());
        return;
    }

    // Create pipe for the child process's standard error
    if(!CreatePipe(&hStderrRead,&hStderrWrite,&saAttr,0))
    {
        printf("CreatePipe failed (%d).\n",GetLastError());
        return;
    }

    if(!CreateProcess(
        (LPCTSTR)L"D:/_Dev/stockfish_15.1_win_x64_avx2/stockfish-windows-2022-x86-64-avx2.exe",   // No module name (use command line)
        (LPTSTR)L"",                // Command line
        NULL,                   // Process handle not inheritable
        NULL,                   // Thread handle not inheritable
        TRUE,                  // Set handle inheritance to TRUE
        0,                      // No creation flags
        NULL,                   // Use parent's environment block
        NULL,                   // Use parent's starting directory
        &si,                    // Pointer to STARTUPINFO structure
        &pi)                    // Pointer to PROCESS_INFORMATION structure
        )
    {
        printf("CreateProcess failed (%d).\n",GetLastError());
    }

    // Close the Stockfish process
    CloseHandle(hStdinRead);
    CloseHandle(hStdoutWrite);

    // Send a command to Stockfish
    SendStockfishCommand("uci\n");
    Sleep(2000);
    SendStockfishCommand("isready\n");

    Sleep(2000);

    std::vector<std::string> testOutputList=ReadStockfishOutput();
    printf("testOutputList size=%d\n",(int)testOutputList.size());

    for(int i=0; i < testOutputList.size(); i++)
    {
        printf("testOutputList %d=%s\n",i,testOutputList[i].c_str());
    }

    SendStockfishCommand("d");

    Sleep(2000);

    std::vector<std::string> testOutputList2=ReadStockfishOutput();
    printf("testOutputList2 size=%d\n",(int)testOutputList2.size());
    for(int i=0; i < testOutputList2.size(); i++)
    {
        printf("testOutputList2 %d=%s\n",i,testOutputList2[i].c_str());
    }
}

void Game::CloseStockfish()
{

}

void Game::SendStockfishCommand(std::string str)
{
    DWORD bytesWritten=0;
    str+='\n';
    WriteFile(hStdinWrite,str.c_str(),str.length(),&bytesWritten,NULL);
    printf("Sent command:%s\n",str.c_str());
}

std::vector<std::string> Game::ReadStockfishOutput()
{
    printf("ReadStockfishOutput() called \n");
    std::vector<std::string> lines;
    DWORD bytesRead=0;
    char buffer[1024];
    while(ReadFile(hStdinRead,buffer,sizeof(buffer),&bytesRead,NULL))
    {
        if(bytesRead == 0)
        {
            printf("bytesRead was zero\n");
            break;
        }

        printf("reading the stdin buffer\n");
        std::string line(buffer,bytesRead);
        std::cout << line << std::endl;
        lines.push_back(line);
    }

    return lines;
}

```

I am trying to learn more and more about c++ and this time I try to write a chess game. I already made a chess game, but the way I created it was not easy to work with (mainly I want to change the whole game, because I want to use the outputted "fen string" from the engine to find where to draw the pieces. In my previous version, the pieces were moved with my own logic and then I converted those positions into a fen string each time.

But this time, I learned by reading here and other sites, I should use `CreateProcess()` (I am only targeting Windows). Previously I used `_popen` (but as I say I ran into problems).

I admit I am in quite far over my head here. Lots of new concepts I've learned in the last couple of days only. But essentially from what I can tell, my `ReadStockfishCommand()` does not work correctly (or, the way I am using it maybe wrong)

The only 2 things I can think is either:

a) I need to wait some time before calling the read function (I doubt this is the answer, as I tried adding Sleep(5000) etc between and this made no difference.

b) I am reading from the wrong "pipe". I think this is most likely, as I have very little understanding of what the pipe actually is. I do realise I created this, so that I can push the data from Std::cin etc to the pipe and then free up the actual Std::cin channel with `CloseHandle(hStdinRead);` etc.

But I guess I am very mixed up now, having tried several similar versions of this code now and always ending up with the "lines" vector being empty. (eg. I send command "isready", then try to read the response. But the response lines always equals zero).

Finally, when running this code. This is what I see in the Console Window:

```
Sent command:uci

Stockfish 15.1 by the Stockfish developers (see AUTHORS file)
Sent command:isready

ReadStockfishOutput() called
testOutputList size=0
Sent command:d

```

I am hoping it is something as silly as changing one parameter in a function call. But really, I am stuck and have no idea what to try next.

# Answer
> 0 votes
```
#include "Game.h"

#include <Windows.h>
#include <sstream>

void Game::GameLoop()
{
    StartStockfish();

    while(!quit)
    {

    }
}

void Game::StartStockfish()
{
    saAttr.nLength=sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle=TRUE;
    saAttr.lpSecurityDescriptor=NULL;

    // Start the Stockfish process

    ZeroMemory(&si,sizeof(si));
    si.cb=sizeof(si);
    ZeroMemory(&pi,sizeof(pi));

    // Create pipe for the child process's standard input
    if(!CreatePipe(&hStdinRead,&hStdinWrite,&saAttr,0))
    {
        printf("CreatePipe failed (%d).\n",GetLastError());
        return;
    }

    // Create pipe for the child process's standard output
    if(!CreatePipe(&hStdoutRead,&hStdoutWrite,&saAttr,0))
    {
        printf("CreatePipe failed (%d).\n",GetLastError());
        return;
    }

    // Create pipe for the child process's standard error
    if(!CreatePipe(&hStderrRead,&hStderrWrite,&saAttr,0))
    {
        printf("CreatePipe failed (%d).\n",GetLastError());
        return;
    }

    si.hStdError=GetStdHandle(STD_ERROR_HANDLE);
    si.hStdOutput=hStdoutWrite;
    si.hStdInput=hStdinRead;
    si.dwFlags|=STARTF_USESTDHANDLES;

    if(!CreateProcess(
        (LPCTSTR)L"D:/_Dev/stockfish_15.1_win_x64_avx2/stockfish-windows-2022-x86-64-avx2.exe",   // No module name (use command line)
        (LPTSTR)L"",                // Command line
        NULL,                   // Process handle not inheritable
        NULL,                   // Thread handle not inheritable
        TRUE,                  // Set handle inheritance to TRUE
        0,                      // No creation flags
        NULL,                   // Use parent's environment block
        NULL,                   // Use parent's starting directory
        &si,                    // Pointer to STARTUPINFO structure
        &pi)                    // Pointer to PROCESS_INFORMATION structure
        )
    {
        printf("CreateProcess failed (%d).\n",GetLastError());
    }

    // Send a command to Stockfish
    SendStockfishCommand("uci\n");
    std::vector<std::string> uci_response=ReadStockfishOutput();
    for(int i=0; i < uci_response.size(); i++)
    {
        printf("uci_response %d=%s\n",i,uci_response[i].c_str());
    }

    SendStockfishCommand("isready\n");
    std::vector<std::string> isready_response=ReadStockfishOutput();
    for(int i=0; i < isready_response.size(); i++)
    {
        printf("isready_response %d=%s\n",i,isready_response[i].c_str());
    }

    SendStockfishCommand("d\n");
    std::vector<std::string> d_response=ReadStockfishOutput();
    for(int i=0; i < d_response.size(); i++)
    {
        printf("d_response %d=%s\n",i,d_response[i].c_str());
    }

}

void Game::CloseStockfish()
{

}

void Game::SendStockfishCommand(std::string str)
{
    DWORD bytesWritten=0;
    //str+='\n';
    if(WriteFile(hStdinWrite,str.c_str(),str.length(),&bytesWritten,NULL))
    {
        printf("Sent command:%s  . BytesWritten=%ld\n",str.c_str(), bytesWritten);
    }

}

std::vector<std::string> Game::ReadStockfishOutput()
{
    Sleep(500);
    printf("*************************Read() called\n");
    std::vector<std::string> lines;
    DWORD bytesRead=0;
    char buffer[1024*4];
    while(true)
    {
        // Check if the read operation was successful
        if(!ReadFile(hStdoutRead,buffer,sizeof(buffer),&bytesRead,NULL))
        {
            printf("FAIL bytes READ=%ld\n",bytesRead);
            DWORD errorCode=GetLastError();
            if(errorCode == ERROR_BROKEN_PIPE)
            {
                printf("Pipe was closed\n");
            }
            else
            {
                printf("Error occurred while reading from the pipe: %d\n",errorCode);
                // Additional error handling code
            }
            break;
        }

        std::stringstream bufferStream(std::string(buffer,bytesRead));
        std::string line;
        while(std::getline(bufferStream,line))
        {
            printf("line=%s\n",line.c_str());
            lines.push_back(line);
        }

        fflush(stdout);
        break;

    }

    printf("lines size=%d\n",(int)lines.size());
    return lines;

}

```

Well, I seem to have fixed the code. But sadly, this was more by trial-and-error rather than fully understanding the code.

The problem revolved around the argument I sent to ReadFile (ie. which pipe I was trying to read) along with the Start function where I had to change the values of si.hStdInput etc.

Hopefully, someone can provide a better answer, but I figured I would post this here, since it does at least print the stockfish responses (and store them in my "lines" vector, as I needed).

---
Tags: c++, windows, chess
---


# Question
Title: Achieving 2D Lighting for Terraria-Like Game
I'm trying to achieve the fog-of-war lighting style that Terraria and Starbound have. Terraria's lighting system seems to be more blocky/tile based, but Starbound's is a lot more smooth.

**The Desired Effect:**

Starbound is using a shader to render its lighting, but how it's going about that is quite a mystery to me.

The idea I had on how to achieve the desired effect is the following: Create a texture that is black and *somehow* calculate the area that is white, storing this in a light map render texture, finally doing an Additive Blend of both the main texture and the light map texture to achieve a similar effect to Starbound's. (However this does not take into account lights in the world, which I also have absolutely no clue how to include in my calculation to the light map render texture)

I say *somehow* in italics because I have no clue as to how I can create this "Mask" effect in the light map render texture. How I can do calculations necessary to create the mask is beyond me; I don't even know how I can begin to translate the game world's data, relative to the what the camera sees, and update the texture accordingly.

**TLDR:** How can I achieve lighting similar to that of either Terraria or Starbound in Unity 2D?

# Answer
> 3 votes
First you draw your color map

Then you draw your light map

And finally you multiply both.

If you want a some sort of secondary lighting in your game, and if your game world uses grid for terrain and/or object placement, then I have a solution for you. This is something like instant radiosity.

First, you find which cells are lit by the light by tracing them from the light source.

Then you place another light sources on lit cells with attenuation of intensity based on a distance from original light. You may also want to blur them a bit (I did). Here's resulting map.

Add original light source there.

Then multiply with your color map.

Here's pseudocode for the rendering pipeline (don't mind the syntax highlight)

```
for each light on scene:
    if light is on screen:
        add light to the drawing queue

draw frame:
    render frame color map:
        draw each visible tile and object

    for each light in queue:
        trace secondary lights on visible cells and add them to the drawing queue

    render frame light map:
        set blending to additive
        for each light in queue:
            move light object to the light position
            set light object width and height to the light radius
            set light object color to the light color
            draw light object
        //then we render shadows for solid places
        set blending to subtraction
        for each visible cell:
            if cell is surrounded by other cells from every side:
                move light object to the cell
                set light width and height to the radius slightly bigger than cell
                set light color to white//to subtract any kind of light color
                draw light object

    set blending to normal
    draw color map
    set blending to multiplication
    draw light map

```

# Answer
> 0 votes
Here's my hacky solution:

1. There's 2 cameras.
2. Empty tiles are filled in with white blocks (only camera 2 render this)
3. A gaussian blur is applied to the camera rendering the white blocks
4. SpriteLightKit blends the two cameras, darkening everything not covered by the white blurry.
5. You can adjust the "light" penetration by changing the white tile's sprite's Pixels Per Unit.

GitHub Link

---
Tags: unity, 2d, shaders, lighting, rendertexture
---