# Question
Title: Calculating the inverse mesh of a 2D mesh inside a bounding box
If I have a mesh (drawn in red below)

How can I calculate the inverse of the mesh (drawn in red below), given that the mesh is always constrained by the same four vertices of the encompassing bounding box?

My mesh is drawn using a series of clockwise wound triangles.

Is there possibly any easy way to do this in a shader?

I wish to draw the triangles, and therefore each pixel, of the inverse mesh rather than draw the original mesh with color of the mesh and the background swapped to give an inverse effect.

# Answer
> 0 votes
If all you need is drawing, simply swapping the colors of the background and the mesh will give you exactly the result you described, of course. If that's not an option for some reason, a simple color replacement shader should suffice.

If you do need to make an inverse mesh for other purposes, I found a simple way to achieve it. It may not apply to the way you're drawing it your mesh, but is a useful way to think about the problem, and took me surprisingly long to realize.

I needed to do it and found this old unanswered question, so after I found my solution I thought I would come here and explain. Here's what I did:

Make a square and set your mesh grid on it. In my case, I made it using a 3x3 grid.

**Tada! A fish.**

Then, hollow out a square to make a donut like shape. Make a second mesh, with 2 more grid points in each dimension (in this case, 5x5). The empty part of your donut should line up with internal points of your 5x5 grid.

These internal points are exactly the same as a 3x3 grid, so simply set them to the same positions as your fish equivalent, and you will have your inverse mesh!

**Tada! A not fish.**

---
Tags: rendering, geometry, mesh
---


# Question
Title: What is the best way to increase slowly object movement speed and slow down the object near the end?
There a Lerp but also SmoothDamp.

In this script I'm using SmoothDamp but why not using Lerp ? And how should I use this script with the SmoothDamp tp make slowly increasing speed at the start ? Now it's only slow down at the end but I want it also to increase slowly at the start and then slowly down near the end.

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

public class MovementSpeedController : MonoBehaviour
{
    public Transform target;
    private Vector3 velocity = Vector3.zero;
    public float smoothTime = 0.3F;

    void Update()
    {
        transform.position = Vector3.SmoothDamp(transform.position, target.position, ref velocity, smoothTime);
    }
}

```

# Answer
I use the following function to get smooth acceleration/deceleration while moving to the target value/position:

```
float SmoothTowards(float current, float target, ref float velocity, float accel, float maxVelocity = float.PositiveInfinity)
{
    // The calculations need to be made in positive absolute values,
    // This sing variable is for the case of moving backwards (like from 10 to -5)
    // In the end we'll use this to set values to the original change direction sign:
    int sign = (target - current) > 0 ? 1 : -1;

    float distance = target - current;

    // Make the values positive.
    if (velocity < 0) velocity = -velocity;
    if (distance < 0) distance = -distance;

    // d: the distance that is required to decelerate over time and to stop at the target value
    //  with the given aceleration/deceleration and current velocity values:
    float t = velocity / accel;
    float d = velocity * t * 0.5f;
    // remove '* 0.5f' to get the slower deceleration effect. Velocity deceleration will be started earlier and will be slower.

    if (distance <= d)
        velocity -= accel;
    else if (distance - velocity - accel > d)
        velocity += accel;

    // Clamp the velocity if needed
    if (velocity > maxVelocity)
        velocity = maxVelocity;

    // Set the result to the original change direction sign:
    velocity *= sign;

    // Prevent overshooting:
    if (IsThresholdCrossed(current, current + velocity, target))
        return target;
    else
        return current + velocity;
}

```

The 'accel' argument is an acceleration/deceleration step. On every call the result will be increased or decreased by this value depending on the 'distance' to the target value. The `IsThresholdCrossed(...)` function simply checks if the 'target' value is on the other side of the threshold than 'current' value:

```
bool IsThresholdCrossed(float a, float b, float threshold)
{
    if (a < threshold && threshold <= b ||
        b <= threshold && threshold < a)
            return true;
        else
            return false;
}

```

How to use it:

```
float velocityX, velocityY, velocityZ;
float acceleration = 1f;
float maxVelocity = 10f;

void Update()
{
    // First of all, let's get frame rate independent values for acceleration and maxVelocity depending in the last frame time:

    // with acceleration =1 the speed will be gradually increased by 1 m/s every second (or decreased while getting closer to the target)
    float accelDelta = acceleration * Time.deltaTime;

    // limit max speed for current frame
    float maxVelDelta = maxVelocity * Time.deltaTime;

    // Finally, move the transform towards the target:
    transform.position = new Vector3(
        SmoothTowards(transform.position.x, target.position.x, ref velocityX, accelDelta, maxVelDelta),
        SmoothTowards(transform.position.y, target.position.y, ref velocityY, accelDelta, maxVelDelta),
        SmoothTowards(transform.position.z, target.position.z, ref velocityZ, accelDelta, maxVelDelta)
    );
}

```
> 0 votes

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


# Question
Title: How can I randomize my speeds just once, each time values are changed in the Inspector?
```
    private void SpeedUpdater()
    {
        if (changeSpeedOnce == false)
        {
            foreach (WaypointsFollower follower in waypointsFollowers)
            {
                if (randomSpeed)
                {
                    follower.speed = Random.Range(minRandomSpeed, maxRandomSpeed);
                }
                else
                {
                    follower.speed = speed;
                }
            }

            changeSpeedOnce = true;
        }
    }

```

I'm calling SpeedUpdater from inside the Update.

The problem is that if I'm not using the private flag bool changeSpeedOnce it will give each follower speed a random value every frame but I want that when it's random it will give each follower speed only one random speed value that is why I'm using the changeSpeedOnce flag.

but then I can't change the speed in run time when the game is running because changeSpeedOnce is false now.

I'm stuck here. From one side I want to give only one random speed value to each follower but I also want to do it any time in the run time when I'm changing the speed value in the Inspector.

# Answer
> 0 votes
Don't do this in Update. This is exactly what OnValidate was made for. OnValidate gets called in the editor when the inspector properties are changed by the user, or after deserialization.

You can use the `[Delayed]` attribute to hold off on calling OnValidate until the user finishes editing a field.

```
[Delayed]
public float speed;

public bool randomSpeed;

[Delayed]
public float minRandomSpeed;

[Delayed]
public float maxRandomSpeed;

void UpdateSpeeds() {
    foreach (WaypointsFollower follower in waypointsFollowers)
    {
        follower.speed = randomSpeed ? Random.Range(minRandomSpeed, maxRandomSpeed) : speed;
    }
}

#if UNITY_EDITOR
bool _cachedRandomSpeed;
float _cachedSpeed;

void OnValidate() {
    if ((randomSpeed != _cachedRandomSpeed) || (!randomSpeed && speed != _cachedSpeed)) {
        UpdateSpeeds();
    }
    _cachedRandomSpeed = randomSpeed;
    _cachedSpeed = speed;
}
#endif

void Start() {
    UpdateSpeeds();
}

```

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


title: Post Processing without using FBOs?

text:
# Question
Title: Post Processing without using FBOs?
Recently, I've been making a 3D game (hint my questions), and I recently have modified a pixelization shader from a unity shader graph tutorial. The thing is, I want to render the shader on the WHOLE screen, not just a single object, but while researching, I've come across something called *Framebuffer Objects* (FBOs), which make it pretty much easier (basically just grabs the frame and turns it into an image for you to "process" it before it gets rendered on the screen), but I don't really want to use FBOs. How would I come across doing this? I've researched a little and came across using a quad, but since my game is 3D, not 2D, I have a perspective camera, so I don't know how that would turn out.

# Answer
> 0 votes
Are you using a game engine? If yes, your game engine likely comes in with a built in post-processing system/pipeline, in which case you shouldn't have to worry about frame buffers for simple post-processing.

If your engine doesn't have a post-fx system, or you're making an engine from scratch: yes you would use a quad. The key, is that instead of rendering/transforming the quad in *world-space* you would render and position it in *view-space* so it will be fixed in the screen instead of in the world. You'll do this changing whatever transformation matrix is being used to displace the quads vertices to a view-space-matrix.

You might want to familiarize yourself with the purpose of matrices (which effectively act as stores for transformations in 3D games) and the basic graphics / shader pipeline.

Here's a link which offers an overview of the role of *matrices* and *spaces* in realtime 3D rendering.

---
Tags: opengl, fragment-shader, post-processing, vertex-shader
---


title: Structuring a game in Java

text:
# Question
Title: Structuring a game in Java
I am currently programming my first game in Java and I'm having trouble structuring it. My biggest concern is regarding the game loop. Currently I have implemented a class with only a main function which first initializes all of the variables and then goes into a game loop. Here is the structure of the code:

```
public static void main(String args[])

//Initializing all the variables

//Main game loop

while(true)
{
  if (mouse is pressed)
  {
    do something
  }

  if (mouse is released)
  {
    do something
  }
  ......
}

```

The problem is that the "do something" parts are quite lengthy and my code looks quite messy. I would like to turn them into methods, however I am not really sure how to do it.

# Answer
> 0 votes
A common way to break down a long update loop is by creating a separate method for each individual feature of the game. For example:

```
while(!isGameOver()) {
    updatePlayer();
    updateEnemies();
    updateProjectiles();
    updateUi();
    render();
}

```

If any method gets too long, consider to break it down into more methods based on the sub-problem they solve. This is called the "Single Responsibility Principle" in software architecture. Every modularization unit (like a method) should be responsible for one single thing. When you can not explain what its responsibility is in one sentence, or if that sentence contains the word "and", then you might want to consider to break it into two.

For example, when the responsibility `updatePlayer()` would be described as "reads the input state from the controls **and** applies it to the player", then you might want to consider to break it down like this:

```
input = readInput();
updatePlayer(input);

```

And if the responsibilities of `updatePlayer(Input input)` now would be described as "makes the player walk **and** jump **and** shoot based on the current input state", then it could be broken down further like this:

```
input = readInput();
playerWalk(input);
playerJump(input);
playerShoot(input);

```

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


# Question
Title: How to project a 3D circle/ellipse to 2D?
The 3D ellipse is represented by its center and the vectors for its major and minor axes and the 2D ellipse by its center, the length of the major and minor axes and the angle between the major axis and the x-axis. I need the general projection on an axis-aligned plane, discarding a coordinate.

The problem is that the axes after projection are no longer are aligned to the true axes of the 2D ellipse.

# Answer
> 3 votes
Let's express a point \\$\vec p\\$ on your 3D ellipse as a parametric equation, using the vectors \\$ \vec c\\$ for the center, \\$ \vec M \\$ for the semi-major axis and \\$ \vec m \\$ for the semi-minor axis, and a parameter \\$ 0 \le t \le 2 \pi\\$:

$$\vec p(t) = \cos(t) \vec M + \sin(t) \vec m + \vec c$$

From this we can derive three points on your 2D ellipse, at the tip of each of the 3D ellipse's major axes, and one "diagonal" point between them:

$$ (M\_x + c\_x, M\_y + c\_y)\\ (m\_x + c\_x, m\_y + c\_y)\\ (d\_x, d\_y) = (\frac {M\_x + m\_x} {\sqrt{2}} + c\_x, \frac {M\_y + m\_y} {\sqrt{2}} + c\_y)$$

These will be three solutions to the general equation of an ellipse centered at a point \\$\vec c\\$:

$$ A (x - c\_x)^2 + B (x - c\_x) (y - c\_y) + C (y - c\_y)^2 = 1$$

We can clear out all instances of \\$\vec c\\$ to shift our problem to the origin for now (and add it back later). We can then express this equation and our three known solutions as a system of linear equations:

$$\begin{bmatrix} M\_x^2 & M\_x M\_y & M\_y^2\\ m\_x^2 & m\_x m\_y & m\_y^2\\ d\_x^2 & d\_x d\_y & d\_y^2\\ \end{bmatrix} \begin{bmatrix} A\\B\\C \end{bmatrix} = \begin{bmatrix} 1\\1\\1 \end{bmatrix} $$

You can solve this system for the unknowns \\$A\\$, \\$B\\$, \\$C\\$ (eg. using Cramer's Rule or other solving techniques of your liking) to get the equation of the 2D ellipse.

Taking the formulae from Wikipedia, that leaves us with...

$$\begin{align} a,b&=\frac {-{\sqrt {2{\Big (}(B^{2}-4AC){\Big )}\left((A+C)\pm {\sqrt {(A-C)^{2}+B^{2}}}\right)}}}{B^{2}-4AC}\\ \\ \theta &= \begin{cases}\arctan \left({\frac {1}{B}}\left(C-A-{\sqrt {(A-C)^{2}+B^{2}}}\right)\right)&{\text{for }}B\neq 0\\0&{\text{for }}B=0,\ A\<C\\90^{\circ }&{\text{for }}B=0,\ A\>C\end{cases} \end{align}$$

...for the length of the semi-major axis \\$a\\$, semi-minor axis \\$b\\$, and the angle \\$\theta\\$ from the positive x axis to the major axis.

# Answer
> 3 votes
Christopher Brierley Jones describes the process on his website how an ellipse can be fit perfectly into any convex quadrilateral. The process is very similar to what DMGregory describes in his answer to extract the ellipse parameters from the matrix representation.

The key insight is that instead of projecting the ellipse directly, you can project the bounding rectangle. That will always result in an convex quadrilateral. Then you can use Jones process to fit an ellipse into the resulting quadrilateral.

You already mentioned that the axes are no longer aligned after the projection. Note that not even the center of the resulting ellipse aligns with the projected center of the circle. Jones describes the relation between the original circle and the projected ellipse as "inscrutable".

I implemented function for mapping a convex quad to an `{cx,cy,ra,rb,angle}` ellipse in JavaScript.

You can see a live demo here or a video here

```
// W,X,Y,Z are {x:number,y:number} vertices of the convex qudriliteral.
function quadToEllipse(W,X,Y,Z) {
    // Reconstruct matrix that transforms the unit square ((-1,-1), (1,1)) into quad (W,X,Y,Z)
    const m00 =  X.x * Y.x * Z.y - W.x * Y.x * Z.y - X.x * Y.y * Z.x + W.x * Y.y * Z.x -
                W.x * X.y * Z.x + W.y * X.x * Z.x + W.x * X.y * Y.x - W.y * X.x * Y.x;
    const m01 =  W.x * Y.x * Z.y - W.x * X.x * Z.y - X.x * Y.y * Z.x + X.y * Y.x * Z.x -
                W.y * Y.x * Z.x + W.y * X.x * Z.x + W.x * X.x * Y.y - W.x * X.y * Y.x;
    const m02 =  X.x * Y.x * Z.y - W.x * X.x * Z.y - W.x * Y.y * Z.x - X.y * Y.x * Z.x +
                W.y * Y.x * Z.x + W.x * X.y * Z.x + W.x * X.x * Y.y - W.y * X.x * Y.x;
    const m10 =  X.y * Y.x * Z.y - W.y * Y.x * Z.y - W.x * X.y * Z.y + W.y * X.x * Z.y -
                X.y * Y.y * Z.x + W.y * Y.y * Z.x + W.x * X.y * Y.y - W.y * X.x * Y.y;
    const m11 = -X.x * Y.y * Z.y + W.x * Y.y * Z.y + X.y * Y.x * Z.y - W.x * X.y * Z.y -
                W.y * Y.y * Z.x + W.y * X.y * Z.x + W.y * X.x * Y.y - W.y * X.y * Y.x;
    const m12 =  X.x * Y.y * Z.y - W.x * Y.y * Z.y + W.y * Y.x * Z.y - W.y * X.x * Z.y -
                X.y * Y.y * Z.x + W.y * X.y * Z.x + W.x * X.y * Y.y - W.y * X.y * Y.x;
    const m20 =  X.x * Z.y - W.x * Z.y - X.y * Z.x + W.y * Z.x - X.x * Y.y + W.x * Y.y + X.y * Y.x - W.y * Y.x;
    const m21 =  Y.x * Z.y - X.x * Z.y - Y.y * Z.x + X.y * Z.x + W.x * Y.y - W.y * Y.x - W.x * X.y + W.y * X.x;
    const m22 =  Y.x * Z.y - W.x * Z.y - Y.y * Z.x + W.y * Z.x + X.x * Y.y - X.y * Y.x + W.x * X.y - W.y * X.x;

    // invert matrix
    const determinant = +m00*(m11*m22-m21*m12) -m01*(m10*m22-m12*m20) +m02*(m10*m21-m11*m20);
    if(determinant == 0) return null;
    const invdet = 1/determinant;
    const J =  (m11*m22-m21*m12)*invdet;
    const K = -(m01*m22-m02*m21)*invdet;
    const L =  (m01*m12-m02*m11)*invdet;
    const M = -(m10*m22-m12*m20)*invdet;
    const N =  (m00*m22-m02*m20)*invdet;
    const O = -(m00*m12-m10*m02)*invdet;
    const P =  (m10*m21-m20*m11)*invdet;
    const Q = -(m00*m21-m20*m01)*invdet;
    const R =  (m00*m11-m10*m01)*invdet;

    // extract ellipse coefficients from matrix
    const a = J*J + M*M - P*P;
    const b = J*K + M*N - P*Q;
    const c = K*K + N*N - Q*Q;
    const d = J*L + M*O - P*R;
    const f = K*L + N*O - Q*R;
    const g = L*L + O*O - R*R;

    // deduce ellipse center from coefficients
    const centerX = (c*d - b*f) / (b*b - a*c);
    const centerY = (a*f - b*d) / (b*b - a*c);

    // deduce ellipse radius from coefficients
    const radiusA = Math.sqrt(2*(a*f*f + c*d*d + g*b*b - 2*b*d*f - a*c*g)/((b*b - a*c) * (Math.sqrt((a-c)*(a-c) + 4*b*b) - (a+c))));
    const radiusB = Math.sqrt(2*(a*f*f + c*d*d + g*b*b - 2*b*d*f - a*c*g)/((b*b - a*c) * (-Math.sqrt((a-c)*(a-c) + 4*b*b) - (a+c))));

    // deduce ellipse rotation from coefficients
    let angle = 0;
    if(b==0 && a <= c) {
        angle = 0;
    } else if(b == 0 && a >= c) {
        angle = Math.PI / 2;
    } else if(b != 0 && a > c) {
        angle = Math.PI / 2 + 0.5 * (Math.PI / 2 - Math.atan2((a-c), (2*b)));
    } else if(b != 0 && a <= c) {
        angle = Math.PI / 2 + 0.5 * (Math.PI / 2 - Math.atan2((a-c), (2*b)));
    }

    return {
        centerX, centerY, radiusA, radiusB, angle
    }

```

*Update*: See this link for an example where this technique is used for drawing ellipses onto the faces of a rotating 3d cube as shown below:

---
Tags: mathematics, projection
---


# Question
Title: How to compute the 2D equations of 3D circular arcs?
I'd like to obtain these equations for the ellipses produced by the perspective projections of (3-dimensionally transformed) circles.

This is useful for rendering in 2D contexts which provide curve primitives. I'm using HTML5's canvas, so I get Beziers, arcs, and quadratic curves.

See here:

The projection of a sphere outside of the plane of projection is an ellipse because the view is a cone (silhouette of a sphere is a circle).

However if I want to draw my sphere using circular wireframes, that projection-cone is no longer a circular cone. So it's not your traditional conic section anymore.

How to deal with this?

# Answer
> 3 votes
I wouldn't bother with heavy maths to get that ellipse's equation. Here's what I recommend:

* Discretize your wireframe sphere (the usual way, using lattitude/longitude, or with a geodesic grid, or fancier). This gives you a list of 3D vertices;
* Transform them to screen space with the usual model-view-projection matrix;
* Then just render line segments between those transformed vertices.

Of course you've got line segments instead of arcs, but drawing arcs in an HTML5 canvas kills performance, so I wouldn't recommend it. Just subdivide your sphere until the result looks OK.

There's a bunch of 3D engines for Javascript that implement software rendering. For instance, you could have a look at Three.js for inspiration.

That's if you want to do it all yourself, on the CPU. You could also use WebGL, there's already a tutorial for that. Browser support is not very broad yet, but it's supposed to be the future.

# Answer
> 1 votes
> However if I want to draw my sphere using circular wireframes, that projection-cone is no longer a circular cone. So it's not your traditional conic section anymore.

The perspective projection of a 3d circular disk is also an ellipse, as long as the disk is entirely in front of the camera. (If the disk crosses the camera plane, it projects into a hyperbola).

It is only slightly more complicated to compute the ellipse parameters of a projected disk than to compute the ellipse parameters of a projected sphere. And as you've pointed out, there can be greater utility, efficiency, and accuracy in using curve primitives for rendering when curve primitives are available, especially when using a vector based renderer like SVG rather than raster based renderer.

There are several methods for computing the ellipse parameters of a perspective-projected circle, using geometric constructions, or using analytic / algebraic methods. I've found the algebraic methods easier to implement.

Perhaps the simplest algebraic method is to put your disk into matrix form \[1\], run it through the perspective transform \[2\], and then extract the center and axes from the result \[3\]. A simple alternative to the first two steps is to compute the projected ellipse equation by taking 5 sample points from your disk, projecting them to the image plane, and converting the 5 points directly into the ellipse equation coefficients \[4\], then proceed with extracting the center and axes from the coefficients \[3\].

There is a nice complete code example of computing the ellipse using a transform on ShaderToy \[5\] which has a blog post attached describing the math and an interesting application of it, undistorting text. \[6\]

One constructive geometry method is to perspective-project a square that encloses your 3d disk, and find the ellipse inscribed by the projected quad \[7\]. It uses known geometric relationships between the quad and the ellipse (such as the tangents of the contact points) to find the ellipse parameters. The geometric relationships of parts of the ellipse have been explored in depth \[8\]

And just in case you want to go the simpler route of drawing the sphere's silhouette ellipse (rather than wireframe disks), Inigo Quilez wrote a nice article deriving the math \[9\] and he provides a complete implementation \[10\].

\[1\] https://en.wikipedia.org/wiki/Matrix\_representation\_of\_conic\_sections

\[2\] https://math.stackexchange.com/a/2899066/616990

\[3\] https://en.wikipedia.org/wiki/Ellipse#General\_ellipse

\[4\] https://math.stackexchange.com/a/163931/616990

\[5\] https://www.shadertoy.com/view/MlGGz3

\[6\] https://mzucker.github.io/2016/10/11/unprojecting-text-with-ellipses.html

\[7\] https://web.archive.org/web/20190924033522/http://www.math.nus.edu.sg/~graeme/Geometry/Circle\_in\_Perspective/construct\_axes.html

\[8\] https://archive.org/details/constructivegeom00eagluoft/page/96/mode/2up (pages 96-150)

\[9\] https://www.iquilezles.org/www/articles/sphereproj/sphereproj.htm

\[10\] https://www.shadertoy.com/view/XdBGzd

# Answer
> 1 votes
I already answered the question How to project a 3D circle/ellipse to 2D? by providing the JavaScript implementation below.

Christopher Brierley Jones describes the process on his website how an ellipse can be fit perfectly into any convex quadrilateral.

So one way to compute the 2D equations of 3D circular arcs, without discretizing into line segments first, is to project the bounding rectangle and the extract the ellipse parameters from the resulting convex quadrilateral as described by Jones.

You can see a live demo here or a video here

Now if you want to project a *sphere* instead of a plain circle from 3d to 2d the steps would be:

1. create a circle with the same center as the sphere and the same radius but oriented with it's normal towards the camera plane, i.e. that the circle's plane is parallel to the projection plane As DMGregory pointed out the correct orientation for the circle face is not parallel to the projection plane but instead facing the camera center, as illustrated in this diagram.
2. so instead: create a circle with the same center as the sphere and the same radius but oriented with it's normal *towards the camera position*
3. create a bounding square around this circle
4. project the 4 vertices of this square with the camera projection matrix to obtain a quadrilateral
5. reconstruct the ellipse parameters by applying the procedure below to the resulting quadrilateral

```
// W,X,Y,Z are {x:number,y:number} vertices of the convex qudriliteral.
function quadToEllipse(W,X,Y,Z) {
    // Reconstruct matrix that transforms the unit square ((-1,-1), (1,1)) into quad (W,X,Y,Z)
    const m00 =  X.x * Y.x * Z.y - W.x * Y.x * Z.y - X.x * Y.y * Z.x + W.x * Y.y * Z.x -
                W.x * X.y * Z.x + W.y * X.x * Z.x + W.x * X.y * Y.x - W.y * X.x * Y.x;
    const m01 =  W.x * Y.x * Z.y - W.x * X.x * Z.y - X.x * Y.y * Z.x + X.y * Y.x * Z.x -
                W.y * Y.x * Z.x + W.y * X.x * Z.x + W.x * X.x * Y.y - W.x * X.y * Y.x;
    const m02 =  X.x * Y.x * Z.y - W.x * X.x * Z.y - W.x * Y.y * Z.x - X.y * Y.x * Z.x +
                W.y * Y.x * Z.x + W.x * X.y * Z.x + W.x * X.x * Y.y - W.y * X.x * Y.x;
    const m10 =  X.y * Y.x * Z.y - W.y * Y.x * Z.y - W.x * X.y * Z.y + W.y * X.x * Z.y -
                X.y * Y.y * Z.x + W.y * Y.y * Z.x + W.x * X.y * Y.y - W.y * X.x * Y.y;
    const m11 = -X.x * Y.y * Z.y + W.x * Y.y * Z.y + X.y * Y.x * Z.y - W.x * X.y * Z.y -
                W.y * Y.y * Z.x + W.y * X.y * Z.x + W.y * X.x * Y.y - W.y * X.y * Y.x;
    const m12 =  X.x * Y.y * Z.y - W.x * Y.y * Z.y + W.y * Y.x * Z.y - W.y * X.x * Z.y -
                X.y * Y.y * Z.x + W.y * X.y * Z.x + W.x * X.y * Y.y - W.y * X.y * Y.x;
    const m20 =  X.x * Z.y - W.x * Z.y - X.y * Z.x + W.y * Z.x - X.x * Y.y + W.x * Y.y + X.y * Y.x - W.y * Y.x;
    const m21 =  Y.x * Z.y - X.x * Z.y - Y.y * Z.x + X.y * Z.x + W.x * Y.y - W.y * Y.x - W.x * X.y + W.y * X.x;
    const m22 =  Y.x * Z.y - W.x * Z.y - Y.y * Z.x + W.y * Z.x + X.x * Y.y - X.y * Y.x + W.x * X.y - W.y * X.x;

    // invert matrix
    const determinant = +m00*(m11*m22-m21*m12) -m01*(m10*m22-m12*m20) +m02*(m10*m21-m11*m20);
    if(determinant == 0) return null;
    const invdet = 1/determinant;
    const J =  (m11*m22-m21*m12)*invdet;
    const K = -(m01*m22-m02*m21)*invdet;
    const L =  (m01*m12-m02*m11)*invdet;
    const M = -(m10*m22-m12*m20)*invdet;
    const N =  (m00*m22-m02*m20)*invdet;
    const O = -(m00*m12-m10*m02)*invdet;
    const P =  (m10*m21-m20*m11)*invdet;
    const Q = -(m00*m21-m20*m01)*invdet;
    const R =  (m00*m11-m10*m01)*invdet;

    // extract ellipse coefficients from matrix
    const a = J*J + M*M - P*P;
    const b = J*K + M*N - P*Q;
    const c = K*K + N*N - Q*Q;
    const d = J*L + M*O - P*R;
    const f = K*L + N*O - Q*R;
    const g = L*L + O*O - R*R;

    // deduce ellipse center from coefficients
    const centerX = (c*d - b*f) / (b*b - a*c);
    const centerY = (a*f - b*d) / (b*b - a*c);

    // deduce ellipse radius from coefficients
    const radiusA = Math.sqrt(2*(a*f*f + c*d*d + g*b*b - 2*b*d*f - a*c*g)/((b*b - a*c) * (Math.sqrt((a-c)*(a-c) + 4*b*b) - (a+c))));
    const radiusB = Math.sqrt(2*(a*f*f + c*d*d + g*b*b - 2*b*d*f - a*c*g)/((b*b - a*c) * (-Math.sqrt((a-c)*(a-c) + 4*b*b) - (a+c))));

    // deduce ellipse rotation from coefficients
    let angle = 0;
    if(b==0 && a <= c) {
        angle = 0;
    } else if(b == 0 && a >= c) {
        angle = Math.PI / 2;
    } else if(b != 0 && a > c) {
        angle = Math.PI / 2 + 0.5 * (Math.PI / 2 - Math.atan2((a-c), (2*b)));
    } else if(b != 0 && a <= c) {
        angle = Math.PI / 2 + 0.5 * (Math.PI / 2 - Math.atan2((a-c), (2*b)));
    }

    return {
        centerX, centerY, radiusA, radiusB, angle
    }

```

---
Tags: rendering, html5, projection, perspective, curves
---


# Question
Title: Is there a way to run a tool script without attaching it to a node in the scene tree?
What I want to do is run a tool script on the editor.
The usual way would be to attach it to a scene tree node, but then I'd have to guard it with `if`s all over to prevent editor code to be run at runtime and viceversa.

I could instantiate the script and run it directly without it being attached to a node, but the script that instantiates that script would have to be tool too, so not getting rid of the problem.

I guess I could create a node in the scene tree with a tool script attached, that removes itself from the scene tree once the game is running.

Is there a more elegant way of doing it?

Like some kind of project setting to run a tool script on project load?

# Answer
> 5 votes
In this answer I present a few approaches to run code in the editor. The first one is pretty much what you are already doing. If that is an option for you, it is an option for you.

The second is using `EditorScript`. Which technically accomplishes the "without attaching it to a node in the scene tree" requirement. But it is limited in what it can do.

The third is using `EditorPlugin`. Which solves the "run a tool script on project load" requirement. Except, oh, surprise, the Godot IDE has a scene tree, *which is not the scene tree of the game*. I believe that `EditorPlugin` is what you want.

Well, I suppose there is another way: Writing a Godot Module (with C++), which require building Godot from source to include. See Compiling.

---

## `tool` script

As you are aware, you can run GDScript in the IDE by making script a `tool` script (using the `tool` keyword). And you can check `Engine.editor_hint` to know when the code is running in the IDE.

Following that idea, you can have `tool` script, where check `Engine.editor_hint` is `true` and then instance there whatever you want to run only on the editor. If what you instanced there, is only instanced there… Well, you can forgo further checking.

*And yes, I suppose you can have it remove itself.*

---

## EditorScript

Create a new script that inherits from `EditorScript`. Make sure it is a `tool` script. Give it a `_run` function:

```
tool
extends EditorScript

func _run():
    print("Hello from the Godot Editor!")

```

This script runs from the Script Editor. With the script open, go to the File menu, and select Run. You can also use secondary click on the script on the Scripts Panel (on the left of the Script Editor) and select Run in the contextual menu.

---

## EditorPlugin

Go to the Project menu, then Project Settings, on the Plugin tab, click create.

It will open a dialog asking about the details of your plugin. At minimum give it a Name (first field), a subfolder (second field) and a Script Name (last field). You can leave the rest blank (and even edit it later).

It will generate a script that looks like this:

```
tool
extends EditorPlugin

func _enter_tree() -> void:
    pass

func _exit_tree() -> void:
    pass

```

This script runs on the editor only. You can enable it and disable it on the Plugin tab of the Project Settings (where you create it). And yes, this is how you make plugins/addons for Godot.

When you enable it (or when you load a project where it is enabled) it will run `_enter_tree`. Similarly when disabling (or unloading a project where it is enabled) it will run `_exit_tree`.

*To be clear, these will not run when you run the game (because, again, this script runs on the editor only).*

Reminder: The Godot UI is made with Godot. It has a scene tree.

The `EditorPlugin` API will give you access to more parts of the IDE that you usually would.

Refer to Editor plugins and `plugin` folder of the official godot-demo-projects repository (on Github).

---
Tags: godot, editors, gdscript
---


# Question
Title: Unity: Keyboard Shortcut to Deselect Game Object
How do you unselect a game Object in the 3d view using your keyboard?

# Answer
> 2 votes
Reading through the list of Unity editor keyboard shortcuts, it doesn't look like such a shortcut exists.

We can save & load selection presets using `Ctrl`+(`Alt`/`Shift`)+(`1`-`9`), but you can't directly save "no selection" into any of these slots. A workaround mentioned in the link Arthur Gibraltar provided is to create a dummy object, save a selection, then delete the dummy object to end up with a saved empty selection.

Instead of this fiddly process, we can add our own Select None shortcut with an editor script placed inside a folder called "Editor":

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

public static class SelectionHelpers {

    [MenuItem("Selection/Select All (Active Scene) %a")]
    public static void SelectAll() {
        var scene = EditorSceneManager.GetActiveScene();
        var objects = scene.GetRootGameObjects();
        Selection.objects = objects;
    }

    [MenuItem("Selection/Select None %q")]
    public static void SelectNone() {
        Selection.objects = new Object[0];
    }
}

```

With this script we can Select All with `Ctrl`+`A` (or +`A` on Mac),
and Select None with `Ctrl`+`Q` (or +`Q`)

# Answer
> 2 votes
Extending from DMGreggory's solution, we could simplify the `SelectNone` function even more:

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

public static class SelectionHelpers
{

    [MenuItem("Selection/Select None %q")]
    public static void SelectNone()
    {
        Selection.objects = null;
    }
}

```

Where the selected objects is being reset to null as opposed to adding an empty object each time we call `SelectNone()`. This reduces the chances of memory leakage on heap and therefore is a safer solution.

---
Tags: unity, interface
---


# Question
Title: Unpausing a game when a TouchScreenButton node is released
I'm making a mobile game in the Godot game engine. I made a spike scene where the spikes will respawn at a random time in a particular position moving upwards. Then I instanced the scene in the main scene, it worked perfectly, the spikes moving up and appearing in a particular position. Then I created a TouchScreenButton node in the main scene and changed it pause property to process and then added a \_OnPressed and \_OnReleased signal to the main scene script then added this code to the \_OnPressed function `get_tree().paused = true` And added this code to the \_OnReleased function `get_tree().paused = false`

But when ever I press and release the button it only pauses the scene

What should I do?

# Answer
The main node will not be able to receive signals when the tree is paused and it's pause mode is set to `inherit`. You should handle the signals in a node that has it's pause mode set to `process`.
> 0 votes

---
Tags: input, godot, touch
---


# Question
Title: Is it a bad idea to have several audio sources on the same object in unity?
The title is actually self-explanatory. I would like to know if there are any drawbacks (performance-wise, good-practice wise, etc.) for having multiple audio sources on the same GameObject. My initial intuition is that it gives me more freedom to have specific audio settings (volume, pitch, etc.) for each audio clip I want to play, but I want to know if this setup is advisable.

# Answer
As I was taught on *anything* about software development: ***it depends***.

Back in the days, memory and CPU were limited resources, and devs had to be extremely careful about data and cycles used by their software. An old-school video game would feature just a handful of mono sound effects (or background music only). Current video games exploit the power of end-user machines by playing multiple surround sounds for additional immersion.

It isn't bad to have multiple sound sources in your game, and it isn't necessarily a bad idea to assign different Audio Sources to the same object. After all, it would be quite odd if we could hear a character's footsteps originating from **their head** because we assigned one sound source only! On the other hand, it would be overkill to create too many specific sources for any possible sound your character could emit: footsteps, hands, voice, something in their pocket...

In Unity, the Audio Source component plays back an audio clip and defines the audio settings to apply (in the inspector). But, it only does so when we order it to; all other times, it's just storing (basically immutable) values. Performance is more about filtering sounds at runtime and streaming output audio. The Audio Profiler can help you with that by showing a lot of information useful for debugging. If too many sounds are playing at once, you will know. You can also limit the max number of real voices to limit the number of sources actually playing and reduce CPU usage. Besides, if the listener can't hear a specific sound, then it won't be played back. This is similar to graphics: even if an object mesh has a high number of vertices, there's no rendering overhead if the object isn't visible to the camera.

A sound position isn't tracked directly because it derives from the Transform the Audio Source is attached to, for free. Then, if you want different Sources moving around, you need to attach them to different Transforms in a GameObject hierarchy (like any other Component), and that's **by design**: the engine performs a huge number of matrix operations each update, so a couple more are not going to be a big deal. There are few meaningful cases for having multiple Audio Sources in the same GameObject, like the need for very different audio settings at the same 3D position, though these are uncommon.

A good practice to follow is limiting the number of resources as long as the final result is acceptable: I would go with 3 Audio Sources on a character: one for their mouth (at the top), one for their body (at the centre of mass), and another one for their feet (at the bottom). All additional sounds can be played by audio sources attached to different objects, or on-demand at a specific location.
> 4 votes

# Answer
While you *can* have multiple AudioSources on one GameObject, I would recommend creating multiple child GameObjects under one parent GameObject with one AudioSource on each child, because:

* calling `GetComponent` on a GameObject will only return the first AudioSource it finds, and
* clicking and dragging AudioSources into reference fields in the Inspector tab will always show the name of the GameObject, which does not help when there are multiple AudioSources on the same GameObject.

By having multiple child GameObjects with one AudioSource each, you can name each GameObject appropriately regarding the sound, which alleviates confusion as to which AudioSource is being referenced.
> 2 votes

---
Tags: unity, audio
---


# Question
Title: Make platformer character stay in the air at the top of a jump
I have a player who can jump. I want the character to stay in its position and not fall to the floor.

This is the code I am using so far:

```
private void FixedUpdate()
{
        if(moveup)
        {
            rigid.AddForce(new Vector3(0, 1f, 0) * speed, ForceMode2D.Impulse);
            moveup = false;
        }
}

```

How can I stop the character from falling?

# Answer
Just change the

```
void Update()

```

to

```
void UpdateFixed()

```

I hope this solves your problem.

But turn off the collider for the player and make sure you have a rigidbody on ALL assets.

Also, make sure the character isn't in the ground when the game starts.
> -1 votes

---
Tags: unity, 2d, physics, platformer, jumping
---


title: How to use Left-Shift to run?

text:
# Question
Title: How to use Left-Shift to run?
I need to use Left-Shift to run, but I can't figure out how to do so.

Here my code:

```
using UnityEngine;
using System.Collections;

// This script moves the character controller forward
// and sideways based on the arrow keys.
// It also jumps when pressing space.
// Make sure to attach a character controller to the same game object.
// It is recommended that you make only one call to Move or SimpleMove per frame.

public class Move : MonoBehaviour
{
    CharacterController characterController;

    public float speed = 6.0f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;
    public Transform charBody;
    private Vector3 moveDirection = Vector3.zero;
    public float mouseSense = 11f;
    public float runSpeed = 12f;
    public bool isRunning = false;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (characterController.isGrounded)
        {
            // We are grounded, so recalculate
            // move direction directly from axes

            moveDirection = transform.forward * Input.GetAxis("Horizontal") + transform.right * Input.GetAxis("Vertical");
            moveDirection *= speed;
            moveDirection = transform.right * Input.GetAxis("Horizontal") + transform.right * Input.GetAxis("Vertical");
            moveDirection *= speed;

            if (Input.GetButton("Jump"))
            {
                moveDirection.y = jumpSpeed;
            }
        }

        // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
        // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
        // as an acceleration (ms^-2)
        moveDirection.y -= gravity * Time.deltaTime;

        // Move the controller
        characterController.Move(moveDirection * Time.deltaTime);

        float MOUSEY = Input.GetAxis("Mouse Y") * mouseSense * Time.deltaTime;
        float MOUSEX = Input.GetAxis("Mouse X") * mouseSense * Time.deltaTime;

        charBody.Rotate(Vector3.up * MOUSEX);

    }
}

```

When Left-Shift is pressed I want the speed to change to runSpeed.

# Answer
> 2 votes
First I would rename the variable `speed` to `walkSpeed` to better differentiate it from `runSpeed`. Then I would create a local variable `speed` in `Update` and assign it based on the current state of the shift key:

```
float speed;
if (Input.GetKey(KeyCode.LeftShift)) {
    speed = runSpeed;
} else {
    speed = walkSpeed;
}

```

This architecture also allows to take other circumstantial modifiers to the character speed into account.

Then I would use that local speed variable to calculate the moveDirection:

```
Vector3 input = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical");
moveDirection = transform.right * input * runSpeed;

moveDirection.y -= gravity * Time.deltaTime;

characterController.Move(moveDirection * Time.deltaTime);

```

# Answer
> 0 votes
Answer:

using UnityEngine;
using System.Collections;

// This script moves the character controller forward
// and sideways based on the arrow keys.
// It also jumps when pressing space.
// Make sure to attach a character controller to the same game object.
// It is recommended that you make only one call to Move or SimpleMove per frame.

public class Move : MonoBehaviour
{
    CharacterController characterController;

    public float speed = 6.0f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;
    public Transform charBody;
    private Vector3 moveDirection = Vector3.zero;
    public float mouseSense = 11f;
    public float runSpeed = 12f;
    public bool isRunning = false;
    float camRot = 0f;
    public Transform altCamera;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (characterController.isGrounded)
        {
            // We are grounded, so recalculate
            // move direction directly from axes

            moveDirection = transform.forward * Input.GetAxis("Horizontal") + transform.right * Input.GetAxis("Vertical");
            moveDirection *= speed;
            moveDirection = transform.right * Input.GetAxis("Horizontal") + transform.right * Input.GetAxis("Vertical");
            moveDirection *= speed;

            if (Input.GetButton("Jump"))
            {
                moveDirection.y = jumpSpeed;
            }

            if (Input.GetKey(KeyCode.LeftShift))
            {
                moveDirection = transform.forward * Input.GetAxis("Horizontal") + transform.right * Input.GetAxis("Vertical");
                moveDirection *= runSpeed;
                moveDirection = transform.right * Input.GetAxis("Horizontal") + transform.right * Input.GetAxis("Vertical");
                moveDirection *= runSpeed;

            }
        }

        // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
        // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
        // as an acceleration (ms^-2)
        moveDirection.y -= gravity * Time.deltaTime;

        // Move the controller
        characterController.Move(moveDirection * Time.deltaTime);

        float MOUSEY = Input.GetAxis("Mouse Y") * mouseSense * Time.deltaTime;
        float MOUSEX = Input.GetAxis("Mouse X") * mouseSense * Time.deltaTime;

        charBody.Rotate(Vector3.up * MOUSEX);

    }
}
```

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


title: How to I make MOUSEY look up

text:
# Question
Title: How to I make MOUSEY look up
I have MOUSEX worked out perfectly, it moves on the X axis, but when I add the Y axis, I can't use the MOUSEX axis.

```
using UnityEngine;
using System.Collections;

// This script moves the character controller forward
// and sideways based on the arrow keys.
// It also jumps when pressing space.
// Make sure to attach a character controller to the same game object.
// It is recommended that you make only one call to Move or SimpleMove per frame.

public class Move : MonoBehaviour
{
    CharacterController characterController;

    public float speed = 6.0f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;
    public Transform charBody;
    private Vector3 moveDirection = Vector3.zero;
    public float mouseSense = 11f;
    public float runSpeed = 12f;
    public bool isRunning = false;
    float camRot = 0f;
    public Transform altCamera;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (characterController.isGrounded)
        {
            // We are grounded, so recalculate
            // move direction directly from axes

            moveDirection = transform.forward * Input.GetAxis("Horizontal") + transform.right * Input.GetAxis("Vertical");
            moveDirection *= speed;
            moveDirection = transform.right * Input.GetAxis("Horizontal") + transform.right * Input.GetAxis("Vertical");
            moveDirection *= speed;

            if (Input.GetButton("Jump"))
            {
                moveDirection.y = jumpSpeed;
            }

            if (Input.GetKey(KeyCode.LeftShift))
            {
                moveDirection = transform.forward * Input.GetAxis("Horizontal") + transform.right * Input.GetAxis("Vertical");
                moveDirection *= runSpeed;
                moveDirection = transform.right * Input.GetAxis("Horizontal") + transform.right * Input.GetAxis("Vertical");
                moveDirection *= runSpeed;

            }
        }

        // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
        // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
        // as an acceleration (ms^-2)
        moveDirection.y -= gravity * Time.deltaTime;

        // Move the controller
        characterController.Move(moveDirection * Time.deltaTime);

        float MOUSEY = Input.GetAxis("Mouse Y") * mouseSense * Time.deltaTime;
        float MOUSEX = Input.GetAxis("Mouse X") * mouseSense * Time.deltaTime;

        charBody.Rotate(Vector3.up * MOUSEX);

    }
}

```

Here's my code.

but when i add:

```
camRot -= MOUSEY;
transform.localRotation = Quaternion.Euler(camRot, 0f, 0f);
camRot = Mathf.Clamp(camRot, -90f, 90f);

```

The MOUSEX axis doesn't work, and the MOUSEY moves up and down, with the MOUSE axis, but doesn't clamp and the MOUSEX doesn't rotate.

Help please?

Thanks

# Answer
> 1 votes
This line:

```
transform.localRotation = Quaternion.Euler(camRot, 0f, 0f);

```

...says "throw out whatever rotation you had before, and replace it with this one that I constructed from one Euler angle"

So any rotation you worked hard to make on the yaw axis is discarded, and you end up with pitch-only rotation, because that's what you've provided on the right hand side of the equation to replace it with.

You might want to make your `camRot` variable a 2-component vector. That way you can store both yaw and pitch and apply them in the same expression.

```
// Put this instead of camRot where you define your member variables.
private Vector2 _cameraAngles;

// ...

// Inside Update, increment your angles:
_cameraAngles.x -= Input.GetAxis("Mouse Y") * mouseSensitivity;
_cameraAngles.y += Input.GetAxis("Mouse X") * mouseSensitivity;

// Apply your clamping to the pitch axis:
_cameraAngles.x = Mathf.Clamp(_cameraAngles.x, -90f, 90f);
// Optionally, you might also want to wrap your yaw into a fixed range, like -180 to 180:
_cameraAngles.y = Mathf.DeltaAngle(0f, _cameraAngles.y);

// Apply the rotation all at once:
transform.localRotation = Quaternion.Euler(_cameraAngles);

```

Note that we do not multiply the mouse travel by `Time.deltaTime`. These inputs measure how far the mouse has travelled *over the duration* of the previous frame, so they already have a factor of time baked-into them. If we multiply these by `Time.deltaTime`, we "double dip", and can get unwanted inconsistencies in the rate of rotation at different framerates.

---
Tags: rotation, movement
---


# Question
Title: How to set the hair_mesh to follow the animation?
How to set the hair mesh to follow the animation? I am trying this.

```
.cpp
Hair = CreateDefaultSubobject<USkeletalMeshComponent>("Hair");
    Hair->SetupAttachment(GetMesh());
    Hair->AttachToComponent(MyCharacter::GetMesh(), FAttachmentTransformRules::KeepWorldTransform, TEXT("head"));

.h
UPROPERTY(EditAnywhere, Category = "Components")
    class USkeletalMeshComponent* Hair;

```

I have attached the hair mesh to the `Head` socket but the hair mesh is not following the animation. The hair mesh is called `Hair_Mesh` and has been attached in the editor while the `Hair` skeletal mesh component is already sets to `UPROPERTY(EditAnywhere, Category = "Components")`

# Answer
> 0 votes
By the looks of it, the hair is attaching to the mesh but isn't animating.

You can set the Hair component to use the animation of the mesh by calling it's Master Pose Component.

```
Hair->SetMasterPoseComponent(GetMesh());

```

You put this in your cpp constructor under where you've attached it to the mesh.

# Answer
> -1 votes
```
**.h**
UPROPERTY(BlueprintReadWrite, NonTransactional, meta = (Category = "Default", OverrideNativeName = "Hair"))
        USkeletalMeshComponent* Hair;
    UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, meta = (DisplayName = "Skin Met R", Category = "SkeletalMesh", MultiLine = "true", OverrideNativeName = "SkinMetR"))
        UMaterialInstanceDynamic* SkinMetR;
    AMyCharacter(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
    virtual void PostLoadSubobjects(FObjectInstancingGraph* OuterInstanceGraph) override;
    static void CustomDynamicClassInitialization(UDynamicClass* InDynamicClass);
    static void StaticDependenciesAssets(TArray<FBlueprintDependencyData>& AssetsToLoad);
    static void StaticDependencies_DirectlyUsedAssets(TArray<FBlueprintDependencyData>& AssetsToLoad);
virtual void UserConstructionScript();
    UFUNCTION(BlueprintCallable, meta = (Category = "SkeletalMesh", OverrideNativeName = "InitSkeletalMesh"))
        virtual void InitSkeletalMesh()

**.cpp**
void AMyCharacter::InitSkeletalMesh(){
bool CallFunc_K2_AttachToComponent_ReturnValue{};
    if(::IsValid(Hair))
    {
        CallFunc_K2_AttachToComponent_ReturnValue = Hair->USceneComponent::K2_AttachToComponent((*(AccessPrivateProperty<USkeletalMeshComponent* >((this), ACharacter::Mesh() ))), FName(TEXT("head")), EAttachmentRule::KeepWorld, EAttachmentRule::KeepWorld, EAttachmentRule::KeepWorld, true);
    }
}

```

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


# Question
Title: What's the best way to draw gizmos in build
I currently use Unity gizmos for many debugging purposes, but I'd like almost all of them to be visible to the player in-game (when the game is built).

For example, when a player is dragging to place a wall along a grid, I use Gizmos.DrawCube.

I know of a couple of options:

1. ALINE - an asset on Unity asset store, but currently doesn't work with 2D Experimental URP
2. Line renderer - seems very manual and tedious to do, and I'm unsure how I could modify it using code
3. Placing pictures as UI elements over selected tiles (seems pretty expensive to do?)

Any suggestions are appreciated!

# Answer
> 1 votes
Gizmos are for development, not for playing. The usual approach to implement a gizmo would be to create a gameObject representing said gizmo which you activate and deactivate as needed.

So instead of:

```
if (isDragging) {
     Gizmos.DrawCube(dragPosition, dragSize);
}

```

You write:

```
if (isDragging) {
     myGizmo.SetActive(true);
     myGizmo.transform.position = dragPosition;
     myGizmo.transform.scale = dragSize;
} else {
     myGizmo.SetActive(false);
}

```

While this seems a bit more convoluted, think of all the possibilities you have when your gizmos are full-fledged gameObjects which can have any kind of visual and logical components you want.

---
Tags: unity, rendering, gui, unity-ui
---


# Question
Title: How can I mod a Minecraft slime to be about the size of a full block?
I want to make the slime's size roughly the size of a full block, I have tried some values but I'm not sure if any of those I tried fit the idea I have.

What would you recommend for the size of the slime which roughly matches or matches a block's size?

# Answer
> 3 votes
# You can't.

You can't make a "size" 1.8 slime. The closest you can get is a size 2 slime because `Slime.setSize(int)` only takes an integer because the `Size` NBT tag within a slime only takes an integer too.

See this.

---
Tags: minecraft-modding, bukkit
---


# Question
Title: How can I switch the default map to UI in order to pause the game?
I've recently set up the new Input System using Player Input component and invoke unity events. I just have one problem; I want to change the default action map to UI whenever I press the defined pause buttons because pausing won't work when the defualt map is set to Player. I want to do this via code and in `PauseInput` function. I tried using `playerInput.SwitchCurrentActionMap` but it didn't work for me. Also, I don't use a generated c# script for the player inputs. Any guidance would be appreciated.

Here's my pause menu code:

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

public class PauseMenu : MonoBehaviour
{
    public static bool GameIsPaused = false;
    public PlayerInput playerInput;
    public GameObject pauseMenuUI;

    public void OnPause(InputAction.CallbackContext context) {
      if (context.phase == InputActionPhase.Performed) {

          if (GameIsPaused) {
              Resume();
          } else {
             Pause();
          }
     }
}

    public void Resume()
    {
        playerInput.SwitchCurrentActionMap("Player");
        pauseMenuUI.SetActive(false);
        Time.timeScale = 1f;
        GameIsPaused = false;
    }

   public void Pause ()
    {
        playerInput.SwitchCurrentActionMap("UI");
        pauseMenuUI.SetActive(true);
        Time.timeScale = 0f;
        GameIsPaused = true;
    }
}

```

As you can see, I want to change the default map from Player to UI whenever the pause button is pressed and switch back to Player whenever the button is pressed again (resume); because there can only be one active map at a time.

# Answer
Remember that the callbacks get called for multiple distinct reasons, indicated by the `phase` member of the action and its context:

* **Started**: when interaction with the control begins (eg. the start of a hold/tap)
* **Performed**: when the action has been triggered (eg. pressing a button)
* **Canceled**: when the action has ended or been aborted (eg. if the player releases the button, or if the action map changes while the button is held)

So when the player presses the pause button, the following things happen:

1. `OnPause` gets called with `phase = InputActionPhase.Started`
2. You switch the action map before pausing the game.
3. Switching the action map disables the "Player" version of this control and enables the "UI" version, so `OnPause` immediately gets called with `phase = InputActionPhase.Canceled`.
4. You switch the action map before pausing the game.
5. Switching the action map disables the "UI" version of this control and enables the "OnPause" version, so `OnPause` immediately gets called with `phase = InputActionPhase.Canceled`.
6. We're back to step 2 again, and we loop steps 2-5 indefinitely. We never get to finish running the `Pause` method, because it keeps getting interrupted to send another cancelled message, leaving half-finished calls on the stack until we overflow.

So, make sure you check to see if the action is being *performed* before you act on it, so that you don't loop endlessly cancelling actions.

```
public void OnPause(InputAction.CallbackContext context) {
    if {context.phase == InputActionPhase.Performed) {

        if (GameIsPaused) {
            Resume();
        } else {
            Pause();
        }
    }
}

```

And don't forget to wire up your `UnityEvents` for both the Player and UI maps. That is, both your Player and UI maps should contain a "Pause/Unpause" action whose `UnityEvent` calls `OnPause`
> 2 votes

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


# Question
Title: Materials aren't loading correctly from SketchUp into Unity
I imported a SketchUp COLLADA (.dae) file from 2017 SketchUp Make, and imported it into Unity. I then clicked "Use External Materials" and the colors began to load. But I noticed quickly that one of the wings of my imported B-29 was Dark Gray, while the other way a proper color. Random parts, such as the front engine housing piece, were also dark gray. Parts of my advanced dials were also dark gray, and I immediately decided that there is now ay that I am going to manually go in and fix every single dark-gray material, but at the moment, I found no alternative.

I began with the wing. I went to assign the material that I used for the other wing, which was white, to the dark gray wing, but I found out that the other wing *already had* that material in use. And when I went to assign a different white color, absolutely nothing changed, aside from the fact that the wing now claimed that it had that color in use. Is there a fix for this problem? I could try importing as a .SKP file, if the reason for the issue is something to do with the COLLADA (.dae) file.

What I had was 2 wings. they were both components in SketchUp, so whatever I did to one applied to the other, Then I made them unique before importing to Unity. The Wing that won't work right is the one wing that had the USAF Insignia on it. But I doubt this is the problem, because all engines on that wing were also not colored correctly, whereas the other wing was fine. Those engines were also components, but were also made unique before the import.

Each wing has 9 groups inside of it. The other wing is identical in this sense. I imported the file from file explorer by dragging the file from file explorer and dropping it into unity.

This is what the plane looks like in Unity:

My apologies for the crude handwriting, it is difficult to draw with a touchpad. In the image, I numbered the incorrectly-colored parts visible in the image (Right/Left references are perspective to image)

**1.** Left Wing. **Color:** Dark gray. **Color intended:** White.

**2.** Propeller blade hub. This is the part that all propeller blades are connected to. Both hubs on the two propellers on the Left Wing are colored incorrectly. **Color:** white. **Color Intended:** Grey.

**3.** Pistons. All piston components, such as the pistons, securing poles, and piston heads are not colored correctly; same on the other engine on the Left Wing. **Color:** White. **Color Intended:** Grey pistons, darkish-grey piston heads, and copper-orange securing poles.

**4.** Cowl Flaps. In the image, this appears to be a stripe in the engine. Same with the other cowl flaps on the other engine on the Left Wing. **Color:** Dark gray. **Color Intended:** White.

**5.** Propeller blades. All 4 propeller blades on both engines on the left wing are not colored correctly. **Color:** White. **Color Intended:** Black, with yellow tips.

**6.** Right-Wing Pistons. Most piston components, such as the pistons heads and securing poles are not colored correctly. Same with the other engine on the Right Wing. **Color:** White Piston Heads, Grey Pistons, Almost-Black Gray in the lines on the pistons, white securing poles. **Color Intended:** Grey pistons, darkish-grey piston heads, and copper-orange securing poles.

**7.** Front Engine Casing. The same error is in the other engine's front engine casing on the Right Wing. **Color:** Dark Gray, with an apparent shine coming from beneath the part, which shouldn't be happening (the directional light is above the engine part). **Color Intended:** White.

**8.** Rear Engine Casing. The same error is in the other engine's rear engine casing on the Right Wing. **Color:** Dark Gray, with an apparent shine coming from beneath the part, which shouldn't be happening (the directional light is above the engine part). **Color Intended:** White.

# Answer
Just go to the **materials** section of the asset, then select **"Use Embedded Materials"** and change it to **"Use External Materials (Legacy)"** then click **"By Model's Name + Model's Material"** and change it to **"By Base Texture Name."** and then select **"Local Materials Folder"** and change it to **"Project-Wide."** then click **"Apply."** you will then see a Sketchup Importing window, showing the import progress. **after this is complete, all *(or almost all)* of your materials should be assigned properly.**
> 0 votes

---
Tags: unity, materials, sketchup
---


# Question
Title: Remove sprite reference before build in Unity
All the the characters in my 2D game have SpriteRenderers to animate the characters. Some of the characters are only active in their scenes sometimes, so I load their sprites asynchronously based on game state.

During edit mode, I have at least one sprite from an animation assigned to each sprite renderer so I can tell where the game object is. The problem is that including even a single sprite will load up the entire sprite atlas at runtime if I allow the SpriteRenderer.sprite to be set.

Is there an efficient way to unset the SpriteRenderer.sprite for a build, but not during edit time? Is there a better way to handle this?

EDIT: So I finally had a chance to play around with gizmos and the trouble is that some of my characters require multiple sprite renderers, and the scale of the object doesn't seem to affect the gizmo which is important for positioning within the level.

It would be ideal to have the sprites unset just before building.

# Answer
Rather than assigning a sprite in the Inspector for visualization purposes, it may be better to visualize these otherwise-invisible GameObjects using gizmos. The most relevant gizmo is probably `Gizmos.DrawIcon()`:

```
void OnDrawGizmos()
{
    Gizmos.DrawIcon(transform.position, "PlaceholderIcon.png", true);
}

```

The icon image needs to be located in an `Assets/Gizmos/` folder.
> 2 votes

---
Tags: unity
---


# Question
Title: What are good ways to keep the player spending in a single-player RPG?
I'm designing a game where I want the player to take the in-game money into consideration as opposed to majority where they just get rich pretty much all the time with nothing meaningful to spend it on. What are some good ways to keep them spending their money without making it feel like a tedious chore?

I'm already planning to have monsters nor quests not give gold.

And if preventing them from becoming extremely rich eventually is not possible, at least mitigate "easy" ways of generating infinite income. I want them to struggle with their money.

# Answer
> 5 votes
Most RPGs provide a ton of loot to sell. In 'Gothic', you didn't have money, but traded magical ore as hard currency aka sound money. But if the supply of tradeable items with a vendor was up, tough luck. Nothing to get from that person anymore. (Ignoring exploits like waiting for swords to spawn in the blacksmith's inventory so he can play his sharpening the sword animation.)

What games usually don't have is a real market. Why can I beat green slime in the forest and obtain e.g. leaves (craft item) ad infinitum, and sell them at a fixed price forever? When the market is saturated on leaves, make the price go down. Eventually you'll have to trade in a sack of leaves for an apple because everyone has leaves coming out of their ears thanks to you selling them this crap.

That would tackle not drowning in infinite money. It'd also introduce a simulation of trading that rewards supply and demand considerations in different locations, which may not be what you're looking to implement.

Look for opportunities to spend more money. A night at the inn for healing, but not like in most JRPGs where the 1st town costs 5 gold and the second costs 10 gold and so on, increasing cost arbitrarily with story progression. Make it cost a reasonable price per party member, balancing the benefits of larger parties. Introduce damage to gear which decreases combat effectiveness and increases maintenance cost.

Combined with finite resources in the world of NPCs and you may end up with a survival RPG :)

When there's no government to print money, it boils down to a fixed amount of e.g. gold that was mined until the game began, and continues to be mined as the game goes on. Like X gold/day from a mining facility that gets distributed between settlements and vendors. Sounds complicated, but can boil down to the amount of X gold being divided among the N settlements and then the Z vendors for a start: `perVendorGoldIncrease=X/N/Z`

That makes "ass-pricing" (Jason Fried) of items difficult. The price of apple, potion, sword, magic capes -- a round number for each item like 5g, 50g, 500g, 2500g in yer good ole JRPG won't do. You'd have to test prices a lot to see how players stop starving to death on day 4.

Drowning in money is easier than having a somewhat realistic simulation of being a poor peasant :)

# Answer
> 4 votes
1. Put a limit on how much money there is in the game. You can accomplish that by avoiding any sources of money which can be exploited over and over again (like respawning enemies which drop money or sellable loot). Now you know exactly how much money the player can collect at most during their playthrough.
2. Make sure there is more stuff the player would like to buy than there is money in the game.

That way you force the player to make meaningful choices about how to spend the limited amount of money in the game.

If you don't do 1 properly, then you can't realistically do 2, because a determined player will just grind and grind until they can buy everything. They will have an awful time, and then write a bad review about your game being too grindy. And that would be **your** fault (As Civilization game designer Soren Johnson wrote: *"Given the opportunity, players will optimize the fun out of a game"*).

Keep in mind that this system means that any wealth spent is lost forever. So you might want to avoid any trades which destroy wealth:

* You might not want to sell consumable resources (if you want consumable resources in your game, then consider a crafting system, a free-refill system or to grind infinitely for consumables).
* You also don't want to sell any services which don't offer any permanent progression (like healing or fast-travel).
* If you want to allow the player to sell items they bought, they should be able to sell them at full price (this mechanic is usually a money sink which you won't need in this system).
* If you don't want to allow selling, then you might want to make sure that anything the player buys will give them a benefit until the end of the game, and not be made obsolete by a strictly better version of the same item which becomes available later.

# Answer
> 1 votes
My take on this is that any infinite source of money is to be avoided. For example, enemies or even a boss that respawns and drop money or loot every time killed. In effect, the player must keep moving forward because whatever is behind is simply not profitable.

You can do whatever you're currently doing, but **put a cap on everything.** Maybe the enemies only drop loot the first few times or the first time? Maybe resources don't grow back when you harvest them? The player will learn soon enough the path you've chosen for this game.

For items actually on sale, don't have that ultra expensive overpowered item. Have a bunch of items which fit different playstyles and can form synergies with each other easily. This, combined with the finite money, forces the player to really think about every decision they make in game, since they can't buy everything. You say you want the player to "struggle" with their money. The easiest way to do that is choice. **Lots of choice.**

Of course, don't make twenty of the same item with slightly different stats. That's boring. **Make each item feel unique**, because then the opportunity cost of not buying any item increases drastically. Opportunity cost is only perceived, but it is a very powerful effect and forces the player to really think about their choices.

This also has the added effect of allowing many more varied play styles, and in turn allows for more replayability. Another idea you might want to explore is emergent gameplay, since that's something that goes very with this sort of design.

Basically, lots of items to spend money on but finite money leads to increased opportunity cost, which forces the player to really think about their choices, while making sure that grinding for money is completely eliminated from the game.

This answer is deliberately vague as to not push you in any direction. Be as creative as you like with those hard choices!

---
Tags: game-design, rpg, economy
---


# Question
Title: Advantage of Using Addressable Over Asset Bundles in Unity
I have a project that already uses asset bundles. I download assets when the game starts and show them to the user when needed.

I see that Unity provides addressables as new solution for asset management. As its new (not very new as its accessible from 2018.2, but official docs dont say a lot) there is not so much about it on the web.

From what it seems, in addressables you dont need to care about the bundle version, or which asset is in which bundle. In addresables, Unity automatically uploads assets to your host, and Unity automatically correctly manages local caching or downloads from a server, so objects behave like they are in the main game package but you have to check if they are loaded or downloaded. Am I right? Are there any other features that addressables offer?

# Answer
The main advantage of Addressables is that they make it very easy for your game to acquire a certain asset by name at runtime.

This used to be pretty annoying with asset bundles. First you had to know in which asset bundles that asset was hiding in. Then you had to find out if this asset bundles was already loaded, and when it wasn't you had to load it first. And only then were you able to retrieve the asset with `assetBundle.LoadAsset(name)`.

But with Addressables you just need to know the address string. You can then just do `Addressables.LoadAsset<Type>(address);` and Unity will automatically find out if the asset and its dependencies need to be loaded from the local filesystem or from a remote server and do so if necessary.
> 3 votes

# Answer
Personally I also don't get it. If you made the game and you saved your content intelligently then knowing where an asset is located is as easy as knowing the filepath to it (rather than a file url). Using the old WWW.LoadFromCacheOrDownload() meant getting ahold of the latest version and loading it was one line of code.

This means that in the old way you have to upload a new asset bundle each time you rebuild it and just place it at the same URL where you placed it before. Job done.

Now you first have to create online projects to generate buckets and keys for the project and buckets so you can then download a CLI to authorize your system before you can then go into Unity and create a URL based of an existing URL you just magically have to know and then augmented with 2 of the API keys you get from the online project under a few submenus deep before you can finally get around to building the asset bundles (hey look, back to where we started) and publish it to the development URL until you are ready to release in which case you build and publish to the release bucket and NOW... now it is so much easier to use because now you just have to know the address string which is sooooooo much easier than knowing the file path you placed your content into.

Soooooo much easier... only not!
> 1 votes

---
Tags: unity, asset-management, assetbundle, addressable
---


# Question
Title: How do I enable and disable objects with a certain tag in C#?
I have a script that is supposed to find every active object with a certain tag and on the push of a button enable and disable it's meshrenderer and collider. but the script only tries to enable and disable the previous on the object the script is attached to. what am i doing wrong and is there any feasible way to do this?

I've checked all tags, but the script keeps trying to reach this unrelated object. i even tried adding a mesh renderer and a colider. but nothing

here is the script:

```
private bool on = true;

public void Update()
{
    GameObject[] gameObjectArray = GameObject.FindGameObjectsWithTag("buildnode");

    if (Input.GetKeyDown("b"))
    {
        on = !on;
    }

    if (on == false)
    {
        foreach (GameObject go in GameObject.FindGameObjectsWithTag("buildnode"))
        {
            go.GetComponent<MeshRenderer>().enabled = false;
            go.GetComponent<Collider>().enabled = false;
        }
    }

    if (on==true)
    {
        foreach (GameObject go in GameObject.FindGameObjectsWithTag("buildnode"))
        {
            go.GetComponent<MeshRenderer>().enabled = true;
            go.GetComponent<Collider>().enabled = true;
        }
    }
}

```

Thank you and have a good day.

# Answer
> 1 votes
It seems like this code should work, you probably need to add checks to make sure the gameObject is active, and has the components you want to work with. Do this with a LINQ where clause like this:

```
  GameObject[] gameObjectArray = GameObject.FindGameObjectsWithTag("buildnode")
     .Where(go => go.activeInHierarchy &&
                  go.GetComponent<MeshRenderer>() &&
                  go.GetComponent<Collider>())
     .ToArray();

```

then you can really simplify the if statements by just removing them:

```
foreach(var go in gameObjectArray){
     go.GetComponent<MeshRenderer>().enabled = on;
     go.GetComponent<Collider>().enabled = on;
}

```

# Answer
> 0 votes
You cant find Disabled Objects with `GameObject.FindGameObjectsWithTag("buildnode")`

you can find object you want using:

```
  GameObject[] items=     Resources.FindObjectsOfTypeAll(typeof(UnityEngine.GameObject)) as GameObject[];
  GameObject obj = items.FirstOrDefault(x=>x.tag=="mytag");

```

# Answer
> 0 votes
Iterating on the answer by Glenn van Acker.

When you are already using a LINQ chain, then you can just as well avoid the duplicate calls to GetComponent by using the LINQ .Select to transform a gameObject into an anonymous class (aka "tuple") with two variables `meshRenderer` and `collider`. And you can avoid the conversion to an array by feeding the results of the LINQ query directly into a a `foreach` loop:

```
    foreach(var tuple in
        GameObject.FindGameObjectsWithTag("Respawn")
        .Where(go => go.activeInHierarchy)
        .Select(go => new {
            meshRenderer = go.GetComponent<MeshRenderer>(),
            collider = go.GetComponent<Collider>()
        })
        .Where(tuple => tuple.meshRenderer &&
                        tuple.collider))
    {
        tuple.meshRenderer.enabled = true;
        tuple.collider.enabled = true;
    }

```

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


# Question
Title: Managing multiple animation files in a Unity project
I am on my project, but find it hard to understand what I'm missing from those few animation and rigging tutorials.

I have an FBX I modelled and rigged from blender... Or I could just take a model from Mixamo or other resources.

Is it possible to have loosely coupled .anim files which could be mix-matched at runtime with different FBXs?

It seems the Animator Controller can reference each .anim file independently if necessary, so I guess we can make one animation per fbx and split anim files in Unity project explorer... There must be a better way, right?

# Answer
Yes, it is possible to assign the same AnimationController with the same animations to two different models. However, it can be problematic if the rigs of the two models differ. Either make sure that both models have a rig with identical hierarchy and identically named bones, or use avatars which translate the bone names between the two models.

For more information, check out the article in the Unity documentation about animation retargeting.
> 0 votes

---
Tags: unity, animation, fbx, rigging, asset-workflow
---


# Question
Title: Why does Unity call certain methods "messages"?
I just surprised that the Unity documentation calls methods like Update or Start or Awake "Messages" rather than methods.

Does that mean those methods are used to send a message to something?

# Answer
> 2 votes
Methods like `Start` or `Update` are called message methods because these methods get called through the Unity Message System.

You might notice that all those methods don't have an access modifier in the standard template for new MonoBehaviours. When you are familiar with the C# programming language outside of the context of Unity, then you might realize that this means they are actually declared `private`. Which means it should not be possible for them to get called from anywhere except from inside the same class. So how is it possible for those methods to get called by the engine at all? It's because the Unity messaging system uses runtime reflection to find and call private methods of your scripts.

You can actually use the Unity messaging system yourself. The method `gameObject.SendMessage(string methodName)` scans all scripts on the gameObject for methods of that name (no matter if public, internal, protected or private) and calls all of them. I would not *recommend* that for various software architecture reasons, but you can.

*Why* did Unity choose to implement the most essential part of their API architecture in a way most experienced developers disdain and they themselves no longer recommend anymore? Because in the early days of the engine, their primary target demographic were novice developers. So they prioritized code simplicity over performance and clean architecture. Their demographic shifted in the past couple years to a more professional audience, but it's hard to get rid of early sins in such a a well-established software product (unless you reinvent your whole scripting API from scratch).

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


# Question
Title: Unity 'Collider.bounds.Intersects'. Does it handle rotation?
You will probably laugh at my code here (and I would love to hear some completely different approaches to this problem if possible), but I've written this myself using the only logic I could come up with alone.

Basically I want to make a slope randomly covered with trees. The slope is a quad with a mesh collider (I've also tried Box), and the tree is a prefab with just a model and a collider. I iterate through every possible tree location and give it a 0.25 chance of spawning a tree. This all works ok, but since the quad is not lying flat to any axis, I couldn't think how best to assign the Y-position value to my trees.

My idea was to simply drop the trees all from above and have them land in the quads collider. If I lay the quad flat my code will work fine, but as soon as I tilt the slope the collision is still detected. It seems as if its reading the top of the quads highest point and making a box around it all the way to the bottom.

This is the code:

```
        for (int i = 0; i < trees.Count; i++)
        {
            if (!trees[i].GetComponent<Collider>().bounds.Intersects(ski_slope.GetComponent<Collider>().bounds))
            {
                Debug.Log("moving tree");
                trees[i].transform.Translate(0, -0.2f, 0);

            }
        }

```

So really I think my use of the 'Intersects' function must be wrong.

I hope my description of the problem makes sense. Otherwise I can take some screenshots to try show it.

Thank you for any help.

# Answer
> 1 votes
This is one of those many situations where reading the documentation helps.

The documentation for the Bounds type tells you that it:

> Represents an axis aligned bounding box.
>
> An axis-aligned bounding box, or AABB for short, is a box aligned with coordinate axes and fully enclosing some object. Because the box is **never rotated** with respect to the axes, it can be defined by just its center and extents, or alternatively by min and max points.

The documentation for Collider.bounds tells you it's:

> The **world space** bounding volume of the collider (Read Only).
>
> Note that this will be an empty bounding box if the collider is disabled or the game object is inactive.

So when you say:

> It seems as if its reading the top of the quads highest point and making a box around it all the way to the bottom.

Yes, that is *exactly* what you asked it to do. Asking for `Collider.bounds` says "find the highest, lowest, northmost, eastmost, southmost, and westmost points of this collider and give me a box aligned with the world axes enclosing those extremes".

Did you mean to use a raycast, spherecast, or boxcast sweeping downward to find the first intersection point with your mesh collider instead?

---
Tags: unity, c#, collision-detection
---


# Question
Title: how to center 3d camera vertically and horizontally
How to center the `player/camera` in the middle of the `window/screen` , to mimic a `2.5d` camera, so it looks like this game:

where I can move vertically and horizontally , and the camera still be centered on the player?

Edit: I want to center it 18 pixels in the 4 directions

# Answer
**Follow position**

What first comes to mind is to use a `RemoteTransform`. You can set its remote path is the player avatar, and to only update the position (not the rotation, not the scale). Then make the `Camera` a child of the `RemoteTransform` and give it is rotation and offset position.

I suggest to use the split view (click View on the top of the editor and select Two Viewports) and then use one to preview the camera and the other to move it.

---

**Follow x and z**

Sadly `RemoteTrasnform` does not gives you the granularity to say that you want to follow the x and z but not the y. However we can mimic it:

```
tool
extends Spatial

export var remote_path:NodePath
export var y:float

func _process(_delta: float) -> void:
    var target = get_node_or_null(remote_path) as Spatial
    if !is_instance_valid(target):
        return # either null or freed

    var target_position = target.global_transform.origin
    var position = Vector3(target_position.x, y, target_position.z)
    global_transform = Transform.IDENTITY.translated(position)

func _get_configuration_warning() -> String:
    var target = get_node_or_null(remote_path) as Spatial
    if is_instance_valid(target):
        return ""

    return "The \"Remote Path\" property must point to a valid Spatial or Spatial-derived node to work."

```

Set the Remote Path to the player avatar. And, of course, you make the `Camera` a child of that node, and rotate and offset it appropriately.

---

**Isometric view**

Advice if you want the isometric view: The rotation you want 45 degrees (or 135, 225, 315) on y, and -35.264 on x. Set projection to Orthogonal. You may have to adjust the Size of the camera which controls how much you see in the Orthogonal projection.

---

**Margins**

This took some figuring out. I'll go over the script part by part explaining what is going on.

```
tool extends Spatial

```

It is `Spatial` because 3D.

The reason why it is a `tool` script is to give those warnings that appear on the scene tree. We do that by implementing `_get_configuration_warning`. Let us get `_get_configuration_warning` out of the way:

```
func _get_configuration_warning() -> String:
    var target = get_node_or_null(remote_path) as Spatial
    if !is_instance_valid(target):
        return "The \"Remote Path\" property must point to a valid Spatial or Spatial-derived node to work."

    return ""

```

---

These are the variables we will export:

```
export var remote_path:NodePath
export var y:int
export var margin:Vector2 = Vector2.ZERO

```

The variable `remote_path` is the `NodePath` to what the camera should follow. The variable `y` is the value for `y` we use in the transform (because we only take `x` and `z`). And the variable `margin` is how far off center on the screen we allow what we are following to go before we begin moving.

---

I have gone back and forth between whether or not we should use `_process` or `_physics_process`. On one hand the player avatar will only update on `_physics_process`. On the other this is about something visual (the Camera). At the end I ended up opting for `_process` because what this node follows might not necessarily be a physics body, and even if it is, it could be using `_process` for interpolation.

Since this is a `tool` script, `_process` begins like this:

```
func _process(_delta: float) -> void:
    if Engine.editor_hint:
        return

```

Similarly we don't want it to run when it isn't in the scene tree:

```
    if !is_inside_tree():
        return

```

Now let us get a reference to the viewport:

```
    var viewport:Viewport = get_viewport()

```

Just in case, let us check it is valid:

```
    if !is_instance_valid(viewport):
        return

```

Now we use it to get *the current* camera:

```
    var camera:Camera = viewport.get_camera()

```

We not only need to check if it is valid, we also need to check if it is the child of this node.

```
    if !is_instance_valid(camera) or camera.get_parent() != self:
        return

```

We also need the the target that the camera should follow:

```
    var target = get_node_or_null(remote_path) as Spatial
    if !is_instance_valid(target):
        return

```

And we are going to need the coordinates of the center of the screen:

```
    var viewport_center := viewport.size * 0.5

```

---

Alright, we get the position we want to follow:

```
    var target_position := target.global_transform.origin

```

We only want `x` and `z`, of course:

```
    var position_3d := Vector3(target_position.x, y, target_position.z)

```

We figure out where on the screen that is:

```
    var position_2d := camera.unproject_position(position_3d)

```

We figure out the difference from the center of the screen:

```
    var off_center := position_2d - viewport_center

```

And we clamp it to the margin:

```
    var off_center_clamped := Vector2(
            clamp(off_center.x, -margin.x, margin.x),
            clamp(off_center.y, -margin.y, margin.y)
        )

```

If clamping did nothing, then we don't need to move:

```
    if off_center == off_center_clamped:
        return

```

Now, a tricky bit:

```
    var target_2d := viewport_center + off_center - off_center_clamped

```

This is the position in 2D that we want to put on the center. Notice that when `off_center` and `off_center_clamped` are equal, then `target_2d` is `viewport_center`. Meaning we want at the center, what is at the center.

However, `off_center` and `off_center_clamped` are different. So `target_2d` will be moved offset from the center according to that difference.

And now another tricky bit:

```
    var ray_origin := camera.project_ray_origin(target_2d)
    var ray_direction := camera.project_ray_normal(target_2d)

```

That's right, we are ray casting. We need to convert that position back to something in 3D.

```
    var depth := (y - ray_origin.y) / ray_direction.y

```

So what's that?

Let us see. We want to track a position on an horizontal plane defined by `y`. So we need to intersect the ray with that plane.

So we have some equation that looks like this:

```
(ray_origin + ray_direction * depth).y = y

```

Let us put some vector there:

```
ray_origin + ray_direction * depth = _target_3d
whatever.y = y

```

Solve for depth:

```
ray_origin + ray_direction * depth = _target_3d
=>
ray_direction * depth = _target_3d - ray_origin
=>
depth = (_target_3d - ray_origin) / ray_direction

```

And we only care about the `y`, so:

```
depth = (whatever.y - ray_origin.y) / ray_direction.y

```

Thus:

```
    var depth := (y - ray_origin.y) / ray_direction.y

```

Alright, we can now figure out that point. Just plug that equation again:

```
    var target_3d := ray_origin + ray_direction * depth

```

Which, by the way, is the same as:

```
    var target_3d := camera.project_position(_target_2d, depth)

```

Except we already did all the work anyway.

Finally, set the transform:

```
global_transform = Transform.IDENTITY.translated(target_3d)

```

---

Usage is as expected. Make this node the parent of the Camera, set its properties. Position the camera.
> 0 votes

---
Tags: 3d, camera, movement, godot
---


# Question
Title: Should ammo limitations be controlled by the game class or the weapon class?
I have a simple shooter game with a `GameLevel` class and a Shooter class. The shooter has a set amount of ammo, and every time the `shoot()` function is called, the ammo variable in the shooter decreases.

My question is about when the shooter runs out of ammo. Should the `shoot()` function be keeping track of ammo and simply stop shooting when ammo is 0, or should the `GameLevel` class call some sort of `canShoot()` function and have complete control over whether the weapon shoots or not?

This also applies to for example movement limitations i.e. if (in a simple 2D game) the shooter hits a wall, should the shooter itself prevent any movement or should the `GameLevel` class check for this first?

# Answer
> 3 votes
Think about it from the real world perspective (this is how we typically do OOP design):

What decides the ammo limit on a gun, the gun's design or the whole world's design? If it is specific to the gun, keep it in the gun class. Make things as specific as possible.

From an external perspective, pulling the trigger doesn't necessarily shoot a gun, it only *tries* to shoot, because whether a round is chambered or not is entirely internal to the gun, and unknown to the outside world (hence people sometimes die by accident, e.g. Brandon Lee in The Crow).

So from the world, or the player, or what have you, you would call `gun.tryShoot()`. Internally to the `Gun` class, this would be something like:

```
class Gun
{

    tryShoot()
    {
        if (this.hasAmmo()) this.shoot();
        else this.goClick();
    }

    shoot()
    {
        this.sendProjectileFrom(parent.transform); //pass position / direction the gun has according to the holder;
        this.ammo--;
        //play a bang sound
    }

    hasAmmo()
    {
        return this.ammo > 0;
    }

    goClick() { /*play a click sound*/ }
}

```

Collision detection, however, is usually handled by a separate subsystem that considers collisions between all (or subsets of) physical objects, collectively, often treating all of these in some generic fashion and notifying when a collision between pairs of these has occurred (each according to their own fashion, for example a barrel may explode while a player may lose life points).

---
Tags: software-engineering, shooter
---


# Question
Title: How to pre-configure a prefab in the editor for multiple similar buttons before instantiating them
Let me explain my problem with my concrete example. I have a button prefab. A button prefab has a lot of configurations: background color, background shape, background image, text, text color, button type, text size, background size, etc.

I have a few places where I use the button prefab. In some places I can just manually put the prefab into the scene in-editor and preconfigure a button. But there are other places where I need to instantiate a batch of buttons with almost the same configuration.

Sure, I could setup each of these buttons in code during the instantiation. But that seems cumbersome. So, what I did is I added a button prefab to scene. Then configured it as I wish. Then hid it in the scene. Then created a script with a reference to a `GameObject` and now instead of a prefab from a file explorer I put the hidden configured button in that reference. So, now during an instantiation I only need to change the enablement of the instantiated button instead of configuring it from code.

I am really eager to know if there is a better way to do what I am doing.

# Answer
> 1 votes
You can do that with prefab variants. A prefab variant is a prefab which inherits most of its properties from another prefab.

1. Create your basic button
2. Turn it into a prefab by dragging it from the scene window into the project window
3. Drag that basic button prefab from the project into the scene to make an instance of it
4. Modify the instance into a specialized kind of button
5. Drag the instance from the scene into the project window.
6. Unity will ask you if you want it to be a new, independent prefab or a prefab variant. Choose Prefab Variant.

Now any changes to the basic button will be inherited by the specialized button, and then to any buttons created from it, unless that particular property was overridden somewhere along the chain.

You can have prefab variant inheritance chains of any length.

I am using this technique a lot when I design UIs in Unity, because it makes it much easier to theme my UI after I build it. For example, experimenting with different fonts is far easier when every single Text object you have in your UI inherits from the same text prefab.

---
Tags: unity, scene, prefabs, configuration
---


# Question
Title: Movement within a circle, but the circle bends around obstacles?
I wish I knew a better way to phrase this, but I want to make an object move from point to point inside a circle. But I also want that "circle" to bend around obstacles, so that no matter what path the object takes inside the circle, the maximum distance traveled remains constant.

To try and simulate what this shape might look like, I wrote a simple program that creates random lines from a center point to the edge of a circle that represents the maximum distance. If the line collides with an obstacle (represented by a smaller circle), it randomly changes direction until it no longer collides. Some of these lines get all the way around the obstacle, but leave a "shadow" behind the obstacle. So far, it looks like the size of the shadow is about equal to the size of the obstacle, but I'm not a good enough mathematician to prove it, or even to know how to describe this problem better.

Here is an image from my program so you can get some idea of what I'm talking about.

This problem might be similar to that of calculating what's visible from a point, but I want the unit to be able to move behind the obstacle, so I think it's a little different.

EDIT: The shape reminds me of a cardioid.

# Answer
> 1 votes
If you can discretize your navigation to a grid or other graph of small discrete hops, then you can use Dijkstra's algorithm to find all locations reachable within a fixed path distance budget of your starting point.

The finer your grid/graph, the more finely this will capture your shape, but also the more computation you'll need to spend traversing it. So you'd need to find the right balance for your game.

If you want a purely geometric solution without the grid/graph approximation, then as you suspected, you can adapt the method used for drawing visibility polygons.

It's easiest to think about with sharp, polygonal obstacles, so we'll start with that. As you sweep your "scanning beam" line around as described in the article above, you remember each time you hit two vertices in a row from different walls — that tells you there's a section occluded from a direct line-of-sight walk.

From this first scan, you'll end up with a set of triangles radiating out from your origin point. Clip them to pie wedges where they exceed your movement radius.

Now we'll come back to the vertices we remembered from the first pass, with those occluded regions behind them. We can run the same algorithm, just pretending our origin point is the nearer of the two disconnected vertices, and our path length budget is our original budget minus the path distance travelled to this vertex. Do the sweep again, over just the arc from the terminator of the previous visibility pass to the wall connecting to this vertex

Along the way, you may discover further occlusions, and continue recursing on them with reduced movement budget until the search bottoms-out at the limits of your path length budget, or when you hit no new vertices you haven't already visited with a shorter path.

When you're done, you'll have a collection of clipped pie wedges describing your reachable area. Note that these can overlap — if you could go either left or right around a small obstacle, and the paths meet on the other side.

For curved obstacles, it's a bit trickier, so discretizing them into polygons may be easiest. But if you want a purely continuous solution, instead of drawing more pie wedges at points where they occlude the direct ray, you'd trace an involute curve, representing a path that hugs along the surface before moving away in a straight line along a different tangent.

---
Tags: mathematics, algorithm, path-finding, geometry
---