# Question
Title: How can I keep a mesh connected and upright?
I'm pretty new to both programming and Unity, and I honestly have no idea how to accomplish what I want to do.

**Scene:** I have a Sphere which I can control with my keyboard. It rolls around on a plane using physics. Simple stuff.

**What I want to do:** Now, I want to be able to attach objects to this sphere which move along with the sphere, but should always stay upright. **If it's possible to do this dynamically, with a bit of "sway" / smoothing to the correcting motion as the ball rolls around, that would be magical. :)**

# Answer
You can do this with a variation on this bobblehead script I wrote. Keep the spring stiffness high and the conservation low to make the object stay more upright and bounce less.

```
using UnityEngine;

public class Bobble : MonoBehaviour {
    // We'll sproing about this transform's origin point.
    public Transform pivot;

    // Tunable parameters for how sharply the bobble spring pulls back,
    // and how long we keep bobbling after a shake.
    public float stiffness = 100f;
    [Range(0, 1)]
    public float conservation = 0.5f;

    // Used to constrain the bobble to a shell around the pivot.
    Vector3 _restOffset;
    float _radius;

    // Track physics state for Verlet integration.
    Vector3 _worldPosNew;
    Vector3 _worldPosOld;
    Vector3 _forward;

    // Used for interpolation between fixed steps.
    float _timeElapsed;

    private void Start() {
        // Cache our initial offset from the pivot as our resting position.
        // Remapped from pivot space to world space to stay upright.
        //_restOffset = pivot.InverseTransformDirection(
                        transform.position - pivot.position);
        _restOffset = transform.position - pivot.position;

        _radius = _restPosition.magnitude;
        _forward = transform.forward;
    }

    private void FixedUpdate() {
        // Compute a desired position our spring wants to push us to.

        // In the version in the tweet, this position would rotate
        // along with the pivot object.
        // Vector3 desired = pivot.TransformPoint(_restOffset);

        // But to stay upright above a rotating pivot, we'll want this
        // to be applied in world space.
        Vector3 desired = pivot.position + _restOffset;

        // The further we are from this position, the more correcting force it applies.
        Vector3 acceleration = stiffness * (desired - _worldPosNew);

        // Step forward a new position using Verlet integration.
        Vector3 newPos = _worldPosNew + conservation * (_worldPosNew - _worldPosOld)
            + Time.deltaTime * Time.deltaTime * acceleration;
        _worldPosOld = _worldPosNew;

        // Constrain the bobble within our radius.
        _worldPosNew = ClampedOffset(newPos) + pivot.position;

        // Clear the accumulated time now that we have a new sample.
        _timeElapsed = 0f;
    }

    private void Update() {
        // Interpolate our position so we get nice smooth movement,
        // without stutters or beats with the FixedUpdate rate.
        _timeElapsed += Time.deltaTime;
        float t = (_timeElapsed / Time.fixedDeltaTime) % 1.0f;
        Vector3 blend = Vector3.Lerp(_worldPosOld, _worldPosNew, t);

        // Correct the interpolated position to one on the shell around our pivot.
        Vector3 offset = ClampedOffset(blend);
        transform.position = offset + pivot.position;

        // Orient so "up" points away from the pivot,
        // and "forward" aligns roughly to our cached forward direction.
        transform.rotation = Quaternion.LookRotation(offset, -_forward)
            * Quaternion.Euler(90f, 0f, 0f);
    }

    Vector3 ClampedOffset(Vector3 position) {
        // Clamp our position onto a spherical shell surrounding the pivot
        // (as though we were swivelling on a rod of fixed length)
        Vector3 offset = position - pivot.position;
        return offset.normalized * _radius;
    }
}

```
> 2 votes

# Answer
*(I started to answer this before the post was closed soon after the question was posed and before I could finish it. DMGregory's answer is more complete and sophisticated, but I'm offering this anyway because I think it should be very easy for a beginner to understand.)*

The first part of your question is pretty simple. For demo purposes, here's our set up:

We have a terrain that the sphere can roll around on. The sphere has a rigidbody and sphere collider.

For the "attachable" object we have a cube with no collider, scaled in one direction so we can see clearly its orientation. Attached to the cub(oid) is a custom script called AttachToSphere.

Here is that script:

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

public class AttachToSphere : MonoBehaviour
{
    public Transform sphere; //the sphere we'll "attach" to
    public Vector3 offset; // distance from the sphere we'll maintain
    float timer = 0; // used to time when we start and stop the attachment

    void Update()
    {
        timer += Time.deltaTime;

        if (timer > 2 && timer < 10)
        {
            transform.position = sphere.position + offset;
        }
    }
}

```

When the scene runs, the sphere drops and rolls around the terrain. The script's timer in the Update loop waits 2 seconds before coupling the cuboid to the sphere. the cuboid remains upright because it is simply tracing the position of the sphere, without being affected its rotation. After ten seconds, the cuboid detaches (stops follwing the sphere's position.) Very simplistic, but maybe useful as something to play with to begin to understand hown this stuff works. See DMGregory's answer for a much more in depth solution, that actually has the picked up object bobble slightly as the parent object moves around.
> 1 votes

---
Tags: unity, physics
---


# Question
Title: How can I create a custom size plane without scaling in Unity by code?
I'm planning create a plane with the size like 16x1x16, however, I wanna the scale of it is always 1x1x1. I found something useful information Unity change size of cube mesh. It aims to a cube mesh, any idea about plane mesh?

Or can I use a cube mesh as a plane mesh?

# Answer
I googled for a while and change-size-of-mesh-at-runtime is a solution. However, a plane's mesh is still there after following the code. It seems a plane's mesh copies another piece and scales based on that code and the original one keeps its size and can't be scaled. So there are two pieces of meshes in a plane, a bit weird.

As a result, I used the ProBuilder plugin to solve this problem. (This is a free add-on available from Unity's Package Manager.)

Using the method `ShapeGenerator.GeneratePlane(PivotLocation pivotType, float width, float height, int widthCuts, int heightCuts, Axis axis)` the plugin provides, you can achieve the goal.
> 0 votes

---
Tags: unity, mesh
---


title: Reach a moving point smoothly

text:
# Question
Title: Reach a moving point smoothly
First, for my specific problem, we can assume we're working in a 1D space.

I have a point B moving at a specific velocity V. I want to smoothly move the body A so it reaches the point B and moves at the same speed, without oscillating too much. A could be behind or before B.

A is a physic body, on which is applied 2 forces, the thrust and the drag, so I don't directly control it's speed.

I've come to some kind a solution but it's not clean at all and involves a lot of thresholds, so I'm looking for something more clever.

I've already used PIDs to handle steering, and I suspect they may be useful there but for some reason my brain can't find how to properly do it, which annoys me a lot because it looks like a trivial problem.

Thanks.

# Answer
I said in the OP I was struggling to find the way to use a PID controller in this case, but I've figured how to do it. Here are the few steps:

1. Calculate the thrust required to go at the speed of B
2. Use the distance to B as an input error for the PID
3. Use the values returned by the PID as an offset applied to the thrust
4. Tune the PID (the funniest part of course)

After some tuning, it works like a charm.
> 0 votes

---
Tags: physics, ai
---


# Question
Title: How to dim the device backlight using libGDX?
I have an idea for a very minimalistic game. To fit in with this theme. I want no explicit messages or tutorials etc. I want to experiment with ways to very gently, implicitly prompt the player to touch the screen.

My idea is to turn off the phone backlight, to mimic what happens when your phone screen is about to turn off due to inactivity. Hopefully, this will make the player think the screen is about to turn off and make them tap the screen - so mission accomplished, I will have subtly prompted the player to touch the screen.

Now, obviously I don't want to turn the screen off, I want to dim the backlight, or maybe trick the phone into thinking it has been inactive for the right amount of time. I know I can just make the displayed image on the screen darker, but that would not accurately mimic the backlight becoming dimmer.

# Answer
You can do this by setting `LayoutParams` on your Android `Window` where you specifiy `screenBrightness`.

If you define some interface in your **core** like:

```
public interface WindowController {
    void setBrightness(float factor);
}

```

And take a reference to that in the constructor of your game-class:

```
public class MyGdxGame extends ApplicationAdapter {
    WindowController windowController;
    SpriteBatch batch;
    Texture img;

    public MyGdxGame(WindowController windowController) {
        this.windowController = windowController;
    }

    @Override
    public void create () {
        batch = new SpriteBatch();
        img = new Texture("badlogic.jpg");
    }

    @Override
    public void render () {
        if (Gdx.input.isTouched() && windowController != null)
            windowController.setBrightness(0.2f);

        ScreenUtils.clear(1, 0, 0, 1);
        batch.begin();
        batch.draw(img, 0, 0);
        batch.end();
    }
}

```

Then, in your `AndroidLauncher` in **android** you implement that interface and call `setAttributes` with updated `LayoutParams`:

```
public class AndroidLauncher extends AndroidApplication implements WindowController {
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
        initialize(new MyGdxGame(this), config);
    }

    @Override
    public void setBrightness(final float factor) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
                layoutParams.screenBrightness = factor;
                getWindow().setAttributes(layoutParams);
            }
        });
    }
}

```
> 1 votes

---
Tags: libgdx, android, screen
---


# Question
Title: Is it necessary to use HTTPS for mobile game communication with server?
Based on information from my friends working at game studios, it seems most commercial mobile games are using HTTP instead of HTTPS for communication between the phone and the server, and I am wondering why that is the case.

Based on my understanding it would be much harder for hackers to send fabricated message to the server and cheat if HTTPS is used. Is there a big drawback for HTTPS or is it just because the games my friends worked with are small (and larger games are actually using HTTPS)?

# Answer
> 3 votes
> Based on my understanding it would be much harder for hackers to send fabricated message to the server and cheat if HTTPS is used.

That is not correct.

HTTPS uses transport layer encryption: it protects the message while it's in transport, so the third parties relaying it can't peek at its contents or modify it.

HTTPS does not do anything to limit what the sender can send. If a hacker wanted to send a fabricated message, they could do so just as easily. HTTPS would just ensure that their ISP or routers elsewhere in the net couldn't inspect or modify that fabricated message.

So, it's not the right tool if your threat model is a player using a hacked/forged client.

The main threat model HTTPS addresses is spying. Say your user wants to send you their credit card information to make an in-app purchase. That's valuable information that someone would try to sniff off the wire if you let them, so it's important to protect that.

Similarly for personal information like their login, which a dishonest third party could use to hijack their account (or account**s** if the user has recycled the same password on other services). So user authentication is another case for HTTPS.

You probably also want to encrypt in-game chat communication. Otherwise your game could be used by an oppressive government to spy on what players are saying in ostensibly-private conversations.

But "I moved by (+2.3, -0.2, +0.5)" "I shot in direction (0.8, 0.6, 0.0)" you might consider to be information that's uninteresting to bad actors under your threat model. There's an argument that it's still a private conversation between the player and your game and no one else's business, and if you already use HTTPS elsewhere you might as well encrypt this too on principle or for consistency.

Developers may disagree about that one, and performance may be the deciding factor:

> Is there a big drawback for HTTPS

Initiating the encrypted channel, encrypting messages to send, and decrypting them when received, all takes some work, which can contribute to CPU load and latency. This has gotten better with newer chips and the cost is quite reasonable for many uses, but it's not free. Profiling is the best way to determine whether the cost here is significant.

There is some system administration work involved in setting up a server to handle HTTPS communication correctly, though this is becoming standard in the default configuration for many server technologies and hosting platforms.

HTTPS requires an SSL certificate to authenticate your server. This can require purchasing one from a certificate authority and keeping it up to date - though Philipp points out in the comments that services like Let's Encrypt now offer such certificates for free, and that making your own self-signed certificate may be sufficient for this use case. Most game companies will need an SSL certificate anyway for other purposes, so although this is a complication, it's not really a determining factor in whether to use HTTPS.

---
Tags: client-server, http
---


# Question
Title: Unity make an Expandable Scroll List (adding elements)
I am trying to make a scrollable list with premade elements that you can add using a button.
The problem is that the list's `Content` element needs to be exapanded as the list gets larger, and it's not made automatically.

If I expand the size of the list, it "works", more or less, because the list keeps expanded to a limited size, even if the list have only one element (for example), the list is scrollable until the maximum. And I don't want that result. I want to have the list as less expanded as possible, so it is only expanded until all elements are visible.

What do I need to do?

# Answer
> 1 votes
See my answer here regarding adding elements to a Scrollview and having the content area expand automatically.

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


# Question
Title: Way to mechanically justify not allowing players to just fly from location to location when playing as a winged insect
## **The System**

The game itself is an action rpg where the player can play as a wide variety of insects, and each insect is mechanically different and allows you to take a different role in combat, exploration, or just surviving.

## **The Issue**

A fair amount of insects can fly, most with limited range and the act itself is rather taxing on stamina, notably so in things like beetles or mantis.

Some insects like butterflies(which function as a bit of a mobile, evasive healer) and dragonflies(which work like airborne burst damage characters) have extremely good flight abilities and could potentially use these to cheese combat or break the exploration system by flying up very high above the grass. This could have a serious effect on multiplayer and also have a somewhat problematic effect in single player activities. I would prefer not to just remove air-focused insects from the game entirely, because that would severely hamper player freedom as well as remove an entire combat role.

I need a way to keep players from doing things like this without adding a jarring "return to battlefield" message like the halo franchise. I would prefer a method that is explainable in-universe and doesn't take the player completely out of gameplay after the limitation is discovered.

# Answer
> 11 votes
**Birds**

Real insects that fly too high / too far from the grass expose themselves to predators. You can make predation by birds be a risk during extended flight, without making it a hard wall - a gamble where players can decide just how far to push their luck, like Icarus courting the Sun...

For example, you could have invisible volumes in your map, or particular durations/distances of flight, that you associate with chosen risk levels. As the player approaches the threshold, they start to hear bird chirping as a warning.

Every second they spend past the threshold, you roll a die to see if a bird should swoop in and snatch them out of the air. The probability can start low and ramp up the further the player pushes their luck, with the chirping / wing fluttering sound cues building to convey urgency. You could also layer in moving shadows from swooping birds to increase the sense of threat.

When the player is unlucky, play a short animation of a bird swooping in from out of frame and devouring them, which you can handle mechanically as though killed by an enemy character.

Or, if that's too harsh, you can have a chance that the bird just grazes the insect, putting them into a tumble where they rapidly lose altitude or crash. Or lose a wing, limiting their aerial mobility until their next respawn / restoration by an ally.

# Answer
> 2 votes
Make it windy when you get to a certain height. You could either make it so they tumble and then are blown back down, thus making a "return to battlefield" without it ruining the immersion, or just have it make the flying uncontrollable and annoying so the player goes down of his own accord.

You could also possibly use rain for parts of the game. Make the rain thicker when you get high, and the drops can hit their wings and cause them to fall.

---
Tags: game-design, game-mechanics, rpg
---


# Question
Title: How to execute code more frequently than once per tick in Minecraft Forge/MCP?
I'm working on a mod for Minecraft in Java. How can I make something happen every half tick? If I run my code in the `tick` function, my code is called **20** times a second. I want my code to be called 40 times a second, or even 60 or 80. How would I do this?

Any answer, whether in Forge, MCP, or even plain Java would help.

**EDIT:** I'm still keeping this question up, but the rest of the game only ticks at 20. Doing 1 task at 60 wont make a difference if everything else ticks at 20.

# Answer
> 1 votes
It's really easy to call your function twice each tick, but that's calling it twice every 20th of a second, not once every 60th of a second which is what you seem to want.

Without wading into multithreading and worrying about API access and thread-safe interactions in your code, you're not going to be able to get this behavior without increasing the tick rate of the engine.

---
Tags: java, minecraft-modding
---


# Question
Title: Rotating only 2 axes of rotation quaternion to "point" in a direction
Note: I am using the Unity DOTS ECS framework, which contains less maths functions, but I can probably implement the same functions from standard unity if the code is public. This question is not specific to unity though, I think.

I'm trying to have a player be able to run around the inside of a sphere such that their local up direction is always pointing at the centre of the sphere. So, when they run "forward" they naturally run in an orbit around the sphere surface.

I already have an artificial gravity system implemented, that applies a force pushing the player towards the sphere walls.

I calculate the new up direction, and then calculate the new forward direction from that. Feeding these into the built-in quaternion.LookRotation(newForward, newUp) function does orient my player towards the centre, but this also updates the local y-axis rotation of the player, meaning I can't turn the player, and it spins around when you cross each hemisphere.

```
float3 centerDir = math.normalize(sphereCenter.Value - translation.Value);

quaternion newRotation = rotation.Value;

float3 newUp = centerDir;
float3 newForward = mathx.Forward(newUp);

newRotation = quaternion.LookRotation(newForward, newUp);

rotation.Value = newRotation;

```

I then tried to negate the Y axis rotation by trying to find the difference in y axis rotation, and multiplying the rotation by another quaternion rotated on Y only by the negative of this angle. But I'm pretty sure I have the wrong vectors in my calculation to find this angle.

This had some success, but the player starts 90 degrees rotated and did strange things as I moved near to the axes. Where forward would bend towards the axis and start spinning.

```
float3 centerDir = math.normalize(sphereCenter.Value - translation.Value);

quaternion newRotation = rotation.Value;

float3 newUp = centerDir;
float3 newForward = mathx.Forward(newUp);

newRotation = quaternion.LookRotation(newForward, newUp);

float angleDiff = mathx.Angle(ltw.Forward, newForward);
quaternion negateYRotation = quaternion.RotateY(-angleDiff);

rotation.Value = math.mul(newRotation, negateYRotation);

```

I've been banging my head against a wall for days with this. I even tried converting all of the quaternions into Euler angles and setting the y angle to the original y angle, but this also affects the other angles so the player is no longer oriented correctly. (I assume this might be to do with the z axis being applied after the y axis).

Any help with this would be much appreciated.

# Answer
> 2 votes
Following DMGregory's excellent answer and posts linked, I now understand the issue. I have implemented his function provided in one of those answers, and it works beautifully.

This is my solution:

I have added a new static function to my extension class, for easy access.

```
public static class mathx
{
    public static quaternion LookRotationExactUp(float3 approximateForward, float3 exactUp)
    {
        quaternion rotateZToUp = quaternion.LookRotation(exactUp, -approximateForward);
        quaternion rotateYToZ = quaternion.RotateX(math.radians(90));

        return math.mul(rotateZToUp, rotateYToZ);
    }
}

```

And the working implementation:

<pre><code>[UpdateAfter(typeof(TransformSystemGroup))]
public class RotateUpToSphereCenterSystem : SystemBase
{
    protected override void OnUpdate()
    {
        float3 sphereCenter = new float3(0, 0, 0);
        float deltaTime = Time.DeltaTime;
        float rotationSpeed = 5;

        Entities
            .ForEach((ref Rotation rotation, ref MovementData movement, in LocalToWorld ltw) =>
            {
                // Only rotate if not at exact center of sphere
                if (!ltw.Position.Equals(sphereCenter))
                {
                    float3 centerDir = math.normalize(sphereCenter - ltw.Position);

                    float3 newUp = centerDir;

                    //Guarantee exact up direction and maintain forward as close as possible
                    movement.targetRotation = mathx.LookRotationExactUp(ltw.Forward, newUp);

                    //Smoothly rotate to the targetRotation
                    rotation.Value = math.slerp(rotation.Value, movement.targetRotation, deltaTime * rotationSpeed);
                }
            }).ScheduleParallel();
    }
}
```
</code></pre>

# Answer
> 1 votes
I get a lot of mileage out of this trick (see several past answers):

```
// Find what direction points opposite our current facing direction (local z-).
float3 backward = math.mul(rotation.Value, new float3(0, 0, -1));
// Find the new up vector we want to rotate our local y+ axis to match.
float3 newUp = math.normalize(sphereCenter.Value - translation.Value);

// Compute a rotation that points our local z+ vector exactly at newUp,
// and our local y+ vector as close as possible to backward.
quaternion zToUp = quaternion.LookRotation(newUp, backward);

// Pitch forward 90 degrees, so now y+ points toward newUp,
// and z+ points perpendicular to this, as close as possible to our old forward.
quaternion yToZ =  quaternion.Euler(math.PI/2, 0, 0));
quaternion newRotation = math.mul(zToUp, yToZ);

```

---
Tags: unity, rotation, quaternion, angles, unity-dots
---


# Question
Title: How to re-render the scene only when something changes in Unity?
Does Unity continuously refresh the screen or constantly render 3D objects on screen with each refresh?

For example, let's say hypothetically you had a screen where you were just text messaging through the Unity app with someone (mimicking basic SMS but through the Unity app) and at the top of the screen there was a 3D rendered header graphic like a logo or 3D graphic menu.

In principle, you would only need to refresh/re-render the screen when a new message is exchanged, the screen is scrolled, or someone clicks a menu option to trigger a menu function or animation. If it continuously re-renders the entire screen and top 3D graphic every frame endlessly at say 30 fps, this would be incredibly wasteful.

Would there be any way to limit re-renders to only happen on certain events and thus make this practical?

# Answer
> 2 votes
The comment that you found is accurate. Unity was developed as a game engine, designed to run games that are animating on-screen elements continuously. In that context, adding logic to detect when something has changed and re-render only on demand would actually *increase* cost, because you spend extra CPU time doing this validation, when 90%+ of the time the answer is "yes, re-rendering is needed".

Unity is quite flexible and does give you control to render when you want, but since minimizing re-rendering is not a core engine feature, it would be your responsibility to track when you need to render and switch rendering on & off.

Here's a quick proof of concept script that demonstrates this:

```
public class RenderControl : MonoBehaviour
{
    new public Camera camera;

    float _renderFor = 0.1f;
    int _continuousRenderRequests = 0;

    public void RenderFor(float duration = float.Epsilon) {
        _renderFor = Mathf.Max(_renderFor, duration);
    }

    public void StartRenderingContinuously() {
        _continuousRenderRequests++;
    }

    public void StopRenderingContinuously() {
        _continuousRenderRequests--;
    }

    void LateUpdate()
    {
        camera.enabled = (_renderFor > 0) || (_continuousRenderRequests > 0);
        _renderFor = Mathf.Max(0, _renderFor - Time.deltaTime);
    }
}

```

This disables the camera from rendering after it's had a chance to display the initial state of the scene. After this, rendering can be enabled for a set duration or until stopped by calling one of the public methods on this script.

While the camera is disabled, no new drawing commands will be issued, and whatever you last drew to the screen stays there. But game logic (like the update loop that handles user input and checks whether it's time to re-enable the camera) still ticks every frame.

Note that in the Unity Editor view, you'll see a warning overlaid on the game window "Display 1: No cameras are rendering" to alert you to this, because it's usually a sign of an error if it happens in a game. But this warning is not present in the built executable.

If you use the UI system, you'll want to set the canvas mode to "Screen Space - Camera" so that the rendering of the UI is tied to the enabled state of the camera. With "Screen Space - Overlay", the UI will still render continuously over the frozen 3D scene.

You could take this further by computing the screen rectangle bounding the changed area, then change the camera's transform and viewport parameters to limit rendering to just that rectangle.

However, you'll likely find this more laborious than it's worth. You'll save the work of rendering your chat window, which is likely quite lightweight, but still be paying the costs of updating all Unity's other game systems - as well as the download cost of a full-featured game engine. So the efficiency will not match frameworks that are purpose-built for making this kind of mobile app.

Your use case is probably better served by using a dedicated framework designed for building mobile-conscious apps, and then running your minigames either as WebGL apps in a web view, or chaining control to a separate executable for those parts.

---
Tags: unity, rendering, mobile, efficiency
---


# Question
Title: Asset Bundle download from server: how does one prevent scripted attack?
I am relatively new to how asset bundle works in Unity. Based on my learning, it seems one uses `UnityWebRequest.GetAssetBundle` to download an asset from a specified URL.

However, it does not provide any means to authorize the user downloading the asset and it seems once the URL is known by the hacker (which is pretty easy) they can repeatedly send infinite amount of asset download requests using scripts and/or self-made programs. Since the data size is actually quite large for assets this seems to be a very effective way to attack a game server.

I am pretty sure a mature engine like Unity would not have this vulnerability, and most games are not vulnerable to this kind of "trivial attack".

In addition, if all assets are publicly accessible, this seems really insecure too.

Can anyone explain to me how is this kind of situation prevented by Unity, and/or what is the correct way to use Asset Bundle downloading mechanism?

# Answer
> 2 votes
The reason that Unity does not provide any specific mechanism to limit download requests is that the Unity Engine powers your *client-side* application. It does not run your asset-serving server, and **any protections against denial of service attacks *must* be implemented server-side**.

Imagine if the Unity Engine *did* provide some way to for the client sign an asset bundle request. As the information security mantra goes, **the client is in the hands of the enemy**. Anyone with a copy of your game (either a paying customer, or someone who has obtained a copy illegally) could decompile it, extract the request-signing code, and use it to build a fake client that spams your server with flawlessly forged requests. Trying to defend against this in the client is a losing game.

(This is also the reason why you should consider any game assets you package or download into the client to be public information - you can't keep a secret in something you want every player of your game to be able to use)

So, if malicious downloads are a concern for your use case, you'll need to use server-side solutions. Content distribution networks exist to alleviate the load of file serving from servers, and detect/block denial of service attacks, or you can implement your own customized protections.

One possibility would be for a client to first send a conventional GET request asking for permission to download the asset. After validating the request (say, rate-limiting requests by IP, or checking the user's login credentials if you want to restrict the downloads to specific user accounts in your own database), the server can reply with a one-off URI unique to that request. Then your server can respond to requests to that special URI by serving the asset bundle, up to a certain number of download attempts or short deadline, whichever is reached first.

This gives you the flexibility to implement whatever validation approach you deem appropriate for your threat model, entirely on the server side where it's out of the reach of would-be attackers to forge or manipulate.

---
Tags: unity, server, security, assetbundle
---


# Question
Title: Understanding Unity-UI Layout Element - Mininum and Preferred Size
I have been working with Unity for some time, and I am trying to get a better understand of the UI system.

I am a mobile developer and am redesigning the UI but I am unable to achieve what I want.

My game is in portrait mode and I have a panel. I want the panel to have a maximum width of 1080 pixels. In cases where the panel doesn't fit on the screen because the aspect ratio is less (like the new iPhone X), I want it to shrink it a bit with a minimum width of 700 pixels. In the case that the screen is larger than 1080p (like the iPad Pro) I want the panel to have the maximum size.

Here are visuals of what I want to achieve:

Nexus 6P ( 1080x1920)

iPhone X(1125x2436)

iPad pro (2048x2732)

I have been playing with `Layout Element` and `Content Size Fitter` components without success.

If I set the min width size to 700 pixels and preferred size to 1080 pixels nothing happens (even after setting flexible width.)

If I set the `Content Size Fitter` to the preferred size it just always reverts to the preferred size. The same thing happens with min.

How do these components work, and how I can achieve the desired effect?

Canvas configuration:

# Answer
> 1 votes
I don't believe this can be accomplished with the `ContentSizeFitter` and `LayoutElement` components. Instead, you will need a custom script that sniffs the device's screen size and computes the aspect ratio and adjusts the `RectTransform` accordingly.

Fortunately this is quite simple. Here is a demo to show how this can be done. For this example we have a `Canvas` gameobject with a `Panel` child. This panel will be the target of our scaling.

The canvas' `CanvasScaler` component can be set to any of the three *UIScaleModes* -- all work. The panel's `RectTransform` anchor preset should be set to *stretch/stretch* and the top, bottom, left and right values should all be set to zero to have the panel fill the canvas by default.

For demo purposes, the script is attached to an empty gameobject. Also for demo purposes, the scaling routine runs in the `Update` loop -- something you would obviously never want to do in a real application. Here's the script:

```
using UnityEngine;

public class AspectRatioDemo : MonoBehaviour
{
    public RectTransform panel;
    public float maxAspectRatio = 1080f / 1920f; // example: Nexus 6P

    // routine shown in Update for demo purposes, obviously you would only do this once...
    void Update()
    {
        float currentAspectRatio = (float)Screen.width / (float)Screen.height;
        if(currentAspectRatio > maxAspectRatio)
        {
            float padding = (currentAspectRatio - maxAspectRatio)/2f;
            if(padding > .5f)
            {
                Debug.LogError("unsupported aspect ratio"); //addition logic required to support landscape mode
                return;
            }
            panel.anchorMax = new Vector2(1.0f - padding, 1.0f);
            panel.anchorMin = new Vector2(padding, 0);
        }
        else // this is only necessary if panel was previously resized
        {
            panel.anchorMax = Vector2.one;
            panel.anchorMin = Vector2.zero;
        }
    }
}

```

`maxAspectRatio` represents the widest aspect you'll allow before padding the panel's margins. By default I have it set to 1080/1920 (.5625). The routine checks whether the actual aspect ratio exceeds this by dividing `Screen.width` by `Screen.Height`. If not, it does nothing. If it does, it computes a padding value. (Note the if the computed padding value is greater than .5 we're talking about a device in landcape mode which is unexpected and unsupported here.) Finally the code adjusts the anchors to create the padding.

# Answer
> 0 votes
I think you can solve this problem using Anchors. Set your anchor of parent panel to stretch.

below I attached a screenshot to make you understand what I am saying,

> You can found this tool in Unity UI's Rect Transform component where you have to click on the icon and it pops up the attached screenshot.

Now press Alt + Shift (Alt to set position and Shift to set pivot of the object). You will achieve the result you wanted by pressing both alt and shift together and select right one on the downside (last one).

you can learn or read more about anchor point in this unity doc :

> Setting UI for multiple screen resolution

---
Tags: unity, ui-design, unity-ui, aspect-ratio
---


# Question
Title: Is there a way to figure out in which quad I am in fragment shader?
In my openGL project I draw a lot of quads (composed from 2 triangles) - for sake of example let's say quad 0,1,2 and 3. I process them in single pass. I do transform them with projection view matrix in Vertex shader.

Is there then any way in Fragment shader to tell in which quad (0,1,2,3) I am currently drawing the pixel?

# Answer
> 1 votes
I have not done this myself, but something in this vein should work:

Define a varying variable to send the vertex ID from the vertex shader to the fragment shader. Use the `flat` attribute so that it's not interpolated between vertices — instead the value from the provoking vertex will be used for all fragments in the triangle.

```
flat out int vId;
shader void main() {
    vId = gl_VertexID;
}

```

Then in your fragment shader you can read this ID and divide it down (rounding down) to identify the quad:

```
flat in int vId;
void main() {
    int quadId = vId/4;
    // TODO: do something with quadId
}

```

Assuming your first quad is made up of vertices 0-3 in your buffer, this will round down to 0 for all fragments in that quad. If your next quad is made up of vertices 4-7, this will round down to 1 for those fragments, and so on.

# Answer
> 1 votes
You could have a vertex attribute per quad, and send that as a varying to your fragment shader.

---
Tags: opengl, matrix, fragment-shader, vertex-shader
---


# Question
Title: On a UI element(Input field) and overlay canvas how do I find the very bottom middle pos of the UI using it's height from it's rect transform?
I'm trying to place one in our field right below another, all ui belonging to an overlay canvas. I tried doing a few different ways subtracting height from different position types including rect types but the result of position I get seems to be inconsistent and a bit off. Thanks in advance.

Note the anchor pivot point for my body fields on Y is 1, because I need it that way for the field to expand downwards as the field text grows in length.

So as you can see as the lines get longer and the height increases, the placement of the empty body fields is no longer accurate and gets thrown off. What's going on?

So here's the code I'm running to create my new Input fields, the current one turns white and "cements" itself as a new one empty non white one gets instantiated right underneath it, when you double click anywhere on the screen. Hence the times click on the code. Anyways the commented out code are all the different ways I've tried doing this but with no luck. The moment by input field height starts changing when there is more than one line, the new instantiated field doesn't get place properly, right underneath it like it does with just one line as you'll see in the images, below the code.

```
  public void CementSegment_And_AddNewEmpty()
{
    TimesClicked++;
    StartTimesClickedTimer = true;

    if (TimesClicked >= 2)
    {
        //Turns current segment to white (cements it)

        NoteBodyObjects[NoteBodyObjects.Count - 1].GetComponent<Image>().color = new Vector4(1, 1, 1, 1);

        //Adds new unsegmented/non white body to bottom of the (newly cemented white segment from code line above)

        //float height = NoteBodyObjects[NoteBodyObjects.Count - 1].GetComponent<RectTransform>().rect.height;
        float height = NoteBodyObjects[NoteBodyObjects.Count - 1].GetComponent<RectTransform>().sizeDelta.y;

        //Vector3 pos = NoteBodyObjects[NoteBodyObjects.Count - 1].transform.position;
        //Vector3 pos = NoteBodyObjects[NoteBodyObjects.Count - 1].GetComponent<RectTransform>().anchoredPosition;
        //Vector3 pos = NoteBodyObjects[NoteBodyObjects.Count - 1].GetComponent<RectTransform>().localPosition;
        Vector3 pos = NoteBodyObjects[NoteBodyObjects.Count - 1].GetComponent<RectTransform>().position;

        Vector3 BodyFieldLocation = pos - new Vector3(0, (height * 0.5f), 0);

        GameObject NewBodyField = Instantiate(DefaultBodyField, ContentParent);

        //NewBodyField.transform.position = BodyFieldLocation;
        //NewBodyField.GetComponent<RectTransform>().anchoredPosition = BodyFieldLocation;
        //NewBodyField.GetComponent<RectTransform>().localPosition = BodyFieldLocation;
        NewBodyField.GetComponent<RectTransform>().position = BodyFieldLocation;

        NoteBodyObjects.Add(NewBodyField);
    }
}

```

# Answer
I figured out what it was. I'm an idiot. I happened to scale my prefab input field before making it a prefab, using the transform scale tool instead of using the rect tool like I suppose you're suppose to do. Meaning the inconsistencies were due to scale values that went unaccounted for from the transform scaling. I don't deal too much with UI but lesson learned. So if you want accurate manipulation of rect positions, height etc, please make sure you do all your UI size position changes using the rect transform in the inspector or the appropriate rect tools. Hope this helps someone!
> 0 votes

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


# Question
Title: How to create editable SDL2 text input boxes?
Hi all, I'm working on an SDL2 project and I require multiple editable square textboxes as shown in the image above. Is there any way I can do this?

# Answer
There are two parts to my answer: **rendering a dynamic text box onto the screen**, and **changing the text box based on user input**, which hopefully covers both parts of your question. I'm writing this based on the assumption that you're using standard SDL2 libraries and documentation, which (I hope?) are C/C++ blind.

## Dynamic text box: What you'll need

In SDL2, the usual way to draw a dynamic text box is that you will need the following things:

You will also need to include the **SDL\_ttf** library, which is a font rendering library for text that is used within the SDL library. It might have been included in your installation - if not, here is a link to get it.

## Dynamic text box: The implementation

First you can use the built-in SDL\_ttf function TTF\_RenderText\_BlendedWrapped to render your given text string (which must first be converted into a char array) into an SDL\_Surface. The maxLength parameter is the maximum allowable length of the text string before it wraps around into a second line, which is useful for dynamic text wrapping in your boxes to save time and headaches.

```
Surface = TTF_RenderText_Blended_Wrapped(font, CharArray, color, maxLength);

```

Next you can use SDL\_CreateTextureFromSurface to convert that surface into a texture, using your SDL\_Renderer as the first parameter:

```
Texture = SDL_CreateTextureFromSurface(renderer, Surface);

```

And finally, you can draw that text box onto the screen using any other function you would use to draw a texture on screen.

The full text box constructor function that I use in my own SDL2 game, for your convenience:

```
/*
* Constructor with text, font, font color, and renderer.
*
* @param t: The text in the text box.
* @param font: The font we are using.
* @param color: The color of the text.
* @param renderer: The renderer.
* @param maxLength: The maximum width of the text box before it wraps around.
*/
TextBox(string t, TTF_Font* font, SDL_Color color, SDL_Renderer* renderer, int maxLength)
{
    char CharArray[2000]; // Create a char array
    strcpy_s(CharArray, t.c_str()); // Convert the string into a char array for the surface function.

    Surface = TTF_RenderText_Blended_Wrapped(font, CharArray, color, maxLength); // Make into a surface.
    Texture = SDL_CreateTextureFromSurface(renderer, Surface); // Turn the surface into a texture.
    TTF_SizeText(font, CharArray, &w, &h); // Size the texture so it renders the text correctly.
}

```

## Changing the text box for user input

To do this, you'll need to re-render the text box each time its text changes, since the text is rendered into an SDL\_Surface as part of the rendering function. You'll need to overwrite the text box with a new one and re-render it each time the text is updated:

```
Box = TextBox(NewText, Font, TextColor, renderer, maxLength); // Re-render with the new text.

```
> 1 votes

---
Tags: sdl2, c
---


# Question
Title: Making vehicle using WheelColliders faster
I have a driving game and use wheel colliders to control cars, but whatever I change with the WheelCollider components it doesn't get faster and is way too slow.

The code of the controller:

```
[System.Serializable]
public class AxleInfo
{
public WheelCollider leftWheel;
public WheelCollider rightWheel;
public bool motor;
public bool steering;
}

public class SimpleCarController : MonoBehaviour
{
public List<AxleInfo> axleInfos;
public float maxMotorTorque;
public float maxSteeringAngle;

// finds the corresponding visual wheel
// correctly applies the transform
public void ApplyLocalPositionToVisuals(WheelCollider collider)
{

    Transform visualWheel = collider.gameObject.transform;

    Vector3 position;
    Quaternion rotation;
    collider.GetWorldPose(out position, out rotation);

    visualWheel.transform.position = position;
    visualWheel.transform.rotation = rotation;
}

public void FixedUpdate()
{
    float motor = maxMotorTorque * Input.GetAxis("Vertical");
    float steering = maxSteeringAngle * Input.GetAxis("Horizontal");

    foreach (AxleInfo axleInfo in axleInfos)
    {
        if (axleInfo.steering)
        {
            axleInfo.leftWheel.steerAngle = steering;
            axleInfo.rightWheel.steerAngle = steering;
        }

        if (axleInfo.motor)
        {
            axleInfo.leftWheel.motorTorque = motor;
            axleInfo.rightWheel.motorTorque = motor;
        }

        ApplyLocalPositionToVisuals(axleInfo.leftWheel);
        ApplyLocalPositionToVisuals(axleInfo.rightWheel);
    }
}
}

```

and here are the options of the WheelCollider (every wheel has the same options)...

From here I got the code by the way https://docs.unity3d.com/Manual/WheelColliderTutorial.html

# Answer
**Note** *my original response suggested simply increasing maxMotorTorque, but it appears this has no apparent effect by itself.*

Try adding force to the parent (car\_body) rigidbody along with the motor values of the wheel colliders. Something like this:

```
float motor = maxMotorTorque * Input.GetAxis("Vertical");
rb.AddForce(transform.forward * motor);
float steering = maxSteeringAngle * Input.GetAxis("Horizontal");

```

You may need to lower the cg to get the car to handle the way you want.

Here's the whole script, including tweaking the Center of Mass (with magic numbers here):

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

[System.Serializable]
public class AxleInfo
{
    public WheelCollider leftWheel;
    public WheelCollider rightWheel;
    public bool motor;
    public bool steering;
}

public class CarController : MonoBehaviour
{
    public Text speedometer;

    public List<AxleInfo> axleInfos;
    public float maxMotorTorque;
    public float maxSteeringAngle;

    // finds the corresponding visual wheel
    // correctly applies the transform
    public void ApplyLocalPositionToVisuals(WheelCollider collider)
    {
        if (collider.transform.childCount == 0)
        {
            return;
        }

        Transform visualWheel = collider.transform.GetChild(0);

        Vector3 position;
        Quaternion rotation;
        collider.GetWorldPose(out position, out rotation);

        visualWheel.transform.position = position;
        visualWheel.transform.rotation = rotation;
    }

    Rigidbody rb;
    private void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.centerOfMass = new Vector3(0, -4, 0);
    }

    public void FixedUpdate()
    {
        float motor = maxMotorTorque * Input.GetAxis("Vertical");
        speedometer.text = string.Format("motor {0:N0}\n{1:N0} mph", motor, rb.velocity.magnitude);
        rb.AddForce(transform.forward * motor);
        float steering = maxSteeringAngle * Input.GetAxis("Horizontal");

        foreach (AxleInfo axleInfo in axleInfos)
        {
            if (axleInfo.steering)
            {
                axleInfo.leftWheel.steerAngle = steering;
                axleInfo.rightWheel.steerAngle = steering;
            }
            if (axleInfo.motor)
            {
                axleInfo.leftWheel.motorTorque = motor;
                axleInfo.rightWheel.motorTorque = motor;
            }
            ApplyLocalPositionToVisuals(axleInfo.leftWheel);
            ApplyLocalPositionToVisuals(axleInfo.rightWheel);
        }
    }
}

```
> 1 votes

---
Tags: unity, c#, physics, car
---


# Question
Title: Change color in specific sections in sprite
I have a game, where I would like to generate multiple enemies, just switching randomly their skin and clothes, colors. One way to do it, would be to break every position (each position composed by many sprites), like walk, idle, kick, in "layers" in Photoshop, and then import and organize the objects in a scene, connecting them by object parenting. I.e I have the player, then I add pants as child object and then I can control pants color and skin color separately. Theoretically it should work, however it would be a huge amount of work, if you think that I have almost 20 positions, each position is composed by at least 5 sprites. There is a better/easier way to do it? Maybe with 2D Shader?

# Answer
What you describe *will* work; we've done exactly that before. The key is to organize your asset creation flow. We used Illustrator/ Vector Smart Objects to build our layered files that were then "decolorized" before importing to Unity as sprites.

Another approach, especially if you are doing a pixel art style, would be to pre-process your sprite textures in Unity by making copies that replace key pixel colors with your enemy palette sets.
> 1 votes

---
Tags: unity, pixel-art
---


# Question
Title: Why is my shader's call to UnityObjectToClipPos() causing my *other* shaders to be invisible?
I created a shader via a node-based shader tool called Shadero Sprite, and I'm trying to debug an issue with it. Since the code was generated by the node-based tool, I'm not entirely sure what the purpose of every line in the shader is, which makes this issue difficult to debug.

The issue is that, although the shader itself works fine, having an object with it in my Unity scene causes certain *other* objects in my scene to not render at all; they become invisible.

It seems to be something related to this call to `UnityObjectToClipPos()` below:

```
        v2f vert(appdata v)
        {
            v2f o;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.uv = TRANSFORM_TEX(v.uv, _MainTex);
            UNITY_TRANSFER_FOG(o,o.vertex);
            return o;
        }

```

...because, if I replace...

```
            o.vertex = UnityObjectToClipPos(v.vertex);

```

...with...

```
            o.vertex = v.vertex;

```

then the other shaders/objects render fine. However, this of course means that THIS shader doesn't look right.

The only other clue I've been able to deduce is that the other objects (the ones that go invisible) are Unity UI elements that all have custom shaders. One shader is using a call to UnityObjectToClipPos(). The other doesn't seem to (although it has many `#includes`, so perhaps a call to it does exist, buried in one of those `#includes`).

Why is this function call causing other objects to go invisible, and what can I replace it with to fix it?

**EDIT:** Per @DMGregory's comment, it's unlikely an issue with the shader itself; here is the scene configuration for greater context:

# Answer
The issue ended up being with the shader I was using for my text.

The text uses a Unity asset called SuperTextMesh, which offers multiple shaders for text. I was using the "Dropshadow and outline unlit" shader, when I needed to use the "Dropshadow and outline" shader instead. The "unlit" one caused issues.
> 0 votes

---
Tags: unity, shaders, cg
---


# Question
Title: How to make mouse pointer be the vertex of a drawn parabola when estimating the trajectory of a projectile?
I'm trying to remake an old flash game using Unity. The main mechanic of the game is to make the basketball pass over the mouse.

Here's a video of the game: https://www.youtube.com/watch?v=6sArMC1l\_Sc

I've been trying to get the hang of this mechanic for two whole days and I still haven't been able to reproduce it. This is what I've been able to make so far. (forgive me for the colors, my screen gives weird colors when recording it)

As you will see, I managed to calculate the trajectory of the ball, and calculate the speed to follow that trajectory. What bothers me is that the vertex of the drawn parabola is not placed on top of the mouse, but it is displaced to the left. The further left the mouse is from the ball, the more this delta between the vertex and the mouse is pronounced.

I think this is happening because I calculate the initial velocity `U` using only the angle `α` and the maximum height the ball will reach `hmax`. I have not found a formula that allows me to "force" the `(x,y)` point of the mouse as the vertex of the parabola and gives me a way to calculate the velocity I need to apply to the ball for it to reach that `(x,y)` a its highest peak.

I have written a list the parameters and formulas for the SUVAT equations I have found throughout my research on the internet, so I'll list them right below.

```
    /*
     * SUVAT EQUATIONS
     * S    | horizontal distance traveled
     * U    | initial velocity
     * Ux   | initial horizontal velocity
     * Uy   | initial vertical velocity
     * V    | final velocity
     * A    | standard acceleration due to gravity on the surface of the earth (≈ 9.807 m/s^2)
     * T    | travel time
     * h    | initial height
     * hmax | maximum height
     * α    | release angle relative to horizontal
     *
     *
     * When h = 0:
     *
     * Ux = U * cos(α)
     * Uy = U * sin(α)
     * T = 2 * Uy / A
     * hmax = (v^2 sin^2(α))/(2 * A)
     * hmax = Uy^2 / (2 * A)
     * S = (v^2 sin(2 α))/A (old)
     * S = 2 * Ux * Uy / A
     *
     * S  = Ux * T
     * Ux = S/T
     * Uy = (hmax/T + (1/2)) * A * T
     * T = (2 v sin(α))/A
     *
     * When h != 0:
     *
     * Ux = U * cos(α)
     * Uy = U * sin(α)
     * t = (Uy + sqrt(Uy^2 + 2 * A * h)) / A
     * S = Ux * [Uy + sqrt(Uy^2 + 2 * A * h)] / A
     * hmax = (h + Uy²) / (2 * A)
     * Uy = sqrt( (hmax - h) / (2*A))
     * U = sqrt(V - 2A * hmax)
    */

```

Here's a recap of the equations I am using to have this result:

## Angle Calculation

```
    private float GetAngleInDegreesBetweenMouseAndObject2()
    {
        _mouseWorldPosition = GetMousePositionFrom3DWorld();
        _mouseWorldPosition.z = transform.position.z;

        _distanceBetweenObjectAndMouse = Vector3.Distance(transform.position, _mouseWorldPosition);
        _mouseDirection = _mouseWorldPosition - transform.position;

        var angle = Vector2.SignedAngle(Vector2.left, _mouseDirection);
        Debug.Log($"angle: {angle}");
        return angle;
    }

    private Vector3 GetMousePositionFrom3DWorld()
    {
        // I have drawn a 2D plane in order to be able to get an accurate mouse position, with its Z axis being the same all the way.
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (_launchArcPlane.Raycast(ray, out float distance))
        {
            return ray.GetPoint(distance);
        }
        return transform.position;
    }

```

## Maximum Height Calculation

```
    private float GetMaximumHeightForObject()
    {
        return _mouseWorldPosition.y - transform.position.y;
    }

```

## Initial Velocity Calculation

```
    private void CalculateInitialVelocityUsingFinalVelocityMaximumHeightAndAngle()
    {
        _initialVelocity = Mathf.Sqrt(2 * _gravity * _maximumHeight) / Mathf.Sin(_angleInRadians);
    }

```

## Initial Velocity Vector Calculation

```
    private void CalculateVelocityVectorUsingInitialVelocityAndAngle()
    {
        _initialVelocityVector = new Vector3(_initialVelocity * Mathf.Cos(_angleInDegrees * Mathf.Deg2Rad), _initialVelocity * Mathf.Sin(_angleInDegrees * Mathf.Deg2Rad), 0);
    }

```

## Setting Velocity To Ball On Click

```
    private void SetVelocityAndGravityForObject()
    {
        _hasShot = true;
        _RigidBody.useGravity = true;
        _RigidBody.velocity = _initialVelocityVector;
    }

```

## Rest Of The Code

Here's the rest of the code ^^ In case anyone needs any more information in order to get further into this. Beware though, it has some unused functions from the trial an error of different equations I have found throughout the week-end: https://gist.github.com/Juansero29/f3f5a0a7e6c68588dd97ea1fe5d9b59e

I'm an application developer, and I'm interested in the world of games, but I had never tried to achieve a physical mechanic like this, and it's giving me a lot of headaches ^^ (I can't read no more SUVAT equations this week-end lol). Any help from fellow physicians or game develops would be very much appreciated

**Edit:** Here's the result after using DMGregory's help! Thanks a lot!

# Answer
> 3 votes
I think we can do this more simply. This demo uses about 80 lines of code (the interesting ones being just the dozen below), instead of over 300, with no angles/trigonometry functions needed:

At the time \\$t^\*\\$ when we reach the vertex, we know the acceleration due to gravity has completely wiped out our vertical launch velocity:

$$\begin{align} v\_y + a\_g t^\* &= 0\\ v\_y &= - a\_g t^\* \end{align}$$

We can substitute this into our equation for the position, and get a relation between \\$t^\*\\$ and the height of our vertex above the launch position \\$h = p\_y(t^\*) - p\_y(0)\\$:

$$\begin{align} p\_y(t) &= p\_y(0) + v\_y t + \frac 1 2 a\_g t^2\\ p\_y(t^\*) - p\_y(0) &= (-a\_g t^\*) t^\* + \frac 1 2 a\_g {t^\*}^2\\ h &= -a\_g {t^\*}^2 + \frac 1 2 a\_g {t^\*}^2\\ h &= \frac {-1} 2 a\_g {t^\*}^2\\ \frac {-2 h} {a\_g} &= {t^\*}^2 \end{align}$$

We can also use that same equation to get a formula for the vertical velocity (I express it this way because it lets us calculate the horizontal and vertical components together later):

$$\begin{align} h &= v\_y t^\* + \frac 1 2 a\_g {t^\*}^2\\ h - \frac 1 2 a\_g {t^\*}^2 &= v\_y t^\*\\ \frac {h - \frac 1 2 a\_g {t^\*}^2} {t^\*} &= v\_y \end{align}$$

```
Vector3? GetLaunchVelocityToVertex(Vector3 launchSite, Vector3 vertex) {
    Vector3 travelToVertex = vertex - launchSite;

    float timeToPeakSquared = -2f * travelToVertex.y / Physics.gravity.y;
    // If your gravity is not always vertical, you can use this instead:
    // Vector3 down = Physics.gravity.normalized;
    // float timeToPeakSquared = -2f * Vector3.Dot(travelToVertex, down)
    //                           / Vector3.Dot(Physics.gravity, down);

    // If this is zero then the peak is at the same height as the launch point.
    // If it's less than zero, the peak is below, so we have no valid arc there.
    if (timeToPeakSquared <= 0f) return null;

    float timeToPeak = Mathf.Sqrt(timeToPeakSquared);

    return (travelToVertex - 0.5f * Physics.gravity * timeToPeakSquared)
           / timeToPeak;
}

```

Use this velocity to plot your parabolic arc with the equation of motion, something like...

```
float previewTimeSpan = 3f * timeToPeak;
float timeStep = previewTimeSpan / (_parabolaPoints.Length - 1);

for (int i = 0; i < _parabolaPoints.Length; i++) {
    float t = i * timeStep;
    _parabolaPoints[i] = launchSite
                       + launchVelocity * t
                       + 0.5f * Physics.gravity * t * t;
}

```

Now one little trick: the symplectic physics integrators used by Unity's PhysX and Box2D physics engines won't trace this arc *exactly* if you give them this launch velocity as-is. That's because of the way they update the velocity first, then update the position using the velocity as of the *end* of the frame, rather than its average value over the whole frame. In effect, they add an extra half a physics step's worth of acceleration to the initial velocity.

For most purposes this tiny time shift is unnoticeable, so it's a sensible optimization to make the physics simulation faster. For cases where we care about tracing a predicted arc perfectly, we can correct for it by just increasing our initial velocity ever so slightly:

```
projectile.velocity = launchVelocity
                    - 0.5f * Physics.gravity * Time.fixedDeltaTime;

```

---
Tags: unity, c#, physics, projectile-physics, trajectory
---


# Question
Title: How to set a variable from the selected text of a dropdown menu in Unity?
I am trying to set a variable from the value of a DropDown menu in Unity.

I wrote a script as follows, attached it to the dropdown and set it to run it in Unity under: **On Value Changed (Int32)**.

I have confirmed it is running when the dropdown changes from the debug output. However, it is giving me the `NullReferenceException: Object reference not set to an instance of an object` error when trying to get the dropdown's value.

The function I am running is `ChangeLocationDropDown()`:

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

public class LocationSelectorDropDown : MonoBehaviour
{
public void ChangeLocationDropDown() {
        Debug.Log("DROP DOWN CHANGED");
        Dropdown m_Dropdown;
        m_Dropdown = GetComponent<Dropdown>();
        Debug.Log(m_Dropdown.options[m_Dropdown.value].text);
    }
}

```

I get the `DROP DOWN CHANGED` debug output but when I try to get the second debug it says:

`NullReferenceException: Object reference not set to an instance of an object LocationSelectorDropDown.ChangeLocationDropDown ()`

This Unity page suggests fixing this error by somehow using `GameObject.Find` to manually find the dropdown object first by its string name. But this is incredibly impractical and not a proper solution. I may need to make dozens of dropdowns. I need some simple clean way for each value to go into its own variable and/or update a database with their value with every change made.

What is the proper way to handle this?

ie. How do you update a string variable with the new text value of the DropDown?

# Answer
> 2 votes
I tried creating the same setup as you mentioned but I didn't got error. Seems there might be any small mistake, please check below. And also added the update to value to string variable part.

```

using UnityEngine;
using UnityEngine.UI;

public class LocationSelectorDropDown : MonoBehaviour
{
    [SerializeField]
    Text textBox;

    string valueText = "";

    public void ChangeLocationDropDown()
    {
        Debug.Log("DROP DOWN CHANGED");
        Dropdown m_Dropdown;
        m_Dropdown = GetComponent();
        Debug.Log(m_Dropdown.options[m_Dropdown.value].text);

        //store in variable
        valueText = m_Dropdown.options[m_Dropdown.value].text;
        //set textbox value
        textBox.text = valueText;
    }
}

```

Also please have a look at the output DropDownTest\_Unity

P.S. : I am putting it as answer as for the moment i cannot comment

# Answer
> 2 votes
Your code as presented *will* work, provided it is added as a component to a gameobject that also contains a Dropdown component, like so:

However, if the script responding to the valueChange event is a component of some other game object, you'll need to provide a reference. Here's a simple example script:

```
using UnityEngine;
using UnityEngine.UI;

public class DDDemo : MonoBehaviour
{
    [SerializeField] private Dropdown m_Dropdown; // wire this in Inspector

   public void OnMyDropdownChanged()
    {
        Debug.Log(m_Dropdown.options[m_Dropdown.value].text);
    }
}

```

Which will work if wired up in this manner (here the script is attached to the Controller game object):

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


# Question
Title: Seeking a more elegant solution to set buttons so they can increase specific ability level and stats
```
public class AbilitiesUpgradePanel : MonoBehaviour
{

    [SerializeField] Button[] buttons = new Button[3];
    [SerializeField] Text[] abilityNameText = new Text[3];
    [SerializeField] Text[] abilityDescriptionText = new Text[3];
    [SerializeField] Text[] abilityLevelText = new Text[3];
    [SerializeField] Image[] abilityImage = new Image[3];

    private int totalAbilitiesCount = 3;

    public void RandomAbilitesToLevelUp()
    {
        List<int> generatedIds = new List<int>(); //I need each button to have unique ability
        for (int buttonIndex = 0; buttonIndex < totalAbilitiesCount; buttonIndex++)
        {

            int abilityId = Random.Range(0, totalAbilitiesCount);
            while (generatedIds.Contains(abilityId))
            {
                abilityId = Random.Range(0, totalAbilitiesCount);
            }

            if (abilityId == 0)
            {
                buttons[buttonIndex].onClick.RemoveAllListeners();
                buttons[buttonIndex].onClick.AddListener(UpgradeBullet);
                abilityNameText[buttonIndex].text = Bullet.instance.abilityName;
                abilityLevelText[buttonIndex].text = Bullet.instance.abilityLevel.ToString();
                abilityDescriptionText[buttonIndex].text = Bullet.instance.abilityUpDescription;
                abilityImage[buttonIndex].sprite = Bullet.instance.abilitySprite;
            }
            else if (abilityId == 1)
            {
                buttons[buttonIndex].onClick.RemoveAllListeners();
                buttons[buttonIndex].onClick.AddListener(UpgradeLighting);
                abilityNameText[buttonIndex].text = Lightning.instance.abilityName;
                abilityLevelText[buttonIndex].text = Lightning.instance.abilityLevel.ToString();
                abilityDescriptionText[buttonIndex].text = Lightning.instance.abilityUpDescription;
                abilityImage[buttonIndex].sprite = Lightning.instance.abilitySprite;
            }
            else if (abilityId == 2)
            {
                buttons[buttonIndex].onClick.RemoveAllListeners();
                buttons[buttonIndex].onClick.AddListener(UpgradeSatellite);
                abilityNameText[buttonIndex].text = Satellite.instance.abilityName;
                abilityLevelText[buttonIndex].text = Satellite.instance.abilityLevel.ToString();
                abilityDescriptionText[buttonIndex].text = Satellite.instance.abilityUpDescription;
                abilityImage[buttonIndex].sprite = Satellite.instance.abilitySprite;
            }

        generatedIds.Add(abilityId);
        }
    }

// Abilities (Bullet, Lightning, Satellite)
//BULLET
    public class Bullet : MonoBehaviour
{
    public static Bullet instance;

    [SerializeField] GameObject bulletPrefab;

    public string abilityName = "Bullet";
    public string abilityUpDescription = "Default Projectile Shooting";
    public int abilityId = 0;
    public Sprite abilitySprite;

    private Enemy closestEnemy;
    private GameObject instantiatedBullet;

    public float damage = 15f;
    public float cooldown = .7f;
    public float castDistance = 18f;
    public float projectileSpeed = 4f;
    public int abilityLevel = 0;

    Rigidbody2D rb;
    Vector2 moveDirection;

    private void Awake()
    {
        instance = this;
    }

    void Start()
    {
       StartCoroutine(CastBullet());
    }

//SATELLITE
    public class Satellite : MonoBehaviour
{
    public static Satellite instance;

    [SerializeField] GameObject satellitePrefab;
    [SerializeField] GameObject satellitesHolder;

    public string abilityName = "Satellite";
    public string abilityUpDescription = "Creates a sattelite flying around you";
    public int abilityId = 2;
    public Sprite abilitySprite;

    Vector3 center;

    public float damage = 20f;
    public float rotationSpeed = 100;
    public float distanceFromPlayer = 1;
    public int maxSatellites = 1;
    public int currentSatellites = 0;
    public int abilityLevel = 0;

    private void Awake()
    {
        instance = this;
    }

    private void Start()
    {
        satellitesHolder.SetActive(true);
        SpawnSatellites();
    }

//LIGHTNING
 public static Lightning instance;

    [SerializeField] GameObject lightningPrefab;

    public string abilityName = "Lightning";
    public string abilityUpDescription = "Creates a lightning strike";
    public int abilityId = 1;
    public Sprite abilitySprite;

    private GameObject instantiatedLightning;
    int instantiadetLightningsCount;

    public float castDistance = 7f;
    public float damage = 20f;
    public float cooldown = 1f;
    public int maxTargets = 2;
    public int abilityLevel = 0;

    private void Awake()
    {
        instance = this;
    }

    private void Start()
    {
        StartCoroutine(CastLightning());
    }

```

# Answer
> they can't derive from a base class. Yes, they share many of the same properties but they also share many unique properites. – xmaximix 1

Actually I think you can. This a pattern I use all the time for stuff like this and it works very well.

First, I suggest your abilities derive not from Monobehaviour, but from ScriptableObject. They won't recieve events, so you'll have to handle that some other way, (if at all -- do you actually ever need to instantiate an "ability"?\*), but it does make for a nice neat way to create related entities that share many of the same properties and methods.

So -- base Ability class:

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

public class Ability : ScriptableObject
{

    public enum Type
    {
        bullet,
        satellite,
        lightning
    }

    public Type type; // or use get; set;

    public string abilityName = "Lightning";
    public string abilityUpDescription = "Creates a lightning strike";
    public int abilityId = 1;
    public int abilityLevel = 0;
    public Sprite abilitySprite;

    public virtual void Start()
    {
        Debug.Log("Ability started");
    }

    public virtual void CreateAbilityButton(Button button)
    {
        // If button gameobject are configured identically can simply get child components using Find

        button.onClick.RemoveAllListeners();

        button.transform.Find("Ability Name").GetComponent<Text>().text = abilityName;
        button.transform.Find("Ability Level").GetComponent<Text>().text = abilityLevel.ToString();
        button.transform.Find("Ability Description").GetComponent<Text>().text = abilityUpDescription;
        button.transform.Find("Ability Sprite").GetComponent<Image>().sprite = abilitySprite;
    }

}

```

And a derived Bullet class:

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

[CreateAssetMenu (menuName = "Abilities/ Bullet")]
public class Bullet : Ability
{

    [SerializeField] GameObject bulletPrefab;

   // private Enemy closestEnemy;
    private GameObject instantiatedBullet;

    // extra properties for bullet
    public float damage = 15f;
    public float cooldown = .7f;
    public float castDistance = 18f;
    public float projectileSpeed = 4f;

    Rigidbody2D rb;
    Vector2 moveDirection;

    public override void CreateAbilityButton(Button button)
    {
        base.CreateAbilityButton(button);
        button.onClick.AddListener(() => { DoSomeGreatAction(); });

    }

    public void DoSomeGreatAction()
    {
        Debug.Log("Hello from Bullet");
    }

    public override void Start()
    {
       // do some initialization
    }
}

```

lightning...

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

[CreateAssetMenu(menuName = "Abilities/ Lightning")]
public class Lightning : Ability
{

    public static Lightning instance;

    [SerializeField] GameObject lightningPrefab;
    private GameObject instantiatedLightning;
    int instantiadetLightningsCount;

    public float castDistance = 7f;
    public float damage = 20f;
    public float cooldown = 1f;
    public int maxTargets = 2;

    public override void CreateAbilityButton(Button button)
    {
        base.CreateAbilityButton(button);
        button.onClick.AddListener(() => { DoSomeCoolLightningButtonAction(); });

    }

    public void DoSomeCoolLightningButtonAction()
    {
        Debug.Log("Lightning is lit, yo");
    }

    public override void Start()
    {
       // do whatever you want on start
    }
}

```

Etc.

And now the good part -- code to create the buttons is really simplified:

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

public class AbilitiesUpgradePanel : MonoBehaviour
{

    [SerializeField] Button[] buttons;

    [SerializeField] public List<Ability> abilities; // a list containing all your ability prototype

    private void Start()
    {
        RandomAbilitesToLevelUp();
    }

    public void RandomAbilitesToLevelUp()
    {

        List<Ability> threeUniqueAbilties = new List<Ability>();
        int buttonCount = 0;
        while (threeUniqueAbilties.Count < buttons.Length) // magic number
        {
            Ability proposed = abilities[Random.Range(0, abilities.Count)];
            if (!threeUniqueAbilties.Contains(proposed))
            {
                threeUniqueAbilties.Add(proposed);
                proposed.CreateAbilityButton(buttons[buttonCount]);
                buttonCount++;
            }
        }
    }
}

```

Making these scriptable objects means you can easily make many variants of each ability type -- each with whatever custom variables and methods you need to support that type.

\*if you do need to instantiate an "ability" for some reason, you can create a sister runtime class, for which the scriptable object acts as an immutable.
> 5 votes

---
Tags: unity, performance, unity-ui
---


# Question
Title: How to make environment art like the building interiors in Digimon World 3
I'm wondering how to create art like this (the map, not the characters), is this 2D or 3D?

# Answer
I believe - judging by video footage of the game, and the platform the game was released on - that the background is pre-rendered 3D made into square tiles.

To replicate that, you would create the scenario in 3D with textures. Then render it form a isometric perspective (you want both the color and depth), then chop that into squares, and then use those squares as tiles in the game.

Why do you want depth? In game you can position and render the character in 3D space with depth test (so they can walk behind some parts of the background).

Why do you want to chop it into tiles? So you don't have to load one big texture for the map. Instead you can load the tiles as they are needed.

However, the 3D scene would have very simple geometry. Since they and you knew the viewing angle, doing some hand painted parts instead of using 3D geometry is possible. Round objects, and objects not accesible to the player are good candidates.

In the provided screenshot we see some round objects that probably aren't modeled, but hand drawn. So they don't add to the polygon count. That would have been important to keep pre-render times low, and iterate fast.

There is another reason to keep the pre-render model simple: they can use it to generate navigation meshes or collision meshes. *Which is also a reason to make it 3D, instead of hand painting everything, which would have allowed for a more organic look.*

*These are all decisions informed by hardware limitations. Limitations which you would not have today. However, if you are going for an authentic look, you can let those limitation inform your creativity.*
> 1 votes

---
Tags: 2d, 3d, sprites, art
---


# Question
Title: How do I predict where a player will be next in Forge/MCP?
I am trying to predict where a player will be next based on where they are now in Java. I have their *XYZ* position, their *XYZ* motion, but I don't have their speed. How can I predict where they will be in a couple of seconds based on their current position and motion?

I am doing this in Minecraft Forge/MCP but since this is probably more of a math/Java thing, I don't need an answer specific to Forge/MCP.

Thanks!

**EDIT:** The motion values for the player are the following:

While walking on positive *Z* axis (for some wierd reason)

```
Motion X: 2.0520011355833548E-4
Motion Y: -0.0784000015258789 // Gravity
Motion Z: 0.11785815704137818 // Basically 0

```

While running on positive *Z* axis

```
Motion X: 6.335480841945934E-4
Motion Y: -0.0784000015258789 // Gravity
Motion Z: 0.15320559375099232 // Basically 0

```

# Answer
> 0 votes
I threw some math at this, which could maybe give you something towards an approximation, but TBH the result is somewhat disappointing, perhaps because I'm not really sure what space the initial values are supposed to be in:

We can simply take the movement component values (ignoring gravity) from the values you've gotten and calculate the speed of the player in whatever units they happen to be in:

$$ v\_{walking} = \sqrt{v\_{wx}^2+v\_{wz}^2} \approx 0.1179 \\ v\_{running} = \sqrt{v\_{rx}^2+v\_{rz}^2} \approx 0.1532 $$

Now, from the Minecraft Wiki the speed for sprinting should be \\$5.612m/s\\$, and walking \\$4.317m/s\\$.

From this we can try to figure out what the units have been multiplied with to arrive at the values present in the code: $$ v\_{walking} \approx 4.317 \cdot a \\ v\_{running} \approx 5.612 \cdot a \\ \implies a \approx 0.027 $$

(Note that I'm doing some quite harsh approximations and you might want to double check these incase some rounding errors accumulate...)

You'd usually expect \\$a\\$ to possibly represent the delta time, but this doesn't seem to match up with any usual delta-times (this would represent an update rate of 37Hz, which doesn't seem to match up with anything I know of Minecraft's update systems...).

Anyways, with this mysterious constant known you should be able to estimate a future position simply by doing

$$ \vec{p}\_{future} \approx \vec{p}\_{now}+\frac{\vec{motion} \cdot secondsToFuture}{a} \\ $$

---
Tags: java, mathematics, minecraft-modding, movement-prediction
---


# Question
Title: Unity Animator - bool transitions keep re-entering state while true
My StateMachine is triggered in a loop as long as transition boolean is true.

I have made sure my code only runs once, where I set the animation bool:

```
animator.SetBool("talk", true);

```

This does trigger the transition but the problem is that it re-triggers every frame as long as the bool is true. I had the same issue with a normal state earlier, but there I could turn off "Can transition to self" which solved it. However a StateMachine does not have that option.

I want the animation to play until the bool is set back to false, so using a trigger would not be good here.

EDIT: For some reason it seems the "Transition duration" is the one resetting my animation. So if I change that to 3, it re-enters every 3 seconds, and so on. This seems really weird?

How do I just make sure that the animation plays until its done, then it re-enters (to choose another random talking animation from my StateMachine), as long as `talk == true`?

# Answer
> 3 votes
In many cases, like working with a network game, you don't have the option of using trigger as it malfunctions over the network, so to solve this issue and continue using bool parameters, you just click on the transition, expand the Settings in the inspector and uncheck "Can Transition To Self".

---
Tags: unity, animation
---


title: why does my mesh render on top of UI?

text:
# Question
Title: why does my mesh render on top of UI?
I've got some UI elements and a 3D mesh imported from blender. I've tried stuff like sorting layers, so that I render my 3D mesh below a canvas UI element(side panel), for which I put my 3D mesh prefab under the UI layer, but, my mesh always ends up rendering on top. How can I render my mesh below the UI element? This is similar to the TMP(Text Mesh Pro) issue I have seen on the web, but, I already have front and back materials for the mesh, so I can't use TMP's distance field overlay shader.

Here's the basic hierarchy:

parent
| -----\>myprefabMesh (on layer UI)
|
|----\>UISidePanel (on Layer side panel)

Sorting layer order:
-- UI
-- LayerSidePanel

# Answer
> 1 votes
The problem I was having is as mentioned above, I was having the canvas in screen space camera mode rather than in screen space overlay mode.

---
Tags: unity, rendering, mesh, unity-ui
---


# Question
Title: Is it plausible for Tetris to be running at around 250 fps on a laptop?
I coded a simple Tetris game to for some programming practice. It has all the features you would expect from Tetris, like rotating shapes and clearing rows. I implemented a frame rate measure tool out of curiosity to see what the frame rate was. It is currently saying that the game is running at around 250 fps. Could that be accurate? That seems very high to me, but I don't really know too much about computers. Is it realistic for even a simple game like Tetris to run at such high speeds on a laptop, or is my measuring off?

These were the two ways I used for counting the FPS, I suspect that they are both flawed.

Method 1, which generally gave lower results:

```
{

        //At the end of my game loop

        static unsigned int ticks = 0;
        static unsigned int ticksAtStart = 0;
        static sf::Clock clock;

        ticks++;
        if (clock.getElapsedTime().asMicroseconds() >= 1000000)
        {
            frameRate_ = ticks - ticksAtStart;
            ticksAtStart = ticks;
            clock.restart();
        }
}

```

Method 2, which generally gave higher results:

{
        // At the end of my game loop

        static sf::Clock;
        frameRate_ = (unsigned int)std::roundf(1000000.f / (float)clock.getElapsedTime().asMicroseconds());
        clock.restart();
}
```

# Answer
> 1 votes
The game mechanics of Tetris are not very computationally expensive. It ran fine on the 4.19 MHz CPU of my Nintendo Game Boy in 1990.

And I don't know what *your* version of Tetris does for the visual representation. With enough time, creativity and knowledge of GFX programming, it is perfectly possible to create a Tetris version full of fancy but expensive graphic effects. But when you are a beginner then I doubt that you do anything more advanced than just blitting sprites.

So I assume that what you have is a Tetris clone which does use simple graphics and which is implemented in a straight-forward manner with no major performance blunders but also no fancy optimization tricks. Such a game running on 250 Fps on a modern low-budget laptop is pretty plausible.

But it is of course not impossible that your programming isn't actually that free of performance blunders, and that your FPS counter is buggy too. Hard to tell without seeing your code. So when your FPS counter says the game runs at 250 FPS but what you see on the screen does not *look and feel* like 250 FPS, then you might want to show us how exactly you implemented it.

# Answer
> 1 votes
A 2D game of Tetris can indeed run very fast on current day computers. Because this is maybe the first time you programmed a frame rate measuring tool it is hard to say if you can trust it.

You could of course run a third party tool to measure the framerate of your tetris game. There are many tools to choose from, some hidden in the control panel of your GPU like GeForce Experience or Radeon Adrenalin. (Depending on your hardware.) On Windows 10 there is also a performance window you can open on the "XBox Game Bar".

Another idea is to enable "vsync" either from your games code/settings or from your graphics control panel. VSync means vertical-synchronisation and it would prevent your game from drawing faster than your screen can display images. Typically displays show 60 to 144 images per second. (If you have a freensync/gsync monitor this would be wrong though.)

---
Tags: performance, tetris
---


title: Get Angle offset

text:
# Question
Title: Get Angle offset
I'm working on a game where the input is done via a joystick. Normally, one would snap the players rotation to the angle that the joystick is pointing, but for my game's purpose, I have to lerp to the value to give a smooth animation. My joypad angles are calculated as follows:

1. 0 - left
2. 90 - front
3. 180 - right
4. 270 - back

An example of my problem would be: I'm pointing joystick 'front-left'(45 degrees), then I move it 'back-left'(315 degrees), instead of doing the hoped for simple anticlockwise rotation, it rotates clockwise to the value.

I understand why it happens, but I just don't have an idea how to solve this problem. I'd greatly appreciate any input, doesn't have to be code.

# Answer
> 1 votes
You can do this with an angle difference function:

```
// Remaps angles into [0, 360) range on degrees.
float NormalizeAngle(float angle) {
    return angle - floor(angle / 360f) * 360f;
}

// Returns the shortest signed angular delta
// from angle from to angle to, in degrees.
float AngleDifference(from, to) {
    // Wrap difference into [0, 360) range.
    float difference = NormalizeAngle(to - from);

    // Remap to range (-180, 180]
    // so that angles more than a half turn away
    // go via the shorter route.
    if (difference > 180) difference -= 360f;

    return difference;
}

// Linearly interpolates between two angles,
// using interpolation weight blend in [0, 1].
// Return is normalized into [0, 360) range.
float LerpAngle(from, to, blend) {
    float difference = AngleDifference(from, to);

    return NormalizeAngle(from + blend * difference);
}

```

---
Tags: rotation, joystick
---


# Question
Title: What is the correct approach to swapping between rigged models at runtime?
Lets say we are making an RTS and at runtime a unit can go from worker to soldier to baker to forester to male to female and so on, you get the idea.

This requires several different character models. Our current approach to this is to "merge" the models under on main object and have them share a rig since they share proportions. This approach lets us simply active/disable the model we need at runtime, and lets us easily set up a new prefab by just picking the correct model. I see some limitations to this approach, for example when we need other proportions later we will need a different avatar (fat, skinny etc).

Is there a better way? What is the "standard"?

# Answer
> 1 votes
For this case you can use the same rig for all models, so when the "role" of the character changes you can just enable a different mesh included in the same hierarchy

> **Character**
>
> * ---\> Rig
> * ---\> MeshWorker
> * ---\> MeshSoldier

At this point you can and already is, avoiding instantiations, pools, is faster, not overload and you have to work with only one rig and avatar.

For the problem with a different avatar the approach (I) recommended is to use something like a on-the-fly-character system, so you will use another complete different character which you can instantiate or just pick from your pool of "FatWorkers", repositioning in the place of the other character which will be hide and added to the other pool.

# Answer
> 1 votes
Depending on your needs for characters of different proportions, wardrobes, hairstyles, etc, UMA (Unity Multipurpose Avatar) might be an option worth checking out. Setting up "races" is kind of a pain, but once done the system is quite flexible and does some very clever things with texture atlasing and mesh hiding to name a few.

This makes it possible to easily create hundreds of characters all sharing the same "DNA" but with endless variation (fat/ skinny, skin color, hair, you name it). In your scenario, your individual characters can then quite easily change wardrobe items at runtime to assume the different roles you require. Each character is distilled down to as little as one SkinnedMeshRenderer (depending on warddrobe materials) and packed on the fly to a single texture atlas.

UMA 2 on Asset Store (free)

---
Tags: unity, animation
---


# Question
Title: Optimization problem with tweening UI using DOTween in Unity
I read in a Unity blog post that using normal animation with UI in Unity is not really recommended, but instead you should use tweening if you can. To test this so I tried the same animation with both methods. I'm not really expert in tweening but this was really simple animation so I thought it should be ok. Basically I'm filling a image from 0 to 1 with looping animation. When I compared these two methods of animation in the profiler I noticed that while tweening, I get spikes of about 20ms for the time the tween is active, which is similar to normal animation. I'm not sure if this is normal behavior for UI or I am doing something wrong. This is my tween code:

```
Tween tween;
private void OnEnable()
{
    tween = image.DOFillAmount(1, 1f).From(0).SetAutoKill(false);
    tween.OnComplete(() => tween.Restart());
}

private void OnDisable()
{
    tween.OnComplete(null);
    tween.SetAutoKill(true);
}

```

I also tried something like this which does the same thing:

```
 private void OnEnable()
{
    tween = image.DOFillAmount(1, 1f).From(0).SetLoops(-1, LoopType.Restart);
}

private void OnDisable()
{
    tween.Kill();
}

```

Profiler Screenshot:

# Answer
As pointed out in the comments the issue was normal editor overhead. While profiling game in standalone spikes disappeared.
> 0 votes

---
Tags: unity, tweening, dotween
---


# Question
Title: LibGDX: Why won't certain actions work on my Actor?
In my GameClass, I called the Stage.act and Stage.draw methods in the right order accordingly.

I have actions set up so that the actor fades in/fades out, bounces down/up, and also rotate, like so:

```
Label.LabelStyle font = new Label.LabelStyle(new BitmapFont(), Color.BLACK);

    Table table = new Table();
    table.center();
    table.setFillParent(true);

    Label playLabel = new Label("Text", font);

    Action fade = new SequenceAction(Actions.fadeOut(1), Actions.fadeIn(1));
    Action size = new SequenceAction(Actions.sizeBy(-20,-30,1), Actions.sizeBy(10,20,1));
    Action rotate = new SequenceAction(Actions.rotateBy(20), Actions.rotateBy(-40));

    ParallelAction pa = new ParallelAction(fade, size, rotate);

    playLabel.addAction(Actions.repeat(RepeatAction.FOREVER, pa));

    table.add(playLabel).expandX();
    table.row();

    stage.addActor(table);

```

The thing is, everything works *except* for the rotate method.

Similarly, I have similar problem when I use an Actor with Texture regions.

This is an example from another class.

```
public ReadyText () {
    cam = GameClass.cam;
    viewport = GameClass.viewport;
    cam.setToOrtho(true, viewport.getWorldWidth(), viewport.getWorldHeight());
    region = new TextureRegion(GameAssetLoader.Ready);
    this.setX(28);
    this.setY(165);
    this.setWidth(80);
    this.setHeight(30);

    //fade = Actions.sequence(Actions.fadeOut(1), Actions.fadeIn(1));
    Action rotate = Actions.sequence(Actions.rotateBy(80, 1), Actions.rotateBy(-90,1));
    Action resize = Actions.sequence(Actions.sizeBy(10, 5,1), Actions.sizeBy(-10,-5,1));

    ParallelAction pa = new ParallelAction(rotate, resize);

    addAction(Actions.repeat(RepeatAction.FOREVER, pa));

}

@Override
public void draw(Batch batch, float parentAlpha) {
    super.draw(batch, parentAlpha);

    batch = GameClass.batch;
    batch.setProjectionMatrix(GameClass.cam.combined);
    batch.draw(region, this.getX(), this.getY(), this.getWidth(), this.getHeight());

}

```

In this example, the "sizeBy" method works fine. But for some reason, it will not rotate. I commented out the "fade in/fade out" line; it also wasn't working either.

I know people will usually use an Image Actor instead, which makes sense, but I don't think it explains why the rotation won't work, or at the very least, why the Label didn't rotate either.

# Answer
> 2 votes
## You need to draw you actor with a method that *handle rotation*

```
void draw(TextureRegion region,
      float x,
      float y,
      float originX,
      float originY,
      float width,
      float height,
      float scaleX,
      float scaleY,
      float rotation)

```

**And for alpha actions:** (this *myActor* draw method)

```
batch.begin();

// Store old batch alpha
temp = batch.getColor();

// Set new alpha to the batch
batch.setColor(new Color(temp.r, temp.g, temp.b, actorAlpha));

// Draw your actor
batch.draw(texture, getX(), getY(), getOriginX(), getOriginY(), texture.getRegionWidth(), texture.getRegionHeight(), 1, 1, getRotation());

// Restore old batch color
batch.setColor(temp);

batch.end();

```

Where temp is a Color.

# Answer
> 0 votes
## For Texture:

---

```
public void draw (
      Texture texture,
      float x, float y,
      float originX, float originY,
      float width, float height,
      float scaleX, float scaleY,
      float rotation,
      int srcX, int srcY,
      int srcWidth, int srcHeight,
      boolean flipX, boolean flipY
);

```

**Solution:**

```
override fun draw(batch: Batch, parentAlpha: Float) {
        batch.draw(previewTexture, x, y, originX, originY, width, height, scaleX, scaleY, rotation, 0, 0, yourTexture.width, yourTexture.height, false, false)
    }

```

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


title: LibGDX TexturePacker line problem

text:
# Question
Title: LibGDX TexturePacker line problem
I'm trying to use a TextureAtlas for all my textures for better performance. Every time my game starts all my tiles are packed into one texture atlas. I have put following code into my DesktopLauncher class that does that:

```
TexturePacker.Settings settings = new TexturePacker.Settings();
settings.maxWidth = 512;
settings.maxHeight = 512;
settings.filterMin = Texture.TextureFilter.Nearest;
settings.filterMag = Texture.TextureFilter.Nearest;
TexturePacker.process(settings,"blocks","texturePacks","blockPack");
TexturePacker.process(settings,"items","texturePacks","itemPack");

```

The atlas is loaded with the asset manager and I'm getting the texture region with

```
atlas.findRegion(..);

```

It all works, but I have came across an issue. The texture is not filling the whole space anymore. It should fill a 32 by 32 pixel area, but it doesn't. Here is a picture of whats happening:

There are fine blue lines between the tiles and I don't know what I'm doing wrong. My background is blue, if that's helpful information.

I have tried so far:

* Loading the texture region from the .png file directly -\> no blue lines, so it is an issue with the texture packer
* Changing the texture filters, but no one I have tried helped

Thanks in advance for any comments and answers!

# Answer
I don't know if it will helps you but, I had a similar problem. I resolve it by adding a border to my assets in "TexturePacker". You just have to open the "Advanced Settings"

And at the bottom, just add a border padding of 2 pixel as it recommended.

It should help you =)
> 2 votes

---
Tags: java, 2d, libgdx, tiles
---


# Question
Title: How can I make an object follow behind the player with respect to its rotation such that the player never faces it and always remains behind them?
Below is a sample of my current code. It doesn't even move the object at all. I thought I could first get the current forward y rotation of the player and then flip it to get the backward rotation and somehow add a little offset so it's not exactly where the player is, and then make the following object always be at that position. But I don't quite know how to do this.

```
public Transform player;
public Vector3 offset;
// Start is called before the first frame update
void Start()
{
    Vector3 playerPos = player.transform.position;
}

// Update is called once per frame
void Update()
{
    float targetAngle = player.eulerAngles.y - 180f;
    Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
    transform.position = moveDirection+offset;
}

```

# Answer
Your Vector3 reference to the player position in Start is not being updated, so it will always simply be the player’s original position. But it doesn't appear you are actually even using that reference to update the following transform.

This will do what you are asking for:

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

public class SimpleFollow : MonoBehaviour
{
    [SerializeField] private Transform player;
    [SerializeField] private Vector3  offset;

    void Update()
    {
        transform.position = player.position + player.TransformDirection(offset);
        transform.rotation = player.rotation;

    }
}

```

Here's an example of how to set this up -- for demo purposes the "Player" is the green Jeep, it will run around a Cinemachine Dolly Track:

The `SimpleFollow` component is attached to the red car. In the inspector, the Player Transform is assigned, as well as an offset. In this case, we want the follower to be behind the target, so we give it a negative z value:

And Violá:
> 1 votes

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