# Question
Title: Why when scaling it's never getting to 0.001 and how to scale in Update but with specific time duration without coroutine?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NaviManager : MonoBehaviour
{
    public enum TransitionState
    {
        None,
        MovingTowards,
        Transferring
    }

    public Transform player;
    public Transform carte;
    public Animation anim;
    public Transform destinationTransform;
    public float speed;
    public float distanceToStop;
    public float lerpTime;
    public UnlockCrate unlockCarte;

    private GameObject rig_f_middle;
    private Transform originTransform;
    private Vector3 originalScale;
    private float timer;
    private bool openonce = false;
    private TransitionState state = TransitionState.MovingTowards;
    private bool isScaling = false;

    void Start()
    {
        originalScale = transform.localScale;

        rig_f_middle = GameObject.Find("rig_f_middle.02.R");
    }

    void Update()
    {
        var dist = Vector3.Distance(carte.position, player.position);

        if (dist < 1.5f)
        {
            transform.localScale = Vector3.Lerp(transform.localScale, new Vector3(0.001f, 0.001f, 0.001f), Time.deltaTime * 1f);

            if (openonce == false)
            {
                anim.Play("Crate_Open");
                openonce = true;
            }

            switch (state)
            {
                case TransitionState.MovingTowards:
                    var v = rig_f_middle.transform.position - transform.position;
                    if (v.magnitude < 0.001f)
                    {
                        state = TransitionState.Transferring;
                        originTransform = rig_f_middle.transform;
                        timer = 0;
                        return;
                    }
                    Vector3 moveDir = v.normalized;
                    transform.position += moveDir * speed * Time.deltaTime;
                    break;

                case TransitionState.Transferring:
                    timer += Time.deltaTime;
                    this.transform.position = Vector3.Lerp(originTransform.position, destinationTransform.position, timer);
                    if (timer >= 1.0f)
                    {
                        this.transform.parent = destinationTransform;
                        state = TransitionState.None;
                        this.enabled = false;
                        return;
                    }
                    break;

                default:
                    this.enabled = false;
                    return;
            }
        }
    }
}

```

what I need to do is to scale the transform while it's moving to another object and become a child of that object. and I want that while the transform is started moving than to start smoothly slowly also to scale it down and when the object is reaching to its target the scaling also should be reaching the target 0.001

The problems I'm facing :

1. The scaling is never reaching 0.001f but close to it.
2. If I'm using coroutine for the scaling then it will not be smoothly flowing, the transform will wait in the end for the coroutine to end before it will be a child that is why I'm doing the scaling in the Update and not in a coroutine.
3. How can I make in the Update the scaling without coroutine that it will scale the time the transform is moving I mean that it will not scale too fast to 0.001 and too slow but will scale while it's moving?

# Answer
> 1 votes
If I understand your question correctly, then you want an object to move from A to B, and simultaneously interpolate its scale from the original scale to 1/1000th as it progresses on that move.

I would approach this problem as follows:

1. Calculate the current progression factor of the movement in form of a float between 0.0f (at the start) and 1.0f (at the end).
2. Use that value as the linear interpolation factor for the Lerp methods on both the scale and the position.

So first, how do we calculate the progression?

We simply track the time which has passed, and divide it by the time we want the animation to take in full:

```
public class ScaleMove : MonoBehaviour {

    public float duration = 2.9f; // time in seconds we want the action to take

    private float durationCompleted = 0.0f; // time completed

    void Update() {
         durationCompleted += Time.deltaTime;
         float progressionFactor = durationCompleted / duration;

    }

}

```

OK, now what we calculated this "progression factor" between 0 and 1, what do we do with it?

First we want to clamp it to an area between 0 and 1, so it doesn't get beyond 1.0f when the duration is over. And then we use it for the linear inerpolation of both size and position:

```
 progressionFactor = Mathf.Clamp01(progressionFactor);
 transform.position = Vector3.Lerp(startPosition, endPosition, progressionFactor);
 transform.scale = Vector3.Lerp(startScale, endScale, progressionFactor);

```

OK, but where do these start and end variables come from? And no, you can not take the start values from the `transform` of the object (at least not in Update) because those values change during the process (although you could substitute the end position by a reference to another Transform - that way the destination can move during the process and the script will adapt to that). I would recommend to make those private variables as well and set them by a public method which can be called by other scripts to initialize the movement action. That method (let's call it `Go`) could also takes care of managing whether or not the movement action is currently active. So it can be called again to repeat the action. The whole script would look something like this (untested code!):

```
public class ScaleMove : MonoBehaviour {

    public float duration = 1.0f; // time in seconds we want the action to take

    private float durationCompleted = 0.0f; // time completed
    private bool running = false;
    private Vector3 startPosition;
    private Vector3 endPosition;
    private Vector3 startScale;
    private Vector3 endScale;

    public void Go(Vector3 startPosition, Vector3 endPosition, float startScale, float endScale) {
         this.startPosition = startPosition;
         this.endPosition = endPosition;
         this.startScale = new Vector3(startScale, startScale, startScale);
         this.endScale = new Vector3(endcale, endScale, endScale);
         running = true;
         durationCompleted = 0f;
    }

    void Update() {
         if (running) {
             durationCompleted += Time.deltaTime;
             float progressionFactor = Mathf.Clamp01(durationCompleted / duration);
             transform.position = Vector3.Lerp(startPosition, endPosition, progressionFactor);
             transform.scale = Vector3.Lerp(startScale, endScale, progressionFactor);
             if (progressionFactor == 1.0f) {
                  running = false;
             }
         }
    }

}

```

---

"OK, it works, but it looks too linear for my taste. Can I add some easing to make it smoother?".

Sure, you can. A Unity beginner would now experiment with all kinds of math and weird abuse of Lerp in ways it's not supposed to be used to smooth the movement. Or perhaps bother with a 3rd party tweening library like DOTween.

But an experienced Unity developer will just add a public `AnimationCurve` variable to the script. This adds a handy curve-based editor to the inspector, allowing you to visually edit your time-to-progression function. You can then sample your animation curve with `Evaluate(progressionFactor);`

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


# Question
Title: locations being stored in map manager are inaccurate and ruining overlap validation
https://youtu.be/uKblVWHaqn0

I don't understand why sometimes the sections are deactivating like they should... and sometimes they are not. All I'm trying to do is make sure the maze pieces can't be placed on top of each other (unless I want them too... users will get a power up where their tiles "crush" underlying tiles, so I have to be mindful of that feature now.

MazeManger.cs

```
  public static void SectionPlaced(GameObject mazeTile)
    {
        SectionValidation[] children;
        children = mazeTile.GetComponentsInChildren<SectionValidation>();
        foreach (SectionValidation sectionValidation in children)
        {

            if (instance.placedSections.Contains(sectionValidation.gameObject.transform.position))
            {
                Debug.LogError("placed two sections in same spot");
            }
            else
            {
                instance.placedSections.Add(sectionValidation.gameObject.transform.position);
            }
        }
        EventManager.TriggerEvent("OnPlaceTile");
    }
}

```

BuildController.cs

```
  private void RotateGhost()
    {
        ghost.transform.Rotate(Vector3.up * 90.0f);
        currentRoty += 90.0f;
        if (currentRoty >= 360) currentRoty = 0.0f;

        SectionValidation[] children;
        children = ghost.GetComponentsInChildren<SectionValidation>(true);
        foreach (SectionValidation section in children)
        {
            section.gameObject.SetActive(true);
        }
        EventManager.TriggerEvent("OnMoveGhost");
    }

    private void PlaceMazeTile()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out RaycastHit hitInfo, 300f, mask))
        {
            if (!equippedTile) return;
            targetNode = hitInfo.transform.gameObject;

            GameObject placed = Instantiate(ghost, new Vector3(targetNode.transform.position.x, 0, targetNode.transform.position.z), Quaternion.Euler(0, currentRoty, 0));

            MazeManager.SectionPlaced(placed);

            if (ghost) Destroy(ghost);
        }
    }

    public void MoveGhost()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out RaycastHit hitInfo, 300f, mask))
        {
            if (!equippedTile) return;
            //only run the first time we hit a new node
            if (hitInfo.transform.gameObject == targetNode) return;
            targetNode = hitInfo.transform.gameObject;

            if (ghost) Destroy(ghost);
            ghost = Instantiate(equippedTile, new Vector3(hitInfo.transform.position.x, 0, hitInfo.transform.position.z), Quaternion.Euler(0, currentRoty, 0));
            EventManager.TriggerEvent("OnMoveGhost");

        }

    }

```

SectionValidation.cs This is placed on every 1x1 square section of the tile... like minos making up a tetromino

```
 private void OnMoveGhost()
    {
        if (!isGhost) return;

        if(MazeManager.instance.placedSections.Contains(this.gameObject.transform.position))
        {
            this.gameObject.SetActive(false);
        }
    }

```

# Answer
My advice would be to store only descreet adresses of tiles and not object positions directly. Convert them into integers before storing and checking.
> 1 votes

---
Tags: unity, c#, gimbal-lock, validation
---


# Question
Title: How to detect all vertices within collision Area?
Using collision detection algorithms such as MPR (Minkowski Portal Refinement), GJK (Gilbert–Johnson–Keerthi distance algorithm), you can calculate the penetration depth in the collision.

For 2 mesh colliding, how to know the volume of collision, or the intersection between them?

# Answer
> 1 votes
I am by no means a Blender or collision expert but I assume you have access to internal code of Blender https://github.com/blender/blender , I believe what you are trying to achieve needs calculations that happen during collision tests unless Blender exposes some api that allows you to get vertices of intersection. Getting these vertices should be possible during collision test of course.

* A - collider.
* B - collider.

You can use these vertices to calculate a volume of intersection but you will need "imaginary" vertices which are a product of intersection of \[A\] planes(collider's planes that are defined by its vertices) by edges between \[B\] vertices that penetrated this collider's \[A\] planes and the other collider \[B\] vertices that haven't penetrated these \[A\] planes.

On the first image you can see a pyramid created by intersection of a plane. This pyramid vertices is what you need to calculate the volume in this case.

---
Tags: collision-detection, physics, blender, bullet-physics
---


# Question
Title: How do I get this non-scaled image to look "sharp"?
I am using a 1920x1080 resolution. For the boxes at the bottom of the image posted below, the one on the left uses a 64x64 pixel sprite (which is the exact size it needs to be without scaling it up or down for) and the boxes on the right use a 128x128 pixel image which is twice the size of how many pixels represented in the scene.

I would expect that the smaller image that I do not scale looks more "crisp", while the larger image that I scale looks more blurry.

It is not what I get.

How do I get the smaller image to look "sharp"?

# Answer
> 1 votes
Bilinear Filtering + Pixel Snapping produces a sharp image for the 64x64.

---
Tags: unity
---


# Question
Title: Why is JumpHeight of 7f not visibly lifting Player off ground?
I'm using this code for Jump but when Space is hit, the character looks like they don't move. I played with JumpHeight and it turns out the jump **does** work; it just takes like 50f for it to finally visibly jump.

My Player's scale is 1 (1 x, 1 y, 1 z) so it's weird to me that a `Jump Height` of `7f` isn't enough to make the character look like it's jumping at all. Is there something possibly deeper going on here?

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

public class Jump : MonoBehaviour
{
    public float jumpHeight = 7f;
    public bool isGrounded;

    private Rigidbody rb;

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

    void Update()
    {
        if (isGrounded)
        {
            if (Input.GetKeyDown("space"))
            {
                rb.AddForce(Vector3.up * jumpHeight);
                print("Space");
            }
        }
    }

    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "Ground")
        {
            isGrounded = true;
            print("IsGround");
        }
    }

    void OnCollisionExit(Collision other)
    {
        if (other.gameObject.tag == "Ground")
        {
            print("NoGround");
            isGrounded = false;
        }
    }
}

```

Player just has a Rigidbody with XYZ Rotation Constraints, and a capsule collider with a bottom that is sitting slightly above the Mesh's feet.

# Answer
Just because you name a variable "height" does not make it a measure of height.

The way you're using this variable, it is not a height but a force:

```
rb.AddForce(Vector3.up * jumpHeight);

```

So instead of representing a 7 meter rise, it represents a 7 Newton nudge.

1 Newton is enough force to accelerate a 1 kg object by \\$1 \frac m {s^2}\\$. And you apply this force for just one frame, which might be something like one sixtieth of a second.

So if your object has a mass of one kilogram, then seven Newtons applied for one frame accelerates it to a speed of \\$7 \frac m {s^2} \cdot \frac 1 {60} s = \frac 7 {60} \frac m s = 0.11666... \frac m s\\$ upward.

In that same time, the default gravity of \\$-9.8 \frac m {s^2}\\$ would accelerate your object to a speed of \\$\frac {-9.8} {60} \frac m s = -0.16333... \frac m s\\$ downward. This is greater than your upward velocity, so you do not attain a positive launch velocity to ever leave the ground.

This is grade 9 physics, so it really should not be a surprise that 7 Newtons is not enough to lift your object.

If you want to parametrize your jump with a height, a good way to do that is to use `OnValidate` to transform that height parameter into the corresponding physics push you need to achieve that height.

We can use the formula for the height of a vertically-launched projectile at time \\$t\\$:

$$ h(t) = h\_0 + v\_0 t + \frac g 2 t^2$$

Setting the derivative to zero gets us a formula for the time until we reach the apex of the parabola:

$$h^\prime(t) = v\_0 + g t\\ 0 = v\_0 + g t^\*\\ -gt^\* = v\_0\\ t^\* = \frac {v\_0} {-g}$$

And substituting that into our original equation lets us solve for the initial velocity we need \\$v\_0\\$, assuming an initial height of 0:

$$h(t) = h\_0 + v\_0 t + \frac g 2 t^2\\ h(t^\*) = 0 + v\_0 t^\* + \frac g 2 {t^\*}^2\\ h(t^\*) = v\_0 \frac {v\_0} {-g} + \frac g 2 \frac {v\_0^2} {g^2}\\ 2g h(t^\*) = -2 v\_0^2 + v\_0^2 = -v\_0^2\\ -2g h(t^\*) = v\_0^2\\ \sqrt{-2g h(t^\*)} = v\_0 $$

We'll take just the principal root since we know we're looking for an upward (positive) launch velocity.

Now we can write:

```
// Now this really truly does represent a height.
public float jumpHeight = 7f;

[SerializeField, HideInInspector]
private float _jumpVelocity;

void OnValidate() {
    // Compute the launch velocity needed to attain the requested height.
    _jumpVelocity = Mathf.Sqrt(-2f * Physics.gravity.y * jumpHeight);
}

void Update()
{
    if (isGrounded && Input.GetButtonDown("Jump")) {
        // Apply an instantaneous impulse to reach our launch velocity from rest.
        rb.AddForce(Vector3.up * _jumpVelocity, ForceMode.VelocityChange);
    }
}

```
> 3 votes

---
Tags: unity, physics
---


# Question
Title: Floats vs. Ints for position and collision
So I’m writing a player class and using floats to store the positon and velocity (Vector2) as well as using it when drawing. When it comes to collision I get the player bounds using this code: `public Rectangle Bounds => new Rectangle((int)_pos.X, (int)_pos.Y, 12, 23);` to test it against solid blocks.

The issue comes when I apply gravity to the player and the player moves in \<1 increments per frame eg. first frame 0, second frame 0.25, etc. This causes the player to jitter when above a block due to him falling down little by little until the collision code (which uses ints) pushes it back up.

One solution I came across is to use the Bounds I calculated earlier for drawing, instead of using the position directly. However there is another problem (because the problems never stop coming)… Now the jitter occurs behind the scenes causing the ground detection to not work. How can I make the float positioning and int collision system work in harmony??

The player class' file:

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;

public class Player
{
    public Rectangle Bounds
        => new Rectangle((int)_pos.X, (int)_pos.Y, 16, 16);

    Vector2 _prevPos;
    Vector2 _pos;
    Vector2 _vel;

    World _world;

    const float GRAVITY = 500;
    const float MOVE_SPEED = 100;
    const float JUMP_FORCE = 275;
    const float MAX_FALL_SPEED = 350;

    public Player(Vector2 position)
    {
        _pos = position;
        _world = Main.World;
    }

    public void Update(float dt)
    {
        // Gravity
        _vel.Y += GRAVITY * dt;
        _vel.Y = MathHelper.Clamp(_vel.Y, -MAX_FALL_SPEED, MAX_FALL_SPEED);

        // Horizontal movement
        if (Input.IsKeyHeld(Keys.A))
            _vel.X = -MOVE_SPEED;
        else if (Input.IsKeyHeld(Keys.D))
            _vel.X = MOVE_SPEED;
        else
            _vel.X = 0f;

        // Jumping
        if (Input.IsKeyDown(Keys.Space))
            _vel.Y = -JUMP_FORCE;

        // Calculate position
        _prevPos = _pos;
        _pos += _vel * dt;

        HandleCollisions();

        System.Console.WriteLine("Velocity: {0}", _vel);
    }

    void HandleCollisions()
    {
        Rectangle bounds = Bounds;
        Rectangle prevBounds = new Rectangle((int)_prevPos.X, (int)_prevPos.Y, bounds.Width, bounds.Height);

        // Only check blocks around player
        int left = bounds.Left / TileData.TILE_SIZE;
        int right = bounds.Right / TileData.TILE_SIZE;
        int top = bounds.Top / TileData.TILE_SIZE;
        int bottom = bounds.Bottom / TileData.TILE_SIZE;

        for (int x = left; x <= right; x++)
        {
            for (int y = top; y <= bottom; y++)
            {
                // Not a solid block
                if (_world.GetBlock(x, y) == -1)
                    continue;

                Rectangle blockBounds = new Rectangle(x * TileData.TILE_SIZE, y * TileData.TILE_SIZE, TileData.TILE_SIZE, TileData.TILE_SIZE);

                // Resolve collision on x axis
                if (bounds.Intersects(blockBounds))
                {
                    // Previously to left of block
                    if (prevBounds.Right <= blockBounds.Left)
                    {
                        _pos.X = blockBounds.Left - bounds.Width;
                        _vel.X = 0f;
                    }
                    // Previoulsy to right of block
                    else if (prevBounds.Left >= blockBounds.Right)
                    {
                        _pos.X = blockBounds.Right;
                        _vel.X = 0f;
                    }
                }

                // Perform further collision using new bounds
                bounds = Bounds;

                // Resolve collision on y axis
                if (bounds.Intersects(blockBounds))
                {
                    // Previously above block
                    if (prevBounds.Bottom <= blockBounds.Top)
                    {
                        _pos.Y = blockBounds.Top - bounds.Height;
                        _vel.Y = 0f;

                        // _isGrounded = true; Doesn't work due to float and int mismatch
                    }
                    // Previoulsy below block
                    else if (prevBounds.Top >= blockBounds.Bottom)
                    {
                        _pos.Y = blockBounds.Bottom;
                        _vel.Y = 0f;
                    }
                }
            }
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.FillRectangle(Bounds, Color.White);
    }
}

```

# Answer
> 1 votes
You want to make it so that 'bottom' resolves into the next tile when there is a small increase in \_pos.Y, the same goes for 'right' and \_pos.X. This will also fix the edge case when you're exactly aligned within a tile ie. 'top' and 'bottom' will be within the same tile in that case.

So to calculate the left, right, top and bottom, do something like the following:

```
const int maxCells = 0x1000;            // Arbitrarily large. Beware float precision issues.
int pixels = maxCells * TileWidth;
int xLeft = (int)_pos.X / TileWidth;
int xRight = maxCells - (int)(pixels - _pos.X) / TileWidth;    // Aligns correctly within a tile in the edge case
int yTop = (int)_pos.Y / TileHeight;
int yBottom = maxCells - (int)(pixels - _pos.Y) / TileHeight;

```

Basically for 'bottom' and 'right' you're calculating the tile position from the other side and negating to give the desired result. The reason for subtracting from a constant is to keep everything in the positive range for the (int) cast.

With this you should be able to detect when 'bottom' enters the ground correctly.

---
Tags: 2d, xna, collision-detection, monogame
---


# Question
Title: Physics-based marble race: how can you minimize the gap between first and last?
I'm building a 2D sideview marble game, where they race down the track via gravity. The problem is that once one gets ahead of the others, it usually wins.

In racing games, they can address this by subtly changing the enemies' speed, or the AI's skill, or using power-ups, but I can't do that. I'm looking for obstacles I can add to address this.

The only things I can think of are:

* Gate - holds front players in place until a certain amount catch up, then releases
* Spring - launches marbles up or back, and they have to land just right to continue on the track

Are there any other methods I could use?

# Answer
> 13 votes
Add some destructible obstacles (e.g. balloons that get popped, glass that gets broken) that will slow down or even temporarily stop the first player to pass through it, but then is gone and won't affect the rest of the competitors.

The severity of the delay can be based on the current gap between first and last, so the race won't get too lopsided, and a close race won't get tipped the other way.

# Answer
> 4 votes
For real marbles, the first marble will not accelerate anymore because the force of friction will equal the force of gravity. How can the other marbles make their distance to number one smaller? If they are not accelerating anymore too, how will they ever be able to catch up? If the first marble "makes no mistake", it will surely finish first! A bit boring indeed. So what can we do to let the other marbles approach?

Giving the first marble extra obstacles is indeed possible, but unfair.

Instead, you should give the other marbles the opportunity to close in. You can consider giving them the possibility (though at higher risk!) to take an alternative parallel road, on which friction is less (but the chance of a dangerous encounter with whatever higher), so they can speed up and thereby closing in on the number one.

# Answer
> 3 votes
Included obstacles that have a certain chance per second to be passed. The longer the race goes on, the higher the chance to pass. For example you can have on you track poles that are sinking in the ground. The frequency of emerge is going to be lower the longer the races goes on. Or upwards propeller, with reduced strength later. You can include as gates that open when a certain amount reaches it like a scale that sinks slowly with only one on it but faster the more fall on it.

# Answer
> -1 votes
Add like bowls so like for example the first marble gets second place and second gets first and add some spinners, teleporters, etc. It would be fun and challenging!

---
Tags: physics, game-design, level-design
---


# Question
Title: Unity's LODs by distance to the orthographic camera
I'm trying to do something that I thought was simple, but seemingly it's not that easy.

I understand that Unity's LOD system works by refering to a percentage of screen size that objects occupy. That's not fit for the isometric 3D game I'm trying to make.

I'd like to have my LODs match the distance from the orthographic camera, as perceived from the viewer. Or, to put it otherwise, that the LODs are set according to their distance from the plane of the camera (and not the camera object itself) multiplied by the orthographic factor. Thus, when the ortho camera zooms out, all objects should swap LODs at the same time.

Is there a simple (or less simple) way to do that ?

Thanks

# Answer
> 1 votes
If you want to implement your own logic for choosing LOD levels, then you can do so via a script. Use the `ForceLOD(int level)` method of a LODGroup component to force it to the desired LOD level. Calling the method once will permanently set the LOD level of that gameObject to the stated level. So you only need to call it once per object when changing the camera zoom level.

(In case you want to re-enable the regular LOD logic, call `ForceLOD(-1)`.

# Answer
> 0 votes
Put this in update ( make sure camera is facing down, i.e. x rotation and y rotation to 90)

```
  var pos = this.transform.position;
  pos.y = this.GetComponent<Camera>().orthographicSize;
  this.transform.position = pos;

```

This will solve problem as it will tie camera y world position to orthographicSize, which in orthographic camera won't make a difference, as it doesn't consider camera y position! But the value of orthographicSize is approx to camera y position, then one can calulate vector3 distance between camera and object, now manually set active lod, i.e set active gameobject at whatever distance you like.

---
Tags: unity, level-of-detail
---


# Question
Title: Parts of the FBX getting flipped upon import from Blender to Unity
I am trying to import a race track into unity, which I have modeled in blender. The problem is some objects of the model are getting flipped, to be specific all the curbs on the sides of the race track are getting rotated except one. I have already applied transforms and the direction in Y up on export. Below are the images of what is happening exactly.

A link to the FBX file

# Answer
In Unity you can select all the curbs that are inverted, change scale Y value to -1, and then simply drag them down/up to the right height.
> 1 votes

---
Tags: unity, blender
---


# Question
Title: Prevent multiple input packets to authoritative server
I'm working on a simple game with an authoritative server. The player can move in 4 directions on a 2D board.

The game samples input at 30hz and sends it to the server. The server also runs at 30hz. One input packet contains basically the current player movement direction (None, Left Right..). When a packet is received, it is buffered and then processed during the next server tick.

It works well, however when a malicious client doubles it's sampling rate, the player speed will double as well and this allows for speed hacking. One solution would be to only process a single update packet every tick. However I am aware that packets do not arrive nicely spaced due to network lag.

Another solution I found is to keep a "allowedInputUpdatePackets" counter for each player and increasing it with every tick. (A Solution from the related question Network jitter, client input to server) This prevents the speedhacking while still allowing for some network jitter. But now the client can just stop sending packets, and after a while send multiple at once, resulting in a teleportation. (well almost) I can limit the maximum number of input updates per tick to e.g. 3-5 but this still allows the players to have a small speed boost every time they start moving.

I don't really see a solution to this problem. How to deal with malicious clients sending multiple input packets?

# Answer
Have clients stamp their input packets with the index of the 30 Hz input window to which they correspond.

On the server, keep a bitmask of windows for which you've received input from each client. You can use this as a circular buffer and keep recycling it so you don't need to store input flags going back to the dawn of time.

If you receive an input that's stamped too far in the past (or too far in the future!) discard it. A client who sends many inputs out of time may have too high a ping, so you may need to drop them entirely. A client sending messages from the future is likely a cheater, or a bug in your synchronization.

If you receive an input that's stamped for a window for which you already handled input from this client, that's either a duplicated packet (if the content is identical) or a cheating attempt, so you do not commit it to the game's simulated state.

This way, a cheater cannot have more inputs processed than 30 per second, same as the vanilla client.

This stamping can also be useful for rewinding to handle inputs received late or out of order.
> 2 votes

# Answer
Send a packet when the player stops or starts or changes direction. Record the direction (or lack of it) and calculate the movement on the server at the end of each tick. The client should check the server for the player position and not calculate it locally.

The player's client can then send an unlimited number of requests, it won't help them move any faster.
> 1 votes

---
Tags: networking, client-server, unity-networking
---


# Question
Title: Filing a dictionary through an enumerator 1 listing at a time
I have an issue with one of my functions. I have 5 arrays that get populated through a coroutine, if all parameters are met all of them get populated at the same time and that makes the game lag and sometimes crash on android devices. These are the two functions that do that

```
public void StartPopulating()
    {
        if (canPopulateAnimals())
        {
            StartCoroutine(GetTextures("LevelAnimals", PopulateArray));
        }

        if (canPopulateArch())
        {
            StartCoroutine(GetTextures("LevelArchitecture", PopulateArrayArch));
        }

        if (canPopulateTech())
        {
            StartCoroutine(GetTextures("LevelTechnology", PopulateArrayTech));
        }

        if (canPopulateVeh())
        {
            StartCoroutine(GetTextures("LevelVehicles", PopulateArrayVeh));
        }

        if (canPopulateNat())
        {
            StartCoroutine(GetTextures("LevelNature", PopulateArrayNat));
        }
    }

    public IEnumerator GetTextures(string _dirname,Action<Texture2D[]> onLoaded)
    {
        var fileNames = Directory.GetFiles(Application.persistentDataPath + "/" + _dirname, "*.jpg");
        Array.Sort(fileNames, (s1, s2) => Path.GetFileName(s1).CompareTo(Path.GetFileName(s2)));
        var textures = new Texture2D[fileNames.Length];
        for (int i = 0; i < fileNames.Length; i++)
        {
            UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture("file://" + fileNames[i]);

            yield return webRequest.SendWebRequest();
            if (webRequest.isNetworkError || webRequest.isHttpError)
            {
                Debug.Log(webRequest.error);
            }
            else
            {
                textures[i] = DownloadHandlerTexture.GetContent(webRequest);
                status++;
            }
            done = true;
        }
        onLoaded(textures);
    }

```

Now i was told that i could fill a dictionary instead and Fill that in StartPopulating() and then pass that as the parameter to GetTextures() and then go through the listings one at a time but to be honest i have no idea how to do that.

so initially i created a Dictionary

```
public Dictionary<string, Action<Texture2D[]>> sets;

```

But have no clue as to how to place that into the function and enumerator , Any help would be appreciated thank you!

# Answer
> 1 votes
You can wait for a coroutine finish by yielding it like this:

```
yield return StartCoroutine(SomeCoroutine());

```

In your case you could make the `StartPopulating()` method a coroutine and yield each of the population coroutines:

```
public IEnumerator StartPopulating()
{
    if (canPopulateAnimals())
    {
        yield return StartCoroutine(GetTextures("LevelAnimals", PopulateArray));
    }

    if (canPopulateArch())
    {
        yield return StartCoroutine(GetTextures("LevelArchitecture", PopulateArrayArch));
    }
}

```

# Answer
> 0 votes
To answer your question about Dictionary - you can use dictionary like this:

```
Dictionary<int,Sprite> niceDictionary = new Dictionary<int, Sprite>();
...
niceDictionary.Add(4654, someNiceSprite); // to add
...
mySprite = ((Sprite)niceDictionary[186]);  // to take out at a key 186
...
if (niceDictionary.ContainsKey(48) == true)  // to check if dictionary contains key 48
  {
    // something here
  }

```

note that you can use anything else instead of *int* or *Sprite* \- vectors, strings, objects etc.

Now to address your problem from other angle. Your problem is that several coroutines sometimes are started at once. So just make sure that only one is running. For example add if/else statements.

Also you might want to try to change *StartPopulating* into coroutine, and *GetTextures* into simple function, thus making sure that two *GetTextures* are not running at the same time. (In this case you would have to make sure that *StartPopulating* itself is not launched twice).

---
Tags: unity
---


# Question
Title: How does heavily constrained delaunay triangulation work?
In short: I'm trying to find an algorithm for performing a Delaunay triangulation of a heavily constrained polygon (for the purpose of pathfinding), with the understanding that most of the resulting triangles will be illegal (non-Delaunay) due to the constraints. Making the effort should still help reduce generation of long/thin triangles where possible.

I'm trying to understand how constrained Delaunay triangulation works, within the context of game maps where the available ground surface for navigation and pathing is defined by a polygon on a flat 2D plane. The polygon needs to be triangulated for use in pathfinding, such that moving from point A to point B passes through as few polygons as possible (so polygons need to be as large as possible).

I first looked into regular Delaunay triangulation, and there are multiple methods available, but they all assume a point cloud where the goal is to create ideal triangles without constraints.

Then I looked into constrained Delaunay triangulation, but there is very little available I could find beyond academic papers, and many of those simply perform a regular Delaunay triangulation, then cut triangles that intersect constraints and re-triangulate around them. This seems backwards and inefficient to me when literally ALL of the triangles I want to end up with will be constrained.

I saw a GDC video, where the Starcraft 2 devs talked about using constrained Delaunay triangulation, and you can kind of see it when you look at the pathing mesh in the Starcraft 2 editor (see below). However, very few of the generated triangles are legal, due to the number of constraints in the map layout. Still, I am assuming the Delaunay algorithm influenced the selection of points to triangulate, in order to get the best triangle coverage.

However, I can't find any further info on how this might work. How does one start with constraints, points connected by fixed lines, and then "fill in" the remaining lines to generate triangles that are a best-effort attempt to not be overly stretched or narrow?

Edit: Screenshot example from Starcraft 2 editor:

# Answer
> 5 votes
You're almost there. Once you have a delaunay triangulation of all the points (including constraint points) then:

foreach constraint edge:

1. Find all existing intersecting edges in the triangulation
2. 'Remove' these intersecting edges (see below)
3. Restore the delaunay triangulation

Regarding step 2), here is a description from Eric Nordeus that summarises this step:

*"The idea here is that all possible triangulations for a set of points can be found by systematically swapping the diagonal in each convex quadrilateral formed by a pair of triangles. So we will test all possible arrangements and will always find a triangulation which includes the constrained edge."*

The quadrilateral is formed from the 2 triangles that share the edge intersecting the constraint.

Get the 3 vertices for the triangle the intersecting edge is on and then get the 'opposite' edge of this edge (in the half edge data structure on the Habrador blog, the opposite edge has the same vertices, but they are swapped in order).

If these 4 points form a convex quad then you can flip the edge.

If the new flipped edge intersects the current constraint you push it back on the intersectingEdges list, otherwise you have a new edge that no longer intersects the constraint.

Here's a very simple diagram that hopefully helps illustrate the basic concept:

Here is some further reading, including better & more detailed descriptions on the above & some further experiments on constrained delaunay navmesh pathfinding by myself:

Eric Nordeus blog: constrained delaunay

Constrained Delaunay Navmesh someone posted on the Unity forums, complete with tutorial

My own blog post on using Constrained Delaunay Triangles as a navmesh including dynamic updating and pathfinding info

---
Tags: path-finding, navmesh, delaunay-triangulation
---


# Question
Title: regarding about game servers performance and security
I have two options to implement

* should my game server access the database directly
* should game server access database via api

would it be necessary to abstract the calls via api even though its located in same location

# Answer
You can do whichever one you want. Note that the second option is more work. Note that the database is *already* an API, so if you want to put your own API on top of that API you'd better have a good reason for it.

There *are* some good reasons, like if you want to make it possible to drastically change the database system later. If you use MySQL and the game server runs `select * from players where id = 123456;` when you log in, you can't change to MongoDB without updating the game server. If you use `http://localhost/players/123456` then you can update your API instead of updating the game server. But on the other hand, what's wrong with updating the game server? Maybe if you have 500 game servers and one API server then it's easier to update the API server.

If you don't have a reason to create a separate API, then don't. It's just extra work. If you think of a reason later, you can always create it at that time.
> 1 votes

# Answer
Technically, your gameserver *is already* an API used by clients as an intermediary to communicate with the database. API does not necessarily mean *web service* API.

A service-oriented architecture (SOA) has several advantages:

* When you have multiple consumers, then you can offer a static interface which is decoupled from the implementation details. This is useful when you want to change the way the service works internally without having to change all the consumers. But that's only useful when you have a lot of different consumers probably implemented in different technologies, so changing them all would be a lot of work.
* When you don't just have multiple consumers but also multiple data providers, then you can hide that behind one common API. For example, you can change your API implementation to draw data from not just one database but from multiple databases using different query languages, from other APIs or from filesystem resources. All while the consumers are unaware of where the data actually resides.
* You can control what the interface can and can not do, which is useful when you have untrusted consumers. For example, 3rd party services drawing data. Or perhaps you want the game client to do certain operations bypassing the gameserver entirely.

But note that all these advantages are moot when you only have one consumer. In that scenario there is really not much to gain from delegating the construction of SQL queries and parsing their results to a separate middleware. Anything the API does can be done by the gameserver directly.

But a SOA also has disadvantages:

* You create more complexity in your server setup. There is now one more piece of software to develop, deploy, host and maintain.
* You are creating another level of indirection causing additional latency and which might potentially become a bottleneck.
* Implementing and testing new features might become harder, because they require changes to the API.
> 0 votes

---
Tags: unity, client-server, databases, photon, api
---


# Question
Title: How to load level 1 when the cutscene ends?
I use timeline for creating an opening cutscene and I want to load the first level after the cutscene ends. So, I decided to use timeline signals. I created a signal emitter at the end of the cutscene and added `LoadGamePlay` script to the signal receiver component. The problem is that the function doesn't show up in the dropdown menu. I can just select "string name" and write the scene name in the inspector. But this doesn't help so level 1 cannot be loaded. I'm not sure what I'm doing wrong.

```
using UnityEngine;
using UnityEngine.SceneManagement;

public class LoadGamePlay : MonoBehaviour
{
   public string myScene = "";

   public void LoadLevel()
   {
      SceneManager.LoadScene(myScene);
   }
}

```

# Answer
> 0 votes
For solving this problem, I followed these steps:

1. Created an empty obejct.
2. Attached `LoadGamePlay` script to it as a component.
3. Wrote the name of the scene I wanted to load. In this case, it was "Level 1".
4. Dragged the game object into Signal Receiver in the inspector.
5. In the drop down menu, selected `LoadGamePlay` and then `LoadLevel()`.

***Note:** You can also drag the object into Signal Emitter's inspector* field.

---
Tags: unity, c#, loading, cutscene
---


# Question
Title: Which functions does an animation event call?
I have an animation with animation events in an imported .fbx file. I spent some hours creating a class with delegates so that I could trigger methods on any C# class I wanted.

Now I wonder if that is necessary? Which types and methods does the animation event delegate a call to? Does it search through all fields, properties, containers etc in the GameObject with the Animator to find matching function names?

I found out unity has released a read-only version of their repository on github so I will dive in there and see if I can find what happens.

Ok I *think* it looks through all MonoBehavior based off the GetComponents on the GameObject with the Animator.

# Answer
Animation events use the SendMessage system. That means that when an Animator component encounters an animation event, then it goes through all the components on the same gameObject looking for methods with a specific name and calls them.

So all you need is a script on said gameObject with a method with the right name and (optionally) the right parameter. As with all the other Unity event methods (like `Start` or `Update`), those don't necessarily need to be `public`.

How you then proceed from there is up to you. For example, you might want to handle the animation event in a different behavior on a different gameObject, so you could translate it into a C# event. Or perhaps you want to feed into the newer Unity Event System. Or you could feed it into some event handling system of your own.
> 1 votes

# Answer
My interpretation is that this code sets up the function calls: https://github.com/Unity-Technologies/UnityCsReference/blob/2019.4.0f1/Editor/Mono/Animation/AnimationWindow/AnimationWindowEventInspector.cs

In there it looks like the GameObject's GetComponents method is called. So that is probably how it works.

(I haven't read the entire context so not entirely sure but it sounds reasonable).
> 0 votes

---
Tags: unity
---


# Question
Title: What kind of information is important to share in the README.md of an Open Source game?
I want to write a very small and amateur game for toddlers and I want to make it open source.

I'm trying to figure out what I need to put in the README.md. A general approach could be:

> # Building a Peanut Butter and Jelly Sandwich
>
> ## Introduction
>
> In this project, you will build a Peanut Butter and Jelly Sandwich (PB&J).
>
> ## Getting Started
>
> Before you build a PB&J, you will need to:
> ***YOUR WORKING ENVIRONMENT HERE***
>
> ## Dependencies
>
> In order to build a PB&J, you will need the following supplies:
> ***YOUR INGREDIENTS HERE***
>
> ## Instructions
>
> Once you've collected your dependencies, to build your PB&J:
> ***YOUR ASSEMBLY INSTRUCTIONS HERE***
>
> ## Output
>
> ***YOUR EXPECTED OUTPUT HERE***

What would you expect to read for an Open Source game in order to be able to use it or contribute to it?

Would this be enough?

# Answer
> 1 votes
If you share an open source game poeple should be able to build it in their local dev environment. If you add installing and building isntructions and which tools you used will helpful. Also, if you used some private/secrets keys like api key etc. keep them secret don't include them project and indicate people you used this kind of apis/keys.

---
Tags: open-source, documentation
---


title: Gameobject doesn't move when hits wall

text:
# Question
Title: Gameobject doesn't move when hits wall
I have a gameobject that moves tile based(It moves 1 unity unit continously when I press button) But when ıt hits a wall, ıt doesn't move anymore

As you see, When It hits a wall, ıt doesn't move any direction anymore. Actually I found the problem but I couldn't find how to solve. The main problem is when cube hits wall, the distance between `nextPosition` and `transform.position` never will be \<0.0005f But Idk how to solve this.

Those are code that moves cube :

```
void MovePlayer()
{
    rb.MovePosition(Vector3.MoveTowards(transform.position, nextPosition, speed * Time.deltaTime));

    if (Input.GetKeyDown(KeyCode.W))
    {
        direction = Vector3.forward;
    }

    if (Input.GetKeyDown(KeyCode.S))
    {
        direction = Vector3.back;
    }

    if (Input.GetKeyDown(KeyCode.A))
    {
        direction = Vector3.left;
    }

    if (Input.GetKeyDown(KeyCode.D))
    {
        direction = Vector3.right;
    }

    if (Vector3.Distance(transform.position, nextPosition) < 0.0005f)
    {
        nextPosition = transform.position + direction;
    }
}

```

I tried to make with timer but failed

```
 float timer = 0.25f;
 float elapsed;
  private void Update()
{

    elapsed += Time.deltaTime;
}

    if(Vector3.Distance(transform.position, nextPosition) > 0.9f && elapsed > timer)
    {
        nextPosition = transform.position;
    }

```

I tried to make wtih collision. But this time when I try to make a lateral movement, ıt just moves 1 unit(1 tile) every time I pressed button.

```
float timer = 0.25f;
float elapsed;
bool elapsedBool;

 private void OnCollisionEnter(Collision collision)
{
    if(collision.gameObject.tag == "Wall")
    {

        elapsedBool = true;
        nextPosition = transform.position;
        direction = Vector3.zero;

    }
}

private void OnCollisionExit(Collision collision)
{
    if(collision.gameObject.tag == "Wall")
    {
        elapsedBool = false;
        elapsed = 0f;
    }
}

void ElapsedTime()
{
    if(elapsedBool == true)
    {
        elapsed += Time.deltaTime;
    }

}

```

# Answer
> 1 votes
Also you can avoid using walls altogether. Just keep track on which tile you are on , and if you reached outer tile, just don't move anymore. Lets say your starting point is bottom, right corner (0,0). so you could write something like this:

```
public enum MovementDirections{Right,Left,Up,Down};
MovementDirections currentDir;
void MovePlayer()
{
 ...
 //your code..
if (Input.GetKeyDown(KeyCode.A))
{
    direction = Vector3.forward;
    currentDir = MovementDirections.Left;
}
...

```

Then create and update int *horizTile* in your if statement:

```
int horizTile = 0;
if (Vector3.Distance(transform.position, nextPosition) < 0.0005f)
{
    nextPosition = transform.position + direction;
    if(currentDir == MovementDirections.Left){
       horizTile++;
      }
}

```

Now you can prevent going off-board by altering your keypress if statement:

```
if (Input.GetKeyDown(KeyCode.A) && horizTile < 11 )
{
    //your code..
}

```

Now left going button will do nothing if you on leftmost tiles..

Do similar for vertical tiles.

# Answer
> 0 votes
Seems that the problem that wall stops you arriving to *nextPosition* so distance to it is always slightly above 0.0005f. Am I correct?

If yes, your *nextPosition* is not reset even if you press the button, since if statement allows to reset it only if you have arrived. And you haven't. One solution would be to move wall little back.

Another solution would be to add another clause to your if statement - boolean *justHitWall*.

```
if (justHitWall || Vector3.Distance(transform.position, nextPosition) < 0.0005f)
{
... your code

```

now this if statement will allow you to reset *nextPosition*.

To set value to *justHitWall* you can use something like this:

```
bool justHitWall = false;
private void OnCollisionExit(Collision collision)
{
  if(collision.gameObject.tag == "Wall")
  {
    justHitWall = true;
  }
}

```

also you may want to reset it somewhere (to wait for another wall hit). Maybe in your if statement itself:

```
if (justHitWall || Vector3.Distance(transform.position, nextPosition) < 0.0005f)
{
    // your code..
    justHitWall = false;
}

```

---
Tags: unity
---


# Question
Title: Should delta be applied to every change per frame ? (e.g. acceleration, deceleration, jump, etc.?)
I have written a game based on another game's original physics. I have all the constants the original game used in the Sega Megadrive. For example:

```
float ACCELERATION = 0.03287f;
float DECELERATION = 0.4f;
float FRICTION     = ACCELERATION;
float TOP_SPEED    = 8f;

```

when the player presses the right button I do:

```
     if (rightPressed) {
       speed.x += ACCELERATION * delta; // accelerate

       if (speed.x >= TOP_SPEED * delta) {
             speed.x = TOP_SPEED * delta; // impose a top speed limit
       }
     }
     ...
     else { // user is not moving the player (left/right)
        speed.x -= Math.min(Math.abs(speed.x), FRICTION * delta) * Math.signum(speed.x);
     }

```

Several lines later:

```
    x += speed.x * delta;
    y += speed.y * delta ;

```

Is the delta here used correctly? Should it appear anywhere as I did or just the moment I set x and y? My understanding is that speed should accelerate according to delta as well.

Another problem I have is that, by using the original game constants, the character moves in slow motion (even if I only have delta at the moment of updating x and y) so I had to multiply all constants by 15000 in order to have normal playing speed. I expected I may have to multiply by 60 (because of the 60 frames per second of Sega Megadrive) but not by 15000.

# Answer
> 0 votes
Multiplying by a time delta is a form of integration.

You do it when you want to convert a linear *rate* of change over time into an increment, like to go from a speed (rate of change in position over time) to a displacement (amount of change to apply this frame).

So, this is correct:

```
speed.x += ACCELERATION * delta;

```

because we're taking a rate of change in speed over time (acceleration) and converting it to an incremental change in speed to apply this frame (a "delta v").

The same goes for these, where we convert a speed to a position increment:

```
x += speed.x * delta;
y += speed.y * delta ;

```

But this is **not correct**:

```
   if (speed.x >= TOP_SPEED * delta) {
         speed.x = TOP_SPEED * delta;

```

Here we're trying to compare/assign a speed to a speed. We are not integrating speed over a time interval, so it is not appropriate to multiply by `delta` here.

A useful trick is to use dimensional analysis. Keep track of the units on each term:

$$\require{cancel} position (m) += speed \left( \frac m s \right) \times \Delta time (s)\\ position (m) += \left( speed \times \Delta time \right) \left( \frac m {\cancel {s}} \times \cancel {s} \right)\\ position (m) += \left( speed \times \Delta time \right) (m)$$

We get the same unit (m) on both sides, and it makes sense to measure position in metres, so this little unit debugger confirms we're not doing anything too silly here.

If you repeat that with the top speed comparison above, you'll end up with m/s on the left side of the comparison (which makes sense for a speed), and just m on the right (which does not make sense for a speed!), giving you a signal that you're doing the wrong thing.

You also do not want to multiply by delta time if the change you're trying to apply is meant to be instantaneous, rather than integrated over the duration of the frame. Something like a jump or the launch of a projectile should apply an absolute change in velocity, not an acceleration over time. That way, you ensure you get consistent behaviour no matter the framerate, rather than getting short jumps when the game is running fast and long jumps when the game is chugging.

Strictly speaking, while integrating constant acceleration over time into a velocity increment is linear, and integrating constant velocity over time into a position increment is linear, integrating a constant acceleration into a changing velocity into a changing position is *non*-linear. Position will change quadratically. You can account for that if you want, though many games will accept this as a small integration error.

---
Tags: libgdx, physics, physics-engine
---


# Question
Title: Object reference not set to an instance of an object - Trying to set IK target to a GameObject but getting this error
I'm trying to make Player reach for `anchorObject` when Player is within `5f` of it.

However, when I hit Play, the `leftHandEffector.target` is always empty in the Inspector even though I think it should be populated by `anchorObject` based on the code.

How can I get the `leftHandEffector.target` set to `anchorObject` when code runs rather than getting the `Object reference not set to an instance of an object` error?

Thanks.

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

public class CheckAnchor : MonoBehaviour
{
    public GameObject anchorObject;
    public float distance = 5f;
    FullBodyBipedIK ik;

    void Update()
    {
        anchorObject = GameObject.FindWithTag("Anchor");

        if (Vector3.Distance(anchorObject.transform.position, this.transform.position) < distance)
        {
            print("Player is close to anchorObject");
        }
    }

    private void LateUpdate()
    {
        if (anchorObject != null)
        {
            ik.solver.leftHandEffector.target = anchorObject.transform;
        }
        else
        {
            print("Null");
        }
    }
}

```

# Answer
> 0 votes
For anyone who is trying to get Final IK working, here is what I did:

`FullBodyBipedIK ik;` at top of class. And then in Start, `ik = this.GetComponent<FullBodyBipedIK>();`

Then I am able to reference `ik.solver.leftHandEffector.position = targ.transform.position;` as desired and it works.

---
Tags: unity
---


# Question
Title: How to keep the value of angle between 0 and PI in box2d
In box2d, if i rotate an object multiple times in clockwise or anti clockwise direction, the value of angle ( body.getAngle() ) keeps on increasing. Like at start it is at 0 radians, then 1.57(90 deg), after complete roatation 6.28, then after second rotation 2\*6.28 . If a player keeps on rotating for too much time, angle value becomes really big.And for multiplayer games, sending big values uses more bytes.

How can i keep the value between 0 to +-3.14.Is there any solution in box2d Or Is it a good way of sending Sin(angle) to keep the value between -1 and 1 and doing reverse of sin at client side.

# Answer
> 1 votes
For better or worse, unbounded, non-normalized, angles are a property of the body's sweep. When calling `b2Body::GetAngle()`, that's what you're actually getting (see line 491).

If you want bounded, normalized angles, you can perform a modulo operation on this angle as has been suggested before in the comments.

Alternatively, you can also use the angle from the rotational portion of the body's transformation. Call `b2Body::GetTransform()` to get the transform and invoke `q.GetAngle()` on that. So if you have a pointer called `b` that's to a body you're interested in getting the normalized, bounded angle for, the code would look like:

```
b->GetTransform().q.GetAngle()

```

Between these two techniques, doing the modulo math on the sweep angle may be faster than the `std::atan2` that using the rotational portion of the transform requires (at least it has been in the bench-marking I've done). OTOH, doing the modulo math may also be less accurate.

Allowing the sweep angle to grow unbounded is a ticking time bomb of floating point math however. This angle's going to get less and less accurate much the way scrolling does for linear values.

To work around this growing imprecision, you may also want to normalize the sweep angle (by doing something like calling `b2Body::SetTransform`). Note however that this can cause odd behavior in joints like gear joints. There doesn't seem like an ideal solution to me. So just understand the issues/trade-offs.

---
Tags: box2d, angles
---


# Question
Title: How could I move an object, while respecting the gravity and other related physics in Unity?
How could I move an object, while respecting the gravity and other related physics in Unity?

I tried using the following approach:

```
    void FixedUpdate()
    {
        rigidBodyToMove.velocity = velocity;
    }

```

The problem with that approach is, for example, when the object falls from a height there is no acceleration of a fall. Also, I am sure that there are other physics related things which do not get respected with that approach.

So, I tried using this:

```
    void FixedUpdate()
    {
        rigidBodyToMove.AddForce(force);
    }

```

Now the problem with this approach is that, for example, when moving horizontally the object gets acceleration, while I want to just move it.

So, my question is basically how could I move an object (in my case a character, using an input from user), while respecting all the physics. I kind of want to have various physical forces which act on the object (gravity, wind, collisions...) but then I want my movement input to not act like a physical force but instead act like a constant velocity layered on top of all the physical movement.

**UPDATE**

There are four ways I know how to change the velocity (neither of them suits me, hence the reason for this question being posted):

**1** Change velocity each frame by setting it:

```
rigidBodyToMove.velocity = velocity;

```

It is not appropriate for me, because this way velocity stays constant and ignores physics accelerations (e.g. gravity acceleration during a fall).

**2** Change velocity each frame by incrementing it:

```
rigidBodyToMove.velocity += velocity;

```

This approach does not suit me either, because now I will add acceleration. Between the first increment and the second increment the `rigidBodyToMove.velocity` decreases and for sure needs to be incremented by some value to remain a constant movement force, but it may decrease or increase by a greater absolute value than the value of the `velocity`.

**3** Change the velocity only once. This does not work as well, because the next frame Unity will recompute velocity and I will lose my applied movement force. And also I am losing the physcis forces with this approach.

**4** Increment the velocity only once. Similar to 3, Unity will recompute the velocity and I will lose my movement force the next frame.

**UPDATE 2**

I tried to use the following approach : `rigidBodyToMove.MovePosition(rigidBodyToMove.position + velocity*Time.deltaTime);` The effect was exactly the same as in the **1** above. I.e. e.g. during a fall if I will start moving the fall acceleration disappears.

# Answer
> -1 votes
It seems like you want your player input to enact a constant **position change (MovePosition)** on the character while having the velocity still be affected by the **forces (AddForce)** of wind, gravity, and other things in the physics engine.
The player velocity, being a separate type of movement, can simply be hardcoded using `MovePosition(position + direction * Time.deltaTime)`. This function will not affect the existing velocity and acceleration and takes into account collisions in the same way that it normally would, although low framerates might cause clipping issues in certain circumstances if you're not using the right interpolation mode. Also, make sure that `direction` is only the direction given by the input (i.e. left or right) and not the 'velocity' of the rigid body.
In regards to your concerns about "putting all the physics features not into the physics engine", this approach wouldn't interfere with any other forces like setting the velocity would, so gravity, wind, and collisions should work as normal (see above). This is the normal way of moving an object a certain distance independent of velocity, and you can actually see an example on the official Unity documentation for MovePosition.

---
Tags: unity, physics, movement, physics-engine
---


# Question
Title: Does a texture mask need to be the same size as the base texture?
new to game development here. I am working with an experienced 3D modeler and following some tutorials on texture mapping. Apologies if this is not the appropriate question for this forum, but this is more about understanding what is happening under the hood than a specific code question.

How can a texture mask be a different size from the base texture of the mesh it's trying to cover? Let me provide these two images I took from Google as an example. Imagine the first image was 2x as large as the mask. In reality though, these images are also slightly different sizes. If they are not the same size, how would the mask know to scale up and mask the right part?

# Answer
> 1 votes
When a pixel shader samples a texture (regardless of what kind of texture), it usually does so using the UV coordinates interpolated between the UV coordinates of the vertices of the polygon. The result is a pair of floating point values between 0 and 1. It then uses those coordinates to get the color value of the texture at that point, with 0:0 being the upper left corner of the texture and 1:1 being the lower right. Those floating point coordinates are unlikely to match to one pixel exactly. Most of the time they will be somewhere between those pixels. Which is where different interpolation algorithms are being used.

That means it is not strictly necessary for textures used within the same material to all have the same resolution or even the same aspect ratio. Interpolation will take care of it. This can be useful when you run into GPU-RAM limits and need to prioritize where to save on texture resolution. Using lower resolutions for some texture types is often a lot less noticeable than for others. For example a high-resolution albedo texture can often get away with a much lower resolution normal map without much perceived loss in visual fidelity.

However, in a case like this, where one texture is directly applied to another, it would be very advisable to make them the same size regardless. It makes the design process a lot easier. The texture artist can overlay both textures in an image editor as separate layers and easily make sure they fit exactly. You are also avoiding artifacts at the border of the texture mask which come from the interpolation algorithms not getting the same results for both textures due to the different pixel resolutions. But that does of course depend on the artists workflow. If they are the kind of artist who never edits textures in 2d and only ever texture-paints on a 3d model, then they might never notice those problems.

---
Tags: textures, graphics
---


title: Creating meaningful and engaging quests

text:
# Question
Title: Creating meaningful and engaging quests
* Kill X number of monsters.
* Gather Y number of items (usually by killing X number of monsters).
* Deliver this NPC's package to this other NPC who is far far away.
* etc.

Yeah. These quests are easy to implement, easy to complete, but also very boring after the first few times. It's kind of disingenuous to call them quests really; they're more like chores or errands.

**What ideas for quests have people seen that were well designed, immersive, and rewarding? What specific things did the developers do that made it so?**

**What are some ideas you would use (or have used) to make quests more interesting?**

# Answer
**Edit: You know what, we're gonna do this again. It's two years later and I now have a different opinion. Read this segment first, then go to the next segment.**

Which of these questlines is more fun:

* "Please deliver this BOX to the DEMOLITIONS AGENT."
* "Thank you for the BOX. Please kill twenty DEMON COMMANDOS within five minutes."
* "Good job. I found this CRYSTAL. Please bring it to your COMMANDING OFFICER."

Alternatively:

* "We've gotten an infiltrator inside the demon base. Unfortunately the team sent to bring him explosives has failed. We need for you to get in there and deliver this BOX to him - he can blow the core sky-high and end this menace once and for all."
* "Thank God you're here! They've been assaulting me for the last hour, and I couldn't hold out much longer. It's going to take me five minutes to rig up these explosives, and before they go off, we need to clear out the area so they can't defuse the bomb. Get to it!"
* "I can't believe it. It didn't work. The core's shattered but the demons keep coming. And there's . . . what are these? Crystals? Look, we need to get this to command. You take it - you're a better fighter than I am. I'll . . . guard your back. Just get back safely, you hear me?"

They're the same quests, but one is far more exciting. A lot of it comes down to writing - don't tell them "go kill thirty rams", tell them "we need warm ramhide clothing for our army, and you're the only one we can spare to get it". It's a lot more motivating.

If you look at recent WoW quests, the vast majority are still "kill X", "acquire Y", or "speak to Z", but they're couched in terms and plotlines that make them more enjoyable.

**As of September 2012, here's my new thoughts:**

Everything I said above? It's correct. I still agree with it. But it's a surface issue, and it's not the deeper issue.

The deeper issue is that MMO quests are often not built around *showing* a story, they're built around *telling* a story. I sort of accidentally stumbled into an example of that above, to be honest, but imagine this instead:

* "Sir, we're cold, and we need clothes. Please go kill twenty rams and bring us their fleece."
* "Thank you, sir! We've discovered a cave of ice demons that have been freezing the land. Go kill them too."
* "Sweet, they're dead now? Okay, we found their leader. He's off in this cave instead. Go kill him now. Chop chop, get to it man."

Many MMO questlines behave like that. You're never given the illusion of free choice. Now, free choice itself is horribly expensive - I'm not going to say that every quest needs to be a branching quest, or anything. But even something as contrived as "stumbling across footprints in the snow", when in reality those footprints are either so common as to be unavoidable or literally spawning next to you every fifteen seconds, can give the player a sense of exploration and plot advancement that is sometimes sorely lacking.

If the player doesn't know *why* they're doing what they're doing, then the player won't be engaged with the quest. And maybe that's cool, maybe that's okay, but eventually it gets very, very old.

Unfortunately, players have been trained out of reading quest descriptions. What you've got to do now is to build it into the quest. One line: "It's freezing cold here. Please find us some warm clothes, and if you can, figure out what's causing this." Then send the player out to explore, and they shouldn't need to come back to town until they've got a backpack full of wool and a spear capped with an ice demon leader head.

All carefully constructed so that the player's guaranteed to meet all the important creatures, without, of course, realizing that they're being funneled down that path.
> 42 votes

# Answer
How about quests that are more than just a success or fail? **Give the player options**. Maybe they can betray their allies because they were tempted by the "power" of the dark side. Maybe add real time sensitive decisions. Sure you can do the quest later, but the town might be razed by then.

Let every decision, even indecision, have small impacts on the quest and its reward.
> 23 votes

# Answer
In order to design meaningful quests, the player must be able to do meaningful things. You must make the most of the design blocks that are available to you and give them meaning inside the context of your quests. Say, if the player only has access to (moving around), (inflicting damage) and (giving objects), try ascribing additional meaning to these actions. Of course, it all depends on the level of control you have over the creatures' behaviors in your game, but here are a few variation on a herding quest:

* Damage as behavioral trigger: In this quest, damage = pain. Herd some mobs toward a goal using pain as a motivator, but you must be careful to deal the right amount. Too little and the mobs will not fear/flee you, too much and you might kill them, diminish their value or turn them against you.
* Moving as a behavioral trigger: Mobs follow you when you're in front of them and above them. Find vantage points along the path from which to guide the mobs. Unfortunately, they're occupied by viciously territorial predators.
* Objects as a behavioral trigger: Mobs only follow you for a little while after you've fed them redsilk plums. Collect plums along the way from poisonous and animated redsilk trees.

However, there's not much more you can do with such primitives. If you have this opportunity, ask your team for more meaningful behavioral primitives that can be exploited in many ways. For instance:

* Creatures that react to what you're wearing or wielding.
* Creatures that react to existing spells - maybe an ailing salamander *wants* to be engulfed in flames to heal itself.
* Creatures that react to the type of terrain they're on.
* Creatures with medium-term memories that can combine several of the above stimuli.
* Etc.

Once you have more primitives, you'll find it much easier to create meaningful quests - by following the great pieces of advice on this page - since you'll have access to many more potentially meaningful actions.

Finally, if you're designing a game, think about these action primitives from the start. That's how you can create a synergy between the game story, the game content and the player's experience. It's much easier to design a meaningful world when you know in advance the kind of (meaningful) things the players will be able to do in it.
> 15 votes

# Answer
A key factor to making quests involving is to have a clear and logical motivation for the actions of a quest. Collecting 10 pieces of loot is pretty dang boring, but if it's for a very specific reason it's interesting. For example, I found grinding for cloth for the server-wide Gates of Ahn'Qiraj event in World of Warcraft way more engaging than similar quests, because there was a very specific game-wide goal that I was concretely helping to advance. Another good example I can remember from WoW is in the dwarven area where you have to collect some potion ingredients. But, when you hand them to the goblin you actually saw him use that potion to extract information from an enemy agent. All that work you did have a real narrative payoff in the form of a in-world skit.

Now, every quest does NOT need to be a "world changing event", and in fact that strategy can completely backfire on you. Many games go for a false sense of urgency in an attempt to make things engaging (You have to do this RIGHT NOW! unless you want to go sidequest for 20 hours... we'll wait...), and if a player notices the discrepancies it can shatter the suspension of disbelief. Nothing kills engagement more than directly lying to a player, because that leads to them to doubting the honesty of the game and it's designers.
> 12 votes

# Answer
Give every NPC an agenda. Whatever that NPC wants out of life: to bring in the crops so her family will eat during the winter or to beat down the agents of a particular megacorp, give the NPC the ability to create quests that further that agenda. And then make it *actually* further that agenda.

If she doesn't get enough crops brought in, the family can starve and disappear. After a time, a new family might move in, but make it matter that they're gone. Maybe when the farm is unoccupied, the players can't rest there to heal up or use the well or buy whatever they need from a farm, etc. The world will come alive as these things overlap.

If you're using a faction standing system, make it matter. Make NPCs react based on faction standings. Make it hard (but not impossible, usually) to gain standing in certain combinations of factions. Make faction standing valuable. NPCs will react with hostility to some and with affection to others. Even if they like you, they'll only give certain important quests to people they trust.

If you have crafting quests like make x units of y and take them to z, set up some kind of demand schedule and if z has received more units of y than they know what to do with, stop issuing that quest for a while. Even during a planetary siege, you only need so many warp-core-transducing-hydrospanners at the shipyard.

Do everything you can to make sure that if I start the same kind of character in the same location, and befriend the same group of NPCs, that I will still not get an identical set of quests.

Also, at every turn, try to imagine interesting content that does not involve fighting. Fighting is cool, but it's a crutch. It's too easy.

The world needs to seem alive and no amount of fancy writing is going to do it. Since you can't possibly author enough quests to make what I'm advising work, you need to develop a system that generates the quests for you and then sprinkle the developer-built quests in among them.
> 7 votes

# Answer
Treat quests as challenges to overcome rather than a job to complete. Have them require skill, thought, or some feat. For instance:

* A certain dungeon in the far east mountains is filled with a poisonous fume. Retrieve the rare flower from within for the sake of a medicinal potion within 30 minutes or risk certain doom.
* An evil king guards a powerful ring that he stole from a village elder. Find some way to steal it back whether by brute force, stealth, bribery, or...
* A pesky troll is blocking one of the exits out of town, demanding riddles be answered. Be a dear and go play his game until he's satisfied enough to leave.

Truly a quest can be a mini-game and a completely different genre at that. It can require stealth, puzzle solving, skillful playing, etc. I think the best quests are like that and not just busy work for the player to do to fill in content gaps. Some of Elder Scrolls IV: Oblivion's quests get creative like that, though there are the typical "kill X number of Y" or "Go clear X dungeon" quests.
> 4 votes

# Answer
The things I've seen that have made quests more engaging are not necessarily about the quests themselves, but more that you're doing multiple steps to achieve some big-picture goal. Or more specifically, that they are part of a longer quest chain that ends with some kind of payoff.

So the typical "engaging quest line" template looks something like this

* (optional) person in a highly visible area tells you a brief synopsis of something that you can do, and to talk to the quest giver who's probably off in some hard to get to area
* quest giver starts talking about something "big" that needs happening
* (repeat X times) small quests that are somehow related to the big something that needs happening, i.e. collecting parts for some machine/incantation/spell/potion, or collecting "signatures" from various other NPCs that also have some say in the story line, etc.
* major payoff for the player

The last quest can take many forms. If you can, give the player something permanent that's not just loot, like a new spell/ability, or access to a new area. Otherwise, try to make the quest result in something that happens specifically in the world for that quest. Some common examples from WoW are things like giving you the ability to see spirits in the world, or doing some kind of arena-style battle, or maybe even a world boss (who usually announces themselves across the entire zone).

That way the individual quests are mostly the simple ones that you outlined, but it's wrapped in some kind of fiction that makes sense, and is hopefully topped off with some kind of reward to make the effort feel worth it.
> 3 votes

# Answer
One of the fan favorites are Quests which involve a temporary companion. You either care or tend for them not to get hurt, or you fight your way through with them.

Somewhere in between the situation changes and calls for a different strategy or a different course of action. The helpless companion may turn out to lock himself away because he was greedy and careless. Or he may turn out to be an evil person, once posessing the sword of dark powers he turns on you. And the hardened fighter may find himself to be locked away in a cast of magic, slowly dying as you try to fight your way through to him.

These are the kind of setups that RPG fans enjoy the most in RPGs. Of course, it's 90% in the writing and if you have voice acting, you need top-notch writing AND top-notch voice-acting.

However, those kinds of quests tend to be a PITA to implement and debug and tend to have the most exploits. This is why most, and especially MMO RPGs, tend to go with the "fetch x items" quests.
> 3 votes

# Answer
The goal of the quests themselves isn't as important as:

* The quality of your core gameplay - if killing demons is viscerally fun, you won't mind a kinda stupid quests. If killing monsters is tedious, who cares how clever the quest is.
* Whether they require you do non-fun things like walk across the map and back, or whack a lot of trees until one drops a Job-Job fruit
* How clear and understandable they are - players don't like having to read through paragraphs of badly-written prose to understand what they have to do
> 3 votes

# Answer
In most action/adventure games there are a few basic goals.

* Collect items (like PACman)
* Reach Location (like Mario)
* kill enemies (like space invaders)

even a game like Gears of War is basically made up of just these goals - get to the extraction point while picking up weapons and ammo and killing locusts. But that's not what makes GoW exciting or fun - it's the obstacles that get in your way - environmental puzzles to solve, enemy behaviour to study and overcome, and the twitch skill you need to survive.

The problem with RPG quests, is that they often remove all the obstacles, puzzle solving and skill that GoW requires, so that all that's left is repetative grind. If the quest designer has the tools to make an interesting journey for the player, they can make something rewarding - if they are only able to define basic kill 10 rats scenarios, then the experience will be a chore.
> 2 votes

# Answer
While it doesn't survive multiplayer that well, riddle-answering quests are often fun.

Similarly, quests that require game-knowledge ("What word is carved on the top of the highest sandshoal mountain?") to answer can encourage exploration.
> 1 votes

# Answer
My favorite quest was the shawl quest in everquest. It was a series of quests and each step completed result in a better item. It was a lot of gather so many of this from killing monster x. Get your skill in jewelcrafting so high. It was a very long and tedious quest series but the reward was different than what could be gotten other ways. The quest could be done solo and that was a great part. I hate quests that I have to go begging for others to waste a lot of their time on the quest.
> 1 votes

# Answer
The Mud Dragonrealms occasionally has events that occur in the world. These are much more elaborate then generic quests and generally one shot(although they can span days), but are generally a big hit with the players. It gives players an opportunity to take part in something that won't happen again, and possibly gain some sort of items in the process that are rare or possibly even Unique. They occasionally have Events like this that are paid as well.

I see no reason why you couldn't do something similar in an MMO. You'd require more work in the art-asset department but it could still be done. Political plots, assassination and intrigue, invasions. There are lots of possibilities if you are willing to have a little bit of human supervision instead of having things run off automatically on their own.

Of course if you are feeling ambitious you could try to implement AI that would occasionally start Events on their own. There has been academic research in story manager AI(my game AI professor in school was crazy about the subject), and if you are interested in that approach let me know and I will try and dig up some of the articles he gave us on the subject.
> 1 votes

# Answer
Give player's activites that they would like to do even if it wasn't a quest, it didn't have any story and didn't have substantial reward. Otherwise you'll end up writing a twilight saga and rewarding player with 18 trillion gold coins but the quest is still "click the cookie 200 times" and player will still feel it was waste of time (unless they only play for the story, in which case the number of times to click the cookie should be like 1-3, not 200).

It's easy to use quests to trick players into playing the game beyond the point where the playing itself is interesting. Don't trick them to be bored.
> 0 votes

---
Tags: game-design, quests
---


# Question
Title: How to make a number show how much the player will lose
Bit new to python. I'm making a game where you click on a strawberry, then it reappears in a new location, and so on and so forth. But you see, every time the player misclicks, they lose Score equal to their Crapscore. Their Score is increased by 10 each time they click on the strawb, and the Crapscore is increased by 10 for each time they miss the strawb. But you see, what the on-screen Crapscore says does not equate to exactly how much the player will lose. I want the Crapscore on screen to equal the exact amount of Score they will lose if they misclick. I've tried messing around with different variables, but I can't get it to work.

Crapscore begins at 10, then if the player misclicks, crapscore is increased by 10. Then, the Score is decreased by Crapscore. What shows on screen works, but it's not a code error. I just can't figure out how to make it so that the player's Score is decreased EXACTLY by the player's current Crapscore. Below is the main code with the crapscore and score.

```
def on_mouse_down(pos):
    global crapscore
    global score
    global hit
    global crapscoreonscreen
    if strawberry.collidepoint(pos):
        score = score + 10
        place_strawberry()
        hit = True
    else:
        crapscore = crapscore + 20
        score = score - crapscore
        place_badshot()
        hit = False

```

# Answer
Swap the order of the variable changes. Minus it first, then increase it to show how exactly much the player will lose.

Here's the fixed else-clause:

```
else:
    score = score - crapscore
    crapscore = crapscore + 10
    place_badshot()
    hit = False

```
> 1 votes

---
Tags: python, pygame
---


# Question
Title: Unity2D: Character goes up and down during idle animation
My character is idling but his feet are changing position during the animation: it seems he's floating. I would like to have the character with his feet stuck.

Video to visualize the issue: https://vimeo.com/568057364

As you can see, the feet are going up and down. I've also tried to animate the collider in order to follow the feet, but that attempt didn't solve the issue.

# Answer
I had to change the pivot of the images to the bottom. It solved the problem. Before it was set to center.
> 0 votes

---
Tags: unity, animation
---


# Question
Title: Single Shadowmap for multiple point lights
I'm trying to render a scene using multiple point light casting shadows. Currently, If I have more than 1 point light, shadows are wrong.

I'm drawing to FBO with a depth cubemap attached to it and in geometry shader for every point light I emit vertices to each face of the cubemap.

```
//Geometry shader
out vec4 v_FragPos;

void main()
{
    for (int pl = 0; pl < u_PointLightsSize; ++pl)
    {
        for (int face = 0; face < 6; ++face)
        {
            gl_Layer = face;
            for (int i = 0; i < 3; ++i)
            {
                v_FragPos = gl_in[i].gl_Position;
                gl_Position = u_PointLights[pl].ViewProj[face] * v_FragPos;
                EmitVertex();
            }
            EndPrimitive();
        }
    }
}

```

u\_PointLights is an array of PointLight structs

```
struct PointLight
{
    mat4 ViewProj[6];
    vec3 Position;

    vec3 Ambient;
    vec3 Diffuse;
    vec3 Specular;
    float Distance;
};

```

And my fragment shader looks like this

```
in vec4 v_FragPos;
const float g_FarPlane = 10000.f;

void main()
{
    float minDistance = g_FarPlane;
    for (int i = 0; i < u_PointLightsSize; ++i)
    {
        float distance = length(v_FragPos.xyz - u_PointLights[i].Position);
        if (distance < minDistance)
            minDistance = distance;
    }
    minDistance /= g_FarPlane;
    gl_FragDepth = minDistance;
}

```

Can anyone tell what I'm doing wrong? If I use one point light, shadows are fine.

# Answer
Consider two point lights on either side of a wall. What you want is that the east light has a shadow caster to the west, and the west light has a shadow caster to the east.

If you try to render them into the same depth cube map simultaneously, you will end up with a depth map that thinks there's a wall casting shadows close to the light on *both* the east and west sides.

So this idea of rendering all of your lights into one cube map in a single pass is simply not feasible.

What you can do instead is this:

* For each light
    + Render a depth cube map from its perspective
    + Shade \[the relevant parts of\] your scene with that light and that cube map
    + Clear the cube map before proceeding to the next light

Since light is additive, you can sum it up in multiple passes like this, whether using forward or deferred rendering.
> 0 votes

---
Tags: rendering, graphics, shadow-mapping
---


# Question
Title: Tween a pop-up containing several buttons
I am developing a small game with Phaser 3. I want to make a container with several buttons, representing a pop-up dialog. The container needs to pop up on completing a task. When container pops up, I want all the buttons in the container to pop up as well.

I thought the best way would be to tween the container. But I cannot find any useful methods or implementations as such in the documentation.

How can I implement this tween?

# Answer
Consider a simple tween where you tween over the scale of something:

```
scene.tweens.add({
  targets: mycontainer,
  scale: {
    from: 0,
    to: 1,
   }
  duration: 1000,
  ease: 'Linear'
})

```

already right there you are close to something "popping" up. In general, you can be as simple as much as you can be general about what you want to do to every child gameobject. Scale is good for this, but possibly not as a elegant as you want. You can also always just run multiple tweens for each object with shared variables in their tween config.
> 1 votes

---
Tags: gui, html5, phaser, tweening
---


# Question
Title: Sprite transparency fails when rendered through shader
I am currently trying to implement a shader to a sprite of mine, but the transparency is completely removed when the texture goes through a Sample Texture 2D node.

The sprite under the Sample Texture 2D node.

The sprite Import settings

The sprite on a image viewer.

# Answer
> 1 votes
I had forgotten to connect the Alpha Channel to the Output of the Shader.

---
Tags: unity, 2d, shaders, sprites, transparency
---


title: Edge bleeding with opacity map

text:
# Question
Title: Edge bleeding with opacity map
I want to layer a grass texture with opacity over a dirt texture to form an edge. Both on the same model. But I'm getting edge bleeding from the opacity. I made both textures within Substance Designer (or any other texturing app). The 1x1 model is just a default plane made within Blender (or any other modelling app). You can see the bleeding in Substance Designer and in Unity. I did make a fast simple layered shader within Unity for both materials, just for reference. So I can apply both materials onto one mesh. I do think, that I understand why this is happening, but how do I fix it? Maybe there is a much better way to do this? I'm using URP.

Substance Designer (grass):

Within Unity:

I want to achieve something like this:

# Answer
Select the texture in your Assets folder, and change the Wrap Mode to Clamp.

This says that samples near the edge of the texture should clamp to the pixel on that edge, instead of repeat which wraps around to blend with the pixels from the opposite edge (good for when you want tiling effects, not so good for a single quat)
> 1 votes

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


# Question
Title: What is the logic behind of ScreenPointToRay?
I'm confused about ScreenPointToRay

Definition of this method says "Returns a ray from camera through a screen point". I'm trying to visualize it to understand how it works. But its not giving result I expected.

Those are code :

```
 public GameObject Cube;

private void FixedUpdate()
{

    Ray ray2 = Camera.main.ScreenPointToRay(Cube.transform.position);
    Debug.DrawLine(ray2.origin, ray2.origin +  ray2.direction * 250, Color.red);

}

```

That is screenshot

There are few things that blows my mind.

1)According to definition of this method, it should draw a line from camera through Vector3. But when I give a position of Cube as you see below. It's not drawing a line from camera through position of cube. Its drawing a line through a silly position as you see(the red ray). Why is that ? Why it's not drawing a line from camera through Cube ? 2) When I give `Input.mousePosition` as parameter it works correctly. What I mean is function is drawing a line from camera through my mouse cursor. It's working properly. Why is that ?

3. The last thing that blows my mind is that how this function works when my mouse cursor out of game window sceen ? How can Unity draw a line when my mouse is out of the boundary of game sceen ? What is reference for Unity ? How does Unity know where I point with my cursor even if I'm not in game scene ?

# Answer
> But when I give a position of Cube as you see below. It's not drawing a line from camera through position of cube.

That's a position in the **world**. That means it gives the number of *meters* east, up, and north, measured from the *world origin* point.

The function name tells you it works with positions on the ****screen****. That means it expects a number of *pixels* right and up, measured from the *bottom-left corner* of the game window.

If you want to convert a point in the world to a point on the screen, you can use Camera.WorldToScreenPoint.

> When I give Input.mousePosition as parameter it works correctly.

`Input.mousePosition` is a position on the screen. So it's already in the correct coordinate system for `Camera.ScreenPointToRay` to work with.

> How can Unity draw a line when my mouse is out of the boundary of game screen?

Because the projection math it's using does not care where the border of the window is. If the cursor is some number of pixels right and some number of pixels up from the center of the window, that corresponds to a ray with some particular yaw and pitch angle relative to the camera's facing direction. If those angles happen to be outside the camera's field of view, so be it. Every point on the infinite plane formed by extending your screen without limit in all directions still maps to a valid direction in the world, whether or not you can see that direction it in the rendered output.

In code it would be implemented something a bit like this (assuming a symmetric view frustum):

```
Ray ScreenToWorldPoint(Vector3 screenPos) {
     // Remap so (0, 0) is the center of the window,
     // and the edges are at -0.5 and +0.5.
     Vector2 relative = new Vector2(
          screenPos.x / Screen.width - 0.5f,
          screenPos.y / Screen.height - 0.5f
     );

     if (!orthographic) {
          // Angle in radians from the view axis
          // to the top plane of the view pyramid.
          float verticalAngle = 0.5f * Mathf.Deg2Rad * fieldOfView;

          // World space height of the view pyramid
          // measured at 1 m depth from the camera.
          float worldHeight = 2f * Mathf.Tan(verticalAngle);

          // Convert relative position to world units.
          Vector3 worldUnits = relative * worldHeight;
          worldUnits.x *= aspect;
          worldUnits.z = 1;

          // Rotate to match camera orientation.
          Vector3 direction = transform.rotation * worldUnits;

          // Output a ray from camera position, along this direction.
          return new Ray(transform.position, direction);
     } else {
          // Scale using half-height of camera.
          Vector3 worldUnits = relative * orthographicSize * 2f;
          worldUnits.x *= aspect;

          // Orient and position to match camera transform.
          Vector3 origin = transform.rotation * worldUnits;
          origin += transform.position;

          // Output a ray from this point, along camera's axis.
          return new Ray(origin, transform.forward);
     }
}

```
> 2 votes

---
Tags: unity, raycasting, mouse
---