# Question
Title: libGDX - How to rotate with a specific duration
I want to rotate my player to 90° for a specific duration. I know scene2d provides this, but I don't want to use it for my players.

With how much to rotate every frame, so after x seconds the rotation is finished? The game can run on different FPS also.

# Answer
You can use the timing system described here (this uses plain Java): https://stackoverflow.com/questions/23932887/libgdx-how-to-calculate-elapsed-time

Basically, set *startTime = System.currentTimeMillis()* before doing the rotation (but don't do it at the start of your program) and each time in your loop you can check to see if the amount of seconds, x, has passed.

Just do something like this (where x represents the seconds the object has to rotate):

```
    if((System.currentTimeMillis() - startTime)/1000 <= x) {
        //do rotation logic
    }

```

The division by a thousand converts it to seconds (1000 milliseconds in 1 second).
> 1 votes

# Answer
Do you want to do a basic rotation of an image or using an Animation of Textures? If it is just a rotation of an image, JoeBode1337's answer is a good one (with a while instead of the if). If you are looking for an Animation of Textures:

```
    rotateSheet = new Texture(Gdx.files.internal("playerRotation.png"));

    TextureRegion[][] tmp = TextureRegion.split(rotateSheet, rotateSheet.getWidth()/nbrOfColumnsInRotateSheet, rotateSheet.getHeight()/nbrOfRowsInRotateSheet);

    int nbrOfRotationPosition = nbrOfRowsInRotateSheet*nbrOfColumnsInRotateSheet;

    rotateFrames = new TextureRegion[nbrOfRotationPosition];
    int index = 0;
    for (int i = 0; i < nbrOfRowsInRotateSheet; i++) {
        for (int j = 0; j < nbrOfColumnsInRotateSheet; j++) {
            rotateFrames[index++] = tmp[i][j];
        }
    }

    rotateAnimation = new Animation((float)x/nbrOfRotationPosition, rotateFrames);
    spriteBatch = new SpriteBatch();
    stateTime = 0f;

    spriteBatch.begin();
    while((stateTime += Gdx.graphics.getDeltaTime()) < x){
      currentFrame = rotateAnimation.getKeyFrame(stateTime, true);
      spriteBatch.draw(currentFrame, player.posX, player.posY)
    }
    spriteBatch.end();

```

(Source: https://stackoverflow.com/questions/24724778/sprite-animation-libgdx-java)
> 1 votes

# Answer
Noticed that there wasn't an answer for this question so I am going to provide something simple that will work at any FPS as you suggested:

You could do something simple involving what angle you want to move to, that being 90°, and the duration you want to complete that movement in.

Taking the your designated time, say it's 3 seconds, you can convert that to frames using the given delta with `Gdx.graphics.getDeltaTime()` or the given delta in the render loop:

```
frameTime = timeInSeconds * (1 / Gdx.graphics.getDeltaTime());
// 3 * (60) = 120 ( which is how many frames over 3 seconds if your running at 60 fps)

```

Note, the getDeltaTime() and delta variable are 1 / fps, so you need to get the inverse of the delta to get the fps.

Then you can take your designated rotation amount, 90°, and find the amount it needs to rotate every frame:

```
degreesEveryLoop = 90 / frameTime;
// 90 / 120 = .75 (So if you wanted the player to move 90° over 3 seconds then you would need to move .75° every frame

```

Then you would just need to apply the amount to the player every frame
> 0 votes

---
Tags: java, libgdx, rotation
---


# Question
Title: Resize font when screen resizes desktop Libgdx
I create my font using the following code:

```
public BitmapFont createFont(FreeTypeFontGenerator ftfg, float dp)
{
    FreeTypeFontParameter f = new FreeTypeFontParameter();
    f.size = (int)(dp * Gdx.graphics.getDensity());
    f.color = Color.BLACK;
    f.minFilter = Texture.TextureFilter.Nearest;
    f.magFilter = Texture.TextureFilter.MipMapLinearNearest;
    ftfg.scaleForPixelHeight((int)(dp * Gdx.graphics.getDensity()));
    return ftfg.generateFont(f);
}

myFont = createFont(new FreeTypeFontGenerator(Gdx.files.internal("Fonts/Roboto-Black.ttf")), 16);

```

I have some labels to which I set the font using:

```
Label myLabel= new Label("Text", uiSkin);
        myLabel.setWrap(true);
        myLabel.getStyle().font = myFont;

```

How I create the stage:

```
Stage collectionStage = new Stage(new StretchViewport(Gdx.graphics.getWidth(), Gdx.graphics.getWidth()));

```

I also tried with no viewport or with other viewports.

In my resize method:

```
public void resize(int width, int height) {
    Viewport viewport = collectionStage.getViewport();
    viewport.update(width, height, false);
    viewport.apply();
}

```

The problem is that when I resize the window on Desktop the font gets distorted. Do I have to create another font in the `resize` method, and then for each label that I have, reassign the new font? Or should I do something else?

# Answer
> 0 votes
You need to use a Viewport which keeps the aspect ratio, for example a FillViewport. This will handle resizing for you, so you "only" need to manage the position. Also, I'd not scale the fonts. Create some fonts in different sizes at the beginning and use them.

# Answer
> 0 votes
Saw because of bump,

If it comes out blurry than you are most likely using a font that is too small for the resolution you are working at. What you'll want to do is to create a font at the size that is suggested for that font, and then scale it up afterwords.

Ex:

```
fontGenerator = new FreeTypeFontGenerator(Gdx.files.internal("Fonts/pixels.ttf"));
FreeTypeFontGenerator.FreeTypeFontParameter fontParameter;
fontParameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
fontParameter.size = 16;
fontParameter.color = Color.WHITE;
font = fontGenerator.generateFont(fontParameter);
// scale here
font.getData().setScale(/*however much you want to scale with*/);

```

Hope this helps.

---
Tags: java, libgdx, fonts, scene2d
---


# Question
Title: How to animate material alpha property via script?
I am creating Animator OverrideController via script based on current controller assigned to animator component. I have created animation curve for position and it works. When i try to animate transparency (material color alpha) it does not work (it does not make any effect, however in Animation Dopesheet there is yellow line: "Object name : Material.Color.a (Missing!)"). Did I fail to properly access this property or is it the consequence that creating animation via script works only for legacy animations with Animation component?

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

public class AnimationScript : MonoBehaviour {

    void Start()
    {
        AnimationClip clip = new AnimationClip();

        AnimationCurve curve = AnimationCurve.EaseInOut(0.0f, transform.position.x, 1.0f, transform.position.x);
        clip.SetCurve("", typeof(Transform), "localPosition.x", curve);

        curve = AnimationCurve.Linear(0.0f, 1.0f, 1.0f, 0.0f);
        clip.SetCurve("", typeof(Material), "_Color.a", curve);

        Animator anim = GetComponent<Animator>();
        AnimatorOverrideController animatorOverrideController = new AnimatorOverrideController(anim.runtimeAnimatorController);
        // "loop" is the name of clip not name of state
        animatorOverrideController["loop"] = clip;
        anim.runtimeAnimatorController = animatorOverrideController;
    }

}

```

However analogous code for legacy Animation component works:

```
void Start()
{
    Animation anim = GetComponent<Animation>();
    AnimationCurve curve;

    // create a new AnimationClip
    AnimationClip clip = new AnimationClip();
    clip.legacy = true;

    // update the clip to a change color
    curve = AnimationCurve.Linear(0.0f, 1.0f, 2.0f, 0.0f);
    clip.SetCurve("", typeof(Material), "_Color.a", curve);

    // now animate the GameObject
    anim.AddClip(clip, clip.name);
    anim.Play(clip.name);
}

```

What am I missing and why is first script not working?

# Answer
Take a look at this. I'm not sure 100% but if you create a 'Color' in code, that is taken the same as your original color, then set the curve value to that color each frame, and finally set this as the color for "\_Color". So perhaps change from using SetCurve to SetColor.

(Note: This doesn't answer your question exactly, but i still think it demonstrates a way to fix the problem):

ALSO: I expect you already have it set, but ensure the Material's Rendering Mode (in Inspector) is set to "Transparent" (it defaults as Opaque I think)

```
 Color transparentColor;

void Start(){
    Material mat = GetComponent<Renderer>().material;
    Color transparentColor = mat.color;
}

void Update(){
   // ... your code to set correct value to 'curve' here
   transparentColor.a = curve;

   mat.SetColor("_Color", transparentColor);

}

```
> 2 votes

---
Tags: unity
---


title: Rotate object around a dynamic object

text:
# Question
Title: Rotate object around a dynamic object
I'm trying to rotate an object (shield) around another object (player) like this question.

My use-case is this: I have players moving around a field. Their respective shield is orbiting in a constant velocity around them. If a "ball"-object (red) touches a player, he's dead. A player can use his shield to deflect a "ball". When a shield collides with the "ball", I want the player *and* shield be affected by the collision; thus the player should bounce back, keeping the shield at the same distance. Alternatively, on colliding with the "ball" the shield could act like a static object, either way would be okay with me.

I tried connecting the player to the shield via a b2DistanceJoint and

* applying a force to the shield (orthogonal to the line between center of player and center of shield i.e. if the shield is right of the player, the force acts downwards; if the shield is below the player, the force acts to the left). This made the shield rotate, but the player's position was affected by the rotation, which resulted in wobbling. Then, I tried changing the density of the shield to turn down the effect on the player, but then the collision with the "ball" was faulty as the ball had way more mass.
* "teleporting" the shield to the right position, but the collision with the "ball" was faulty afterwards (the ball "stuck" to the shield)

I know my whole setup is not a realistic physics model, so is there a way to achieve this behaviour in Box2D?

```
b2Body* body;
{
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(gameToWorld * x, gameToWorld * y);

    body = world.CreateBody(&bodyDef);

    // Define another box shape for our dynamic body.
    b2CircleShape circle;
    circle.m_p.Set(0, 0);
    circle.m_radius = gameToWorld * bodyRadius;

    // Define the dynamic body fixture.
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &circle;

    // Set the box density to be non-zero, so it will be dynamic.
    fixtureDef.density = 1;

    // Override the default friction.
    fixtureDef.friction = 0.0f;

    fixtureDef.restitution = 1.0f;

    // Add the shape to the body.
    body->CreateFixture(&fixtureDef);
}

b2Body* shield;
{
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(gameToWorld * x, gameToWorld * y);

    shield = world.CreateBody(&bodyDef);

    // Define another box shape for our dynamic body.
    b2PolygonShape rect;
    // HERE:
    rect.SetAsBox(1, 1, b2Vec2(0, 0), 45);

    // Define the dynamic body fixture.
    b2FixtureDef fixtureDef;
    fixtureDef.shape = ▭

    // Set the box density to be non-zero, so it will be dynamic.
    fixtureDef.density = 1;

    // Override the default friction.
    fixtureDef.friction = 0.0f;

    fixtureDef.restitution = 1.0f;

    // Add the shape to the body.
    shield->CreateFixture(&fixtureDef);
}

{
    b2DistanceJointDef def;
    def.bodyA = body;
    def.bodyB = shield;
    def.length = 0;

    world.CreateJoint(&def);
}

```

# Answer
Ah... easiest solution: have centre of mass for the shield lie outside it's shape, and have it coincide with the c.o.m. of the player body.

So in other words: model the shield shape away from (0,0,0).
> 1 votes

---
Tags: c++, box2d
---


title: Pygame OpenGL init causes an X Error

text:
# Question
Title: Pygame OpenGL init causes an X Error
`-> pygame.display.set_mode(display, HWSURFACE|OPENGL|DOUBLEBUF)
(Pdb) s
X Error of failed request: BadValue (integer parameter out of range for operation)
 Major opcode of failed request: 154 (GLX)
 Minor opcode of failed request: 3 (X_GLXCreateContext)
 Value in failed request: 0x0
 Serial number of failed request: 28
 Current serial number in output stream: 29`

I've seen one other answer to this question related to video drivers, but I feel like I've already run my game at least once with the same video drivers installed. I'd just like to know if there's another possible cause for this issue before I reinstall my drivers for the umpteenth time on Linux.

# Answer
> 0 votes
Never mind, I'm an idiot. I ran updates on Linux last night and I never restarted after updating since I don't have an automatic reboot set up on my computer yet. It's fixed, now, anyway.

---
Tags: opengl, pygame
---


title: Targeting with a ballistic gun

text:
# Question
Title: Targeting with a ballistic gun
I am trying to determine the gun elevation angle of a gun that fires ballistic projectiles.

For a target at a certain distance D, I will have to compute an angle that increases with D.

This relation ship is non-linear, by the way, because the projectile loses velocity as it travels, for starters, due to drag.

In the past, I have done this with a lookup table.... for a whole bunch of test firings, see where the projectile hits the ground.

But this only works if there is no delta in the elevation between gun and target.

A target that is on a hill top, will need adjustment for extra range. Whereas a target in a valley below, would mean a lower gun elevation.

This means that the table-lookup will break down, and a 2D table seems like a kludge.

What would be an effective way to compute this targeting? I know things also depend on nozzle-velocity and air-drag, but these will not vary (but drag will be non-zero.) Neither will I be modeling the wind.

Additional information:

This is for AI assisted targeting. NPC or player targets a point in the world. The algorithm will find the corresponding angle to hit the target.

Currently, I am using Bullet Physics, with a discretely stepped world.

# Answer
Per @DMGregory who posted a link to Oskar Stålberg's tweet.

By far the easiest solution is a 2D lookup table. Personally, I fill the table by sampling of test firings. I perform test firings by stepping through the range in steps of 0.02 radians, which is 1.146 degrees. For my purposes, this has been accurate enough.

It will be able to handle complex stuff like air drag that scales with the square of the velocity.

The only downside: if you tweak your simulation, you need to re compute the tables.
> 0 votes

# Answer
Is this meant for A.I., testing, or educational purposes? This may dictate if approximated methods are an option.

The Wikipedia page on projectile motion is really descriptive on the behavior of 2D ballistics. It includes a section for Angle required to hit coordinate (x,y) and another for when considering air resistance.

Is the speed at which the gun shoots constant? If not, applying a binary search on **v** while solving for **theta** might be viable.
> 1 votes

# Answer
Those are good references suggested by @Anko and @Rodrigo Borges I am a Mechanical Engineer, so for fun thought I would answer this question directly and save you sometime:

```
Given:
v_0: initial velocity of projectile
v_f: final velocity of projectile
g: gravity
a_d: acceleration due to drag (you state constant in your questions, simplifying the physics)
t: time
dt: differential of time
D: distance traveled
x_0: initial position in x
y_0: initial position in y
x_f: final position in x
y_f: final position in y

conservation of momentum:
m*v_f=m*v_0-g*m*t-m*a_d*t
divide by m:
v_f=v_0-g*t-a_d*t
Integrate to get position from velocity:
D=∫(v_0-g*t-a_d*t) dt
D=v_0*t-1/2*g*t^2-1/2*a_d*t^2+const.
distance, D, component wise use basic trigonometry:
y_f=v_0*t*sinθ - 1/2*g*t^2 - 1/2*a_d*t^2*sinθ + y_0
x_f=v_0*t*cosθ - 0 - 1/2*a_d*t^2*cosθ + x_0

```

Since you know the firing position (x\_0,y\_0) and the target position (x\_f,y\_f) You have two unknowns (t & θ) and two equations, so you can solve for both.
> 0 votes

---
Tags: physics, aiming
---


title: FBO lack of 3D Precision

text:
# Question
Title: FBO lack of 3D Precision
I am trying to do some post processing on my 3d scene. When I render directly to the screen edges are sharp, however when I render my scene to an offscreen FBO then render that to a texture that is then drawn to the screen I get strange Z-fighting around object edges. Any Idea how this can be resolved?

The resolution of the FBO image seems to be worse in some places too, however the FBO size is set to the window width and height.

Thanks!

Direct Rendering

FBO rendering

Depth Buffer Code

---

```
private int createDepthBufferAttachment(){
    depthTexture = Game.textureManager.genTexture();//call to GL11.glGenTextures()
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, depthTexture);
    GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL14.GL_DEPTH_COMPONENT16, Game.WIDTH, Game.HEIGHT, 0, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, (ByteBuffer) null);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
    GL32.glFramebufferTexture(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, depthTexture, 0);

    return depthTexture;
}

```

# Answer
Replace your `GL_DEPTH_COMPONENT16` with `GL_DEPTH_COMPONENT24` when creating the depth buffer texture.
> 1 votes

---
Tags: opengl, lwjgl, fbo
---


# Question
Title: How could I make the player's movement more responsive?
I am working on an Air Hockey game; I tried making the movement physics-based, by doing this:

```
using UnityEngine;

public class Player : MonoBehaviour
{
    private Rigidbody m_Rigidbody;

    private float HorizontalInput;
    private float VerticalInput;

    public float Speed = 1.0f;

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

    private void Update()
    {
        HorizontalInput = Input.GetAxisRaw("Horizontal");
        VerticalInput = Input.GetAxisRaw("Vertical");
    }

    private void FixedUpdate()
    {
        m_Rigidbody.AddForce(new Vector3(VerticalInput * Speed, 0.0f, -HorizontalInput * Speed),ForceMode.VelocityChange);
    }
}

```

and by adding a `PhysicsMaterial` to the `MeshCollider` attached to my player:

The movement should be quick and responsive, but it feels rather sloppy and *un*responsive; I also tried using `Input.GetAxisRaw(...)`, but the controls become quite clunky.
How can I improve on this? Is there a go-to way to do this type of movement in Unity?

(I would like the final version of the game to be played on controllers)

# Answer
> 2 votes
I know it's common advice to capture input in Update and defer acting on it until FixedUpdate, but I think this advice is overly simplistic. I don't follow it in my own games.

> **CAUTION:** This worked in Unity versions circa 2018 when this answer was written. It does not work in 2019 versions I've tried - it looks like they updated the engine to match the documentation instead of the other way around, breaking a useful latency-reduction trick. :(
>
> The numbered advice points later in the answer are still good practices to follow that will also have a dramatic impact on your responsiveness, so all is not lost.

Because FixedUpdate runs before Update each frame (when using the default game loop at least), **doing it this way forces at least one unnecessary frame of latency**:

```
| Frame 1                      | Frame 2                       |
| FixeUpdate...Update...Render | FixedUpdate...Update...Render |
                  ^                     ^                      ^
Input cached here |   Physics acts here |                      | Results Visible

```

If we check input in FixedUpdate, we can eliminate this unnecessary latency in any frames when FixedUpdate is called at least once (and we can adjust our FixedUpdate rate at or above our target framerate to ensure this is almost always the case):

```
| Frame 1                      |
| FixeUpdate...Update...Render |
   ^                           ^
   | Input & Physics           | Results Visible in the same frame

```

Now we need to be a bit cautious doing this, to ensure we don't miss or double-dip on instantaneous actions like Jumps. Here's one way we can do that:

```
bool hasHandledInputThisFrame = false;

void HandleInput(bool isFixedUpdate) {
    bool hadAlreadyHandled = hasHandledInputThisFrame;
    hasHandledInputThisFrame = isFixedUpdate;
    if(hadAlreadyHandled)
        return;

    /* Perform any instantaneous actions, using Time.fixedDeltaTime where necessary */
}

void FixedUpdate() {
    // If we're first at-bat, handle the input immediately and mark it already-handled.
    HandleInput(true);

    /* Apply any continuous physics changes here. */
}

void Update() {
    // Catch any missed input and reset the flag for next frame.
    HandleInput(false);
}

```

There, now we know we don't have unnecessary latency creeping in from the order of our update methods. What else can we do to improve responsiveness?

1. Since we're using physics-based movement, we can get an apparent stutter or judder in the motion due to the mismatch between the rendering framerate and the physics update. This can make the movement look low-performance.

Enabling interpolation on the Rigidbody smooths this out. Technically it can add a fraction of a physics step of latency because we're blending with a past state, but in my experience the smoothness it gives is even more important to the perception & feel of the controls - so long as your physics step isn't unusually long. As long as the player can see *some* effect of their recent input blending in through the interpolation, rather than no change at all or a stuttery inconsistent response, it still reduces perceived latency.

Once you do this, make sure you don't set the position/rotation via the transform component. Doing this effectively turns off interpolation and you're back to judder land. Route all transformation changes via the rigidbody to keep it smooth.
2. Separate your character's speed from their acceleration. Giving a high acceleration - and in particular, an even higher *deceleration* when stopping / changing direction, helps the controls feel snappy, even if the net movement speed stays where it is.

Here's a quick example I whipped up for my students a few weeks ago, that shows the basic idea. You can of course elaborate on this with custom acceleration curves, sliding effects, etc.

```
float maxAcceleration = 10f;
float maxDeceleration = 20f;
float maxSpeed = 10f;

void FixedUpdate() {
    // Handle instantaneous inputs exactly once per frame.
    HandleInput(true);

    // Now handle the continuous inputs like analog stick direction every step:

    // Capture analog stick direction (yes, this works fine in FixedUpdate).
    Vector3 analog = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    analog = Vector3.ClampMagnitude(analog, 1f);

    Vector2 targetVelocity = analog * maxSpeed;

    AccelerateToward(targetVelocity);
}

void AccelerateToward(Vector3 targetVelocity) {
    float limit = maxAcceleration;

    var deltaV = targetVelocity - body.velocity;

    // If we're stopping or reversing direction, use deceleration limit instead.
    if (Vector3.Dot(body.velocity, deltaV) < 0f)
        limit = maxDeceleration;

    // Compute an acceleration to use this frame, within our allowed limits.
    // (Since we're calling this in FixedUpdate, deltaTime gives our fixed timestep)
    var accel = deltaV / Time.deltaTime;
    accel = Vector2.ClampMagnitude(accel, limit);

    body.AddForce(accel, ForceMode.Acceleration);
}

```
3. Provide immediate feedback. The biggest ingredient in perceived latency is waiting to see evidence that the game heard you and is listening. If you use physics or animation-based movement, this could take several frames to become apparent. But if you can feed back some acknowledgement earlier, you tighten the loop between input & confirmation, and the controls feel instantly tighter even with no change in the underlying gameplay behaviour. Some forms this can take:

* rotating the character in the new direction (especially if they're a circle/capsule and this has no physics impacts anyway)

    If rotating the whole character is too extreme, you can try using IK to turn the character's head to look where they're going to move next, or rotate the thrust effects coming out of a spaceship....
    * throwing out particles like a skid effect when changing movement suddenly
    * sound effects (eg. a skid or heavier footfall when stopping/turning)

# Answer
> 0 votes
(1) Have you tried to increase Gravity in controller settings? (2) And I would take Time.deltatime into account, because the movement of player should be same relative to different framerates.

---
Tags: unity, control
---


# Question
Title: Sequencing / triggering messages based on conditions in an adventure game
I've been struggling conceptualizing the best way to make a level flow with dialog and help hints changing as you play etc.

Imagine your goal is to make this one screen 'adventure' game, where you leave your house for work, but along the way, you realize you cannot find your keys to leave the house (and drive to work), also the door handle has fallen out of your door again!

Here is the structure of the story as I see it and how I'd break it down for a game. But what data types would you use, and how would you send messages to the dialog classes telling them to display the lines of text in the correct timing and order?

```
items:
metal bar - floor
door handle - floor
keys - down sofa

bools:
hasFoundKeys
hasFoundDoorHandle
hasFoundBar

dialog flow:
1. "Well I better get to work now."
2. "Oh damn, I can't find my keys." [when trying door]
3. "Ooh whats this" [said when keys found / other items found]
4. "Oh great, the door handle fell out again" [when trying door, but now have keys]
5. "You need that little metal bar thing before the handle works" [trying door before using metal bar on door]
6. "I cant turn that with my bare hands" [trying door without handle but with metal bar in door]

```

The text at the bottom would be the exact string I'd want to pop up, the timing for each one is described in the \[\] brackets.

# Answer
The usual approach to this is to define the specific requirements / sequencing / outcomes of a particular puzzle piece in your game's data. That way you don't need custom code for every different permutation, and (especially if you have a large team), your level designers don't need to check out & modify files in the game's codebase when they just want to make a small change to one level.

Typically this will involve defining a "building block" data type for the kinds of actions your puzzles require, then chaining together several of these building blocks to express more complex behaviour.

In a case like yours, we can handle this with....

* an `InteractionStep` building block that represents one thing we want to do. That could include...

+ Checking for a required set of items (and aborting the action if they're not all available)
    + Giving the player a set of items (or taking them away)
    + Displaying a message
    + Triggering some other script
* an `InteractionChain` collection that represents a sequence of steps to perform in order (like checking if certain items are held before we take any subsequent actions)
* an `Interactable` component you can attach to your interactive objects. This can hold several Interaction Chains. When you trigger its interaction, it will try each chain in sequence until it finds one that it can successfully complete. We can use this to display a different message depending on which items you've collected.

Here's an example of what that can look like:

```
public class Interactable : MonoBehaviour {

    [System.Serializable]
    public enum Interaction {
        None,
        RequireItems,
        GiveItems,
        TakeItems
    }

    [System.Serializable]
    struct InteractionStep {
        public Interaction interaction;
        public string message;
        public Items[] items;
        public UnityEvent effect;

        public bool Attempt(Actor actor) {
            switch(interaction) {
            case Interaction.RequireItems:
                foreach(var item in items)
                    if(!actor.inventory.Contains(item)) return false;
                break;
            case Interaction.GiveItems:
                foreach(var item in items)
                    actor.inventory.Add(item);
                break;
            case Interaction.TakeItems:
                foreach(var item in items)
                    actor.inventory.Remove(item);
                break;
            }

            // If we got here, then this outcome is valid for this inventory state.
            // Show our message and perform our action, if any.
            if(!string.IsNullOrEmpty(message))
                actor.messageChannel.Display(message);
            if(effect != null)
                effect.Invoke();

            return true;
        }
    }

    [System.Serializable]
    public struct InteractionChain {
        public string name; // This just helps us keep track of what's what in the Inspector.
        public InteractionStep[] steps;
    }

    public InteractionChain[] interactions;

    public void Interact(Actor actor) {
        // Try each of our possible chains of interaction in order.
        foreach(var actionChain in interactions) {
            // Abort a chain of actions if its success criteria aren't met.
            var successful = true;
            foreach(var action in actionChain.steps) {
                successful = action.Attempt(actor);
                if(!successful)
                    break;
            }
            // If we've completed a successful action chain, stop.
            if(successful)
               break;
        }
    }
}

```

So, the scenario you showed could be set up in data a bit like this:

* on the Sofa Cushion Interactable:

+ name "Already Collected Keys"
        - Interaction: Require Items
        - Items: \[Keys\]
        - Message "Nothing more under here but lint"
    + name "Collect Keys"
        - Interaction: Give Items
        - Items: \[Keys\]
        - Message "Aha! My keys!"
* on the Door Interactable:

+ name "Solved"
        - Interaction: RequireItems
        - Items: \[Keys, MetalBar, DoorHandle\]
        - Message: "Now I can finally get to work!"
        - Effect: Door.Teleporter.Activate()
    + name "Need Handle"
        - Interaction: RequireItems
        - Items: \[Keys, MetalBar\]
        - Message: "I can't turn the bar with my bare hands."
    + name "Need Bar"
        - Interaction: RequireItems
        - Items: \[Keys, MetalBar\]
        - Message: "The handle won't go on without the little metal bar thing."
    + name "Have Keys"
        - Interaction: RequireItems
        - Items: \[Keys\]
        - Message: "Great, the handle fell off again. I'll have to find the pieces."
    + name "No Keys"
        - Message: "Oh damn, I can't find my keys!"

More sophisticated versions of this could include:

* additional state checks, where a step could check for the state of the door or other object too, rather than just work with the player's inventory
* state changes, where a step could modify the state of an object in the scene
* a "Use" verb, where the object can choose one of several different interaction chains based on what object was used on it.
* branching action chains, where you can trigger one sequence of events or another based on a condition. This can skip some redundant checks if you have several outcomes that share several pre-conditions (like all of the various messages above that trigger only once you've found your keys)

...but all of these follow the same basic structure of defining a building block for your actions, writing some code that walks over those building blocks checking/executing them, and wiring-up your objects with the appropriate sequences of building blocks
> 1 votes

---
Tags: unity, c#, software-engineering, data-structure
---


# Question
Title: How to efficiently store a large amount of data?
I am doing minecraft-like game. I have a limited world in size 32x16x32 chunk. Each chunk is a structure in which there is a three-dimensional array containing the values of the blocks located in it. Structures and arrays are so arranged that from world coordinates I can get the block number that I need and its value. When you start the program, the world is generated, but I need to save all these block values in a file so that when the world changes, these changes are saved after exiting the program. How do I need to organize the recording of data chunks to a file so that it is productive and economical in terms of memory occupied?

Let structures and arrays be declared as c \[32\] \[16\] \[32\] - structures int block\_id \[16\] \[16\] \[16\] - block id

# Answer
First of all, consider if it is actually necessary to break down the world into units of storage. 32x16x32x16x16x16 = 67,108,864 blocks. When each block is a 2 byte integer representing the type-ID, your world is just 128MB of data. All but the most low-end platforms should be able to handle that in-memory. But let's assume that you already tried that and came to the conclusion that you do need to persist and retrieve individual chunks to/from the filesystem.

---

You are usually going to load and store complete chunks, so the data of each chunk should stay together. Serializing and deserializing a fixed length array to a file is trivial, and stackoverflow should provide plenty of code examples. So I don't think I need to get into more detail here.

Now about how to organize the chunks into files.

**Quick and dirty solution: use the filesystem**. Save each chunk to one file with a naming convention which includes the coordinates of the chunk (like `world1_15_12_27.chunk`). Let the operating system worry about organizing and finding those files.

**More sophisticated solution: Use an embedded SQL database.** I made good experiences with SQLite for single-user applications, but there are alternatives available which might be worth looking at. Create a table `chunks` with the primary key `INTEGER x, INTEGER y, INTEGER z` and a non-key field `BLOB data` which contains the serialized data of the chunk. A "SQL by the book" solution would be to normalize the chunk data, but I would advise against it, because as previously said, your primary use-case is to save and load whole chunks. You are not going to query the database for individual blocks.

Using blobs also gives you the option to run your chunks through a stock compression algorithm like LZMA, DEFLATE, bzip etc. to reduce the size of your database. It might seem unintuitive, but compressing your chunks might in some cases actually improve loading times, because reading data from the filesystem can take longer than running it through a decompression algorithm.

**"Not Invented Here" syndrome solution:** Instead of using a ready-made embedded database, invent your own world file format which provides database-like indexing.

When you invent your own format, keep in mind that most storage media are optimized for reading and writing data in sequence. Seeking to a different position within a file is often a slow operation (this changed a bit with solid state drives, but it's still the case). So you should keep data which is usually loaded at once in continuous sections to avoid jumping around in the file.

A simple solution could be to start the file format with an index, followed by the chunks. The index lists all chunks contained in the file and where each chunk begins. Read the index first, then seek to that chunk within the file. When your chunks always have a fixed size (you are not using compression) and the whole world is generated at startup (as opposed to Minecraft which generates chunks on-demand), then the index might be unnecessary because you can simply calculate the starting position of each chunk and seek to it. `position = chunk_size * (x + y * 16 + z * 32)`

I'm looking forward to playing your game.
> 5 votes

# Answer
**What if you didn't actually need to store all of those blocks?**

I mean, you generate all of the world base at the start of the game from seed anyways, right? So, why not just store **changes** to the world that player made? I don't think that the amount of changes will ever be that huge it will perform worse than just straight loading **the whole world** from the disk.

So, when the changes are loaded, you just need to sequentially apply them to the memory that you store your world data in.

You might say, well, if, for example, changes are spread all over the world, it could cause lots of cache misses, since we apply changes one-by-one to (possibly) completely different parts of the computer memory.

And I think that this can easily be fixed by grouping the changes based on their memory location when saving.
> 1 votes

# Answer
Aside from databases and so on, one efficient choice is a multi-level storage bitmap. Basically, a storage bitmap uses a "1" bit for data, and a "0" bit for no-data. There's a balance depending on how barren your data is, but I think a balanced alternative would have 4-5 levels of bitmaps, resulting in a maximum of 8 MB of bitmaps assuming all cells are filled. The algorithm quickly becomes efficient as the data density drops. The break-even point would be at about 87.5% cell density, the lower your data, the more impressive it can become.

Basically, each chunk is stored on the disk only if it has at least 1 object. This bitmap requires up to 2kb of initial storage data. For each present chunk, break it in to 4x4x4 sub-chunks. This results in a 8 byte bitmap per present chunk.

From there, subdivide those in to 2x2x2 chunks, which requires a 1 byte bitmap each. Finally, one last byte bitmap describes which of the 8 cells are populated in this area. After that, it becomes trivial to just read the object data in sequential order.

If your data density is far less than 50%, one final super-chunk bitmap could cut down the chunk bitmap by adding a small 32 byte super-chunk bitmap for each 4x4x4 super-chunk that contains at least one chunk.

To read the data, simply start from the top bitmap and initialize a counter. For each bit, check if it's a 1, and if so, start processing the next smaller sub-area. After each bit, increment the counter by 1 to keep track of what you're doing. This is basically recursive logic, so some optimization is possible here.

To write the data, initialize a full set of empty maps for each possible level. Then, for each cell, set the appropriate present bits. Finally, output each of the non-zero bitmaps in order from the chunk/super-chunk level down to the cell level.

For performance, you can interleave the objects with the bitmaps; every time you output a 2x2x2 bitmap, output all of the objects in bit order. Other designs are possible too, but this is probably the most straightforward and facilitates sequential reads/writes for optimal saving/loading times.

As you can see, Minecraft itself uses a similar structure, a Region format. A region is a set of chunks stored by proximity, which in turn has a bunch of chunks in it. Note that they use separate files, but for a file the size you're talking about, one region is probably acceptable.
> 1 votes

---
Tags: c++, data-structure, databases
---


title: how to predict where a ball will land?

text:
# Question
Title: how to predict where a ball will land?
For a game of table tennis, the goal is that when the player hits the ball, the opponent (the computer) will move to the position where the ball will land in order to hit it back to the player.

Said another way, given a ball in 3D space with an XYZ vector for its velocity, how can I calculate an XYZ velocity vector that will result in the position of the computer player being approximately where the ball will land?

For my coordinate system is, Y is up/down, Z is left and right of the table, and X is forward backward (toward or away from the table)... So, I know I can simply just set the player's z velocity to match the ball's z velocity to match the direction, but I need to know how to find the appropriate X velocity so that the player will move backward / forward depending on how fast the ball is traveling + taking into account the height of the ball + gravity, etc.

**UPDATE**

Seeing that the initial ball height is different than the table and the floor, I did some research and learned that the quadratic formula was the best way to solve this problem...

```
serveToTable = (-ball.vel.y + Math.sqrt((ball.vel.y * ball.vel.y) - (4 * (gravity * 0.5) * (tableY - ball.pos.y)))) / gravity;
tableToFloor = (-ball.vel.y + Math.sqrt((ball.vel.y * ball.vel.y) - (4 * (gravity * 0.5) * (floorY - ball.pos.y)))) / gravity;
duration = serveToTable + tableToFloor;
player.pos.x = ball.pos.x + (ball.vel.x * duration);
player.pos.z = ball.pos.z + (ball.vel.z * duration);

```

This, kind of works.. But it seems the player will go to the ball 2-4 times and then miss the ball. Sometimes by quite a lot.

# Answer
> 1 votes
The problem here is that you can't really use actual physics to solve the problem, because game engines use "Simulated Physics" and not "Real-Time Physics", e.g. Unity uses PhysX for 3d physics.

Take a look in the Physics vs. PhysX section of the documentation to understand where the problem lies.

So, no matter how accurate your equations are, the physics engine will not respond in accordance with those equations.

IMHO the AI playing table tennis should "cheat" a bit to provide an entertaining experience for the real player. I'm a Unity user, so I'll give an indication of what I'd do (or where I'd start) with Unity.

* I'd add a vertical plane with a trigger collider on the side of the AI player. This vertical plane should be greater than the width of the table, wide enough and tall enough so as to detect all incoming shots. -This trigger should detect the moment the ball crosses it, when a ball is incoming. One of the techniques you can use to detect if the ball is incoming and not outgoing is to use a boolean, and set it after the ball gets hit by the player, and the reset after the ball is hit by the AI.
* The AI should always keep a reference to the ball's Transform.position. So, after an incoming ball is detected, the AI can have a response time depending on its "table-tennis" skills/experience, i.e. respond faster if the AI is skilled, or slower if not skilled.
* The AI may also have certain properties and behaviors relative to how often it just -randomly- misses the ball (the AI can get "tired" or "destructed"), whether to apply spin or not, how hard it hits and where, etc.
* After some experimentation you'll be able to get the AI to respond as you like it.

Of course the physics engine can still simulate the gravity of the ball etc, but since its not possible to conform to actual real-time physics, it can't be used for detecting the exact/physics-based ball movement, so I provided you with an alternative to use for your game.

# Answer
> 1 votes
When the ball leaves the user's paddle, copy the ball/game state and run the simulation forwards until you know where the ball will end up, but without updating the visual display of the ball. Then, you can create a spline that describes how the computer's paddle will move to meet the ball, and run the simulation while updating the screen.

This way you're guaranteed to reach the ball because the calculations during the real and fake run are identical, right down to floating point errors.

If you need to let the human win, a basic way would be to give the computer's paddle a maximum speed so that it can't reach the ball in time.

# Answer
> 0 votes
You need to split this into two components: the horizontal component and the vertical component. First you calculate the time it takes for the ball to hit the floor.

Using the law of motion:

```
t = 2 * v(i) / g

```

*v(i)* is the initial vertical velocity. *g* is the gravity constant.

Now you have the time the ball will travel before reaching the ground. Use the horizontal velocity component to calculate the target position:

```
pos(tar) = pos(start) + v(horizontal) * t

```

---
Tags: projectile-physics
---


title: Shader vs Working with Pixels

text:
# Question
Title: Shader vs Working with Pixels
I am working on 2d games only. In that context, when would I ever need to use a shader rather than simply manipulate the pixel-data of an image?

For example, I have an image of a car and I want to change the color of the car (leaving the rest as is).

1. Why should/shouldn't I iterate over the whole image and change a specific color to another?
2. Why should/shouldn't I use shaders for this instead?

# Answer
> 3 votes
There are a few benefits when using a shader:

**Speed**

The GPU is faster in manipulating pixels. Ofcourse you can 'preprocess' the texture and that will be fine. It is under the assumption that you only have a few bitmaps to process and you have the time to do this (for example right after a "choose your car color" screen).

**Flexibility**

So if you want to change the player's car only; sure, you can read the spritesheet, manipulate it and be done.

Now imagine you want to recolor the oppenent cars and have a busy city, this becomes unpractical. Or if you want to show a preview and the player can pick any color they want. Imagine you also want to include a variant with the car flashing white because it has hit an obstacle or something.

In that case you want to do this on the fly... which brings us to:

**Memory**

If you want to have multiple variants of the same car spritesheet with different colors, you would need to rebuild the bitmap for each variant. If the car is static (only shows 1 side and no animations) you could do this. If you have multiple variations and animations the bitmap becomes bigger- and all variations will grow quick. All these textures then have to be put in the GPUs memory.

Now I hear you say: "but there is plenty of memory on the GPU for my 2D game!", next is:

**Performance**

Closely related to the speed topic, above. But in the light of the memory one; the GPU performs at best in 2D games with as little drawcalls as possible. This is usually done by using sprite atlasses; it provides the GPU with all texture data in one go.

Having one bitmap and a few shader parameters simply provides better performance- while having much more flexibility.

**Maintainability**

If you have one sprite atlas for the car's movement, a variable is enough to set the color for any car in the city. If you're to build one sprite atlas to hold all car variations and the colors, you have to keep track of where the images in the sprite atlas were placed (if packed to maximize efficiency). This may be a minor thing; but it greatly helps if all assets are manipulated programmatically by properties and not the location in a bitmap.

**To conclude**

Having said all that; if your game has no complex scenes and is able to redraw the sprites at convenient times without impact- *there is no problem doing so*. Even so if you are able to combine many small variations in a sprite atlas you may be fine.

In the end: the shader route simply provides more *versatility* with best *performance* when scaling up- which is why most games go that route.

# Answer
> 1 votes
> Why should/shouldnt I iterate over the whole image and change a specific color to another?

Mainly because no matter how fast and efficent your algorithm is, It's still going to be *much, much slower* than just "changing the color to a new one" using shaders;

You would need to know *which* pixels need to be changed *and* change their value to the one we want; This becomes quite a fiddly and unnecessary process when dealing with large images.

> Why should/shouldnt I use shaders for this instead?

Reading/writing to an image is most of the times done on the CPU; Shaders, on the other hand, are user-defined programs that run on the GPU, which is *designed* to process and *shade* pixels using a *shading language* like GLSL or HLSL *very, very quickly*.

---
Tags: shaders, fragment-shader
---


# Question
Title: How can we compare the scores of 2 Facebook friends?
We need to show players their friends' scores during play.

In the past, Facebook worked perfectly for this. However, now they have depreciated their Graph API. How can we work around this?

We do not want to use the Google Play Store or Gamecenter for this, as people are hardly connected on these platforms. Also, of course making an ID for our own app is also not going to work for us.

# Answer
> 1 votes
You will have to create your own scoring system, or wait if Facebook comes up with a new one. There is no workaround for this.

---
Tags: facebook, leaderboards
---


# Question
Title: Find if one player is visible to the other
Two players (*p1* and *p2*) are standing in a 3D space, represented by points *(x1, y1, z1)* and *(x2, y2, z2)*. Player 2 is holding a light source, pointing in the direction given by a normalised vector *(xn, yn, zn)*. Given an angle *cone* (between 0 and 360) and a limiting distance *max* to which p2 can see with the light source, how can I determine if *p1* is visible to *p2*.

# Answer
> 0 votes
The dot product of two unit vectors gives you the cosine of the angle between them, so if your angle is measured from the central axis to the outside of the cone you can check it like this:

(or if you measure the angle edge-to-edge, half it first)

```
bool IsIlluminated (Vector3 source, Vector3 target, Vector3 lookDirection, float angleDegrees, float maxDistance) {

    // Compute vector from source to target.
    Vector3 offset = target - source;

    // Find its length, and fail if it's too long.
    float squareMagnitude = Dot(offset, offset);
    if(squareMagnitude > maxDistance * maxDistance)
        return false;

    // We're in range, so next check our direction.
    Vector3 normalized = offset / Sqrt(squareMagnitude);

    // This will give 1 if we're exactly in the look direction,
    // or less and less the further we're off-center
    float cosine = Dot(normalized, direction);

    // Test our computed cosine against the threshold cosine.
    return cosine >= Cos(angleDegrees * pi/180f);
}

```

# Answer
> 0 votes
After thinking about this for a while, I reduced the problem to 2d and came up with two conditions that have to be met for the object to be visible.

1\> p1 should be within the circle drawn with p2 as centre and max as radius and

2\> angle between the line joining p1 and p2, and n, should be less than half of the spread of light

In this picture, p1 is out of max and not within spread. p3 is within max but out of spread. p4 is within spread and within distance (thus visible). p5 is within spread but is out of max distance.

To satisfy 1: the distance between the vectors (straight line distance between p1 and p2 shown in dotted lines) should be less than max. For 2: angle between the line p1-p2 and n (shown as x in the picture) should be less than $\theta$/2.

---
Tags: 3d, vector, angles, line-of-sight, visibility-determination
---


# Question
Title: How to use grammars for procedural generation?
I am working on a system to procedural generate a house using this article. I am trying to understand how grammars work and are made I have found very little information on the topic online. From my understanding a grammar is like a rule and you can for example recursively iterate through a model and add a part to it based on that rule then repeat that process for each rule. Is this the right idea? If not can you provide a explanation or some resources explaining it? Also can grammars be made simply by using a few if statements to determine where something should be or is there something more special about them? I saw a video explaining how they use grammars to make compilers and parse the code. It looked like they were using a custom format to define the grammars. Is this something related and also is this the same type of grammar? If so what is the purpose of using a grammar in my case of procedural generating a house they seam like they are unrelated for generating the placement of rooms?

# Answer
Grammars might not be the best here. There's a fundamental difference between what compilers do and what you want to do: the applying direction.

When doing compiling, grammars are used to check whether the code is put together in a compilable way. Let's say your grammar has an `expression` rule, that can be basically anything from function calls to basic math and you want to implement for loops. The easiest method is to also define a `block` rule which consists of a list of expressions and use that for the loop. But you might also want to add single-expression (blockless or one-line) for loops (`for (a in b) doThis();`), then you also let the for loop be followed by an expression. Something like the following:

```
expression:
    // Stuff

multi-expression:
    [expression] ([multi-expression] || [nothing])

block:
    [opening bracket] [multi-expression] [closing bracket]

for-loop:
    [for-loop-body] ([block] || [expression])

```

Where `([a] || [b])` gives a choice between the two. This lets you create pseudo-recursion where rules can apply to arbitarily long token chains (like in the case of the multi-expression helper rule, which can apply to one, two or more expressions).

The problem with this is that using these to test strings is easy, but generating them is hard, since there are usually infinite possibilities. You might not want trees that take seconds to generate, because rng happened to choose the repeating path over and over again.

A good alternative as mentioned by Bram in the comments is to use an L-system. L-systems are very close to lexical grammars, but they are separated into stages. Each stage you take every letter, apply the production rules and output the new string. You can stop whenever you want, extract the constants and do what you want to do with them.

However, traditional L-systems usually only generate self-similar fractals. This can be solved by making some rules randomly choose between two or more options for the letters (like when doing trees for instance, a branch could either abruptly stop by generating a constant/terminator or branch further)
> 1 votes

---
Tags: algorithm, procedural-generation, procedural, content-generation
---


# Question
Title: Use of NetworkHash128 assetId in Custom Spawn Handler
I was learning Custom spawn handler on Unity Manual. It says before spawning we need to Register Spawn handler using `ClientScene.RegisterSpawnHandler(coinAssetId, SpawnCoin, UnSpawnCoin);` I understood SpawnCoin and UnSpawnCoin is Handler function that will be invoked on clients but what is the use of `coinAssetId`?

# Answer
> 0 votes
Answered on Unity Forum Answered by @goldbug Goldbug from Unity Forum

---
Tags: unity, unity-networking
---


# Question
Title: How to create a 32 bit red texture byte buffer
I want to make a red texture image buffer. Would anyone help me to make it in right way. I have tried following:

```
std::vector<BYTE> redTexture(w*h*4);
const auto stride = w * 4;
BYTE* buf = redTexture.data();

for (int i = 0; i < h; ++i)
{
  const auto redValue = Gdiplus::Color::Red;
  memcpy(buf, &redValue, stride);
  buf += stride;
}

```

# Answer
I have solved the issue by doing the following:

```
    CImage m_cImage;
    // create a test image
    m_cImage.Create(w, -h, 8 * 4); // 8 bpp * 4 channel
    auto hdc = m_cImage.GetDC();
    Gdiplus::Graphics graphics(hdc);

    // Create a SolidBrush object.
    Gdiplus::SolidBrush redBrush(Gdiplus::Color::Red);

    // Fill the rectangle.
    Gdiplus::Status status = graphics.FillRectangle(&redBrush, 0, 0, w, h);
    TRY_CONDITION(status == Gdiplus::Status::Ok);
    ....
    // Then saved the m_cImage.GetBits() to bmp file using Gdiplus::Bitmap
    // and my expected texture is found

```
> 0 votes

---
Tags: textures, image-processing
---


# Question
Title: How can I make an inventory system in Unity?
I am trying to make an inventory system for the game I'm working on with Unity and I want it to expand and compress whenever objects are added or removed. Is there any go-to way to do this?

# Answer
> 0 votes
A very basic version to get started (note I'm still learning myself, but I happen to be several weeks into making my own games with inventories).

You can make a class such as :

```
using UnityEngine;
using UnityEngine.UI;

public class InventoryItem : Monobehaviour
{
    // you could for example attach this script to any object that can be picked up,
    // and then assign values to these fields in the Unity Inspector...
    public string uiTextName;
    public int saleValue;
    public int magicValue;
    public int healthValue;

    public Player player; // note it is better to keep track of the player in a GameController type script which will hold all the game info such as the current player, when to spawn enemies, make game over, and other things. But for now you could add it here using inspector.

    // check if mouse is pressed on this object, find the player
    // and add the item to its inventory:
    private void OnMouseDown()
    {

         player.AddToInventory(item); // we make this class and function in a second, below.
         // ... perhaps here you can un-enable the MeshRenderer and Collider of this Item so it vanishes in the scene...
         MeshRenderer m = GetComponent<MeshRenderer>();
         Collider c = GetComponent<Collider>();
         if (m != null)
              m.enabled = false;
         if (c != null)
              c.enabled = false;
    }
}

```

then make a Player class:

```
using UnityEngine;
using System.Collections.Generic; // this is needed to make us of c# List<>

public class Player : Monobehaviour
{
     // declare a List<> to hold all InventoryItems we collect.
     List<InventoryItem> playersInventory = new List<InventoryItem>();

     // this public function can be called to 'Add' and 'InventoryItem' to the players inventory....
     public void AddItemToInventory(InventoryItem item)
     {
          playersInventory.Add(item);
     }

}

```

I hope that makes sense to you and helps you along the way, if you need more help let me know as I only recently have been learning this myself.

---
Tags: unity, inventory
---


# Question
Title: PhysicsJS on mobile devices: how to optimize for speed
I'm (physics n00b) developing a small animation (gamification) in a mobile HTML5 app (PhysicsJS, HTML5, Cordova, Ionic, JavaScript).

This animation is derived from Basket of verlet constraints. This basket has to carry a lot more bodies (circles).

I'm experiencing performance problems, even on decent hardware (iOS and Android, the latter is worse). The bodies move like if they were in an aquarium. If I remove the basket, the performance is way better, but not yet satisfactory.

**How can this be optimized** in a sense that users don't have the feeling of watching a film in slow-motion?

Are there any **tweaks to control the engine** to do less calculation?

Am I using the appropriate physics engine or **are there alternatives with significant better performance**?

Remark: on my MacBook in Chrome, there is absolutely no performance problem and all movements are very smooth -\> no aquarium.

# Answer
Theres the parameter maxIPF given to the Physics constructor, set that lower for a faster but less precise simulation. But this may be a question more of whole program optimization, do some profiling.
> 1 votes

# Answer
I've found following tweaks to gain performance on mobile devices:

* removed basket (too many bodies to calculate)
* don't render on each step (see code below)
* use `world.warp()` to scale time increments
* use a changed gravity factor
* call `world.pause()` and `world.unpause()` whenever appropriate (e.g. when canvas gets invisible due to a dialog covering it)

With following options the tweaks are set:

```
var options = {
    gravityFactor: 1,
    warp: 1,
    renderSteps: 1
};
if (ionic.Platform.isWebView()) {
    options = {
        gravityFactor: 2,
        warp: 5,
        renderSteps: 2
    };
}

```

**Don't render on each step**

```
// render on each step
var stepNo = 0;
world.on('step', function () {
    ++stepNo;
    if (stepNo % options.renderSteps === 0) {
        world.render();
    }
});

```

**use `world.warp()` to scale time increments**

```
world.warp(options.warp);

```

**use a changed gravity factor**

```
var GRAVITY = 0.0004; // standard gravity for PhysicsJS

var acceleration = Physics.behavior('constant-acceleration')
      .setAcceleration({x: 0, y: GRAVITY * options.gravityFactor});

world.add([acceleration]);

```

---

Please don't hesitate, share your experience and provide the solutions which work best for you!
> 0 votes

---
Tags: 2d, physics, javascript, performance
---


# Question
Title: How do I generate a sphere mesh in Unity?
I'm making a game and I need a way to generate a sphere mesh in Unity for whatever reason. It needs to be generated by code and not be a pre-made sphere or a sphere primitive as I need to edit in generation later on.

# Answer
So, I've already done some research on this and I've found an Icosphere generation code on Unity Wiki and it's not terribly hard to find, but still I wanted to share what I have on the matter, since it took me an afternoon or so to find and modify this.

First up is the Icosphere generation code, you just need to have this in a script but not on any objects. This is just a public API for your other scripts to use. I've added a few things here and there in this code but it's not too different from what the wiki page provides.

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

public static class IcoSphere
{
    private struct TriangleIndices
    {
        public int v1;
        public int v2;
        public int v3;

        public TriangleIndices(int v1, int v2, int v3)
        {
            this.v1 = v1;
            this.v2 = v2;
            this.v3 = v3;
        }
    }

    // return index of point in the middle of p1 and p2
    private static int getMiddlePoint(int p1, int p2, ref List<Vector3> vertices, ref Dictionary<long, int> cache, float radius)
    {
        // first check if we have it already
        bool firstIsSmaller = p1 < p2;
        long smallerIndex = firstIsSmaller ? p1 : p2;
        long greaterIndex = firstIsSmaller ? p2 : p1;
        long key = (smallerIndex << 32) + greaterIndex;

        int ret;
        if (cache.TryGetValue(key, out ret))
        {
            return ret;
        }

        // not in cache, calculate it
        Vector3 point1 = vertices[p1];
        Vector3 point2 = vertices[p2];
        Vector3 middle = new Vector3
        (
            (point1.x + point2.x) / 2f,
            (point1.y + point2.y) / 2f,
            (point1.z + point2.z) / 2f
        );

        // add vertex makes sure point is on unit sphere
        int i = vertices.Count;
        vertices.Add(middle.normalized * radius);

        // store it, return index
        cache.Add(key, i);

        return i;
    }

    public static void Create(GameObject gameObject)
    {
        MeshFilter filter = gameObject.GetComponent<MeshFilter>();
        Mesh mesh = filter.mesh;
        mesh.Clear();
        Vector3[] vertices = gameObject.GetComponent<MeshFilter>().mesh.vertices;
        List<Vector3> vertList = new List<Vector3>();
        Dictionary<long, int> middlePointIndexCache = new Dictionary<long, int>();
        int index = 0;

        int recursionLevel = 3;
        float radius = 1f;

        // create 12 vertices of a icosahedron
        float t = (1f + Mathf.Sqrt(5f)) / 2f;

        vertList.Add(new Vector3(-1f, t, 0f).normalized * radius);
        vertList.Add(new Vector3(1f, t, 0f).normalized * radius);
        vertList.Add(new Vector3(-1f, -t, 0f).normalized * radius);
        vertList.Add(new Vector3(1f, -t, 0f).normalized * radius);

        vertList.Add(new Vector3(0f, -1f, t).normalized * radius);
        vertList.Add(new Vector3(0f, 1f, t).normalized * radius);
        vertList.Add(new Vector3(0f, -1f, -t).normalized * radius);
        vertList.Add(new Vector3(0f, 1f, -t).normalized * radius);

        vertList.Add(new Vector3(t, 0f, -1f).normalized * radius);
        vertList.Add(new Vector3(t, 0f, 1f).normalized * radius);
        vertList.Add(new Vector3(-t, 0f, -1f).normalized * radius);
        vertList.Add(new Vector3(-t, 0f, 1f).normalized * radius);

        // create 20 triangles of the icosahedron
        List<TriangleIndices> faces = new List<TriangleIndices>();

        // 5 faces around point 0
        faces.Add(new TriangleIndices(0, 11, 5));
        faces.Add(new TriangleIndices(0, 5, 1));
        faces.Add(new TriangleIndices(0, 1, 7));
        faces.Add(new TriangleIndices(0, 7, 10));
        faces.Add(new TriangleIndices(0, 10, 11));

        // 5 adjacent faces
        faces.Add(new TriangleIndices(1, 5, 9));
        faces.Add(new TriangleIndices(5, 11, 4));
        faces.Add(new TriangleIndices(11, 10, 2));
        faces.Add(new TriangleIndices(10, 7, 6));
        faces.Add(new TriangleIndices(7, 1, 8));

        // 5 faces around point 3
        faces.Add(new TriangleIndices(3, 9, 4));
        faces.Add(new TriangleIndices(3, 4, 2));
        faces.Add(new TriangleIndices(3, 2, 6));
        faces.Add(new TriangleIndices(3, 6, 8));
        faces.Add(new TriangleIndices(3, 8, 9));

        // 5 adjacent faces
        faces.Add(new TriangleIndices(4, 9, 5));
        faces.Add(new TriangleIndices(2, 4, 11));
        faces.Add(new TriangleIndices(6, 2, 10));
        faces.Add(new TriangleIndices(8, 6, 7));
        faces.Add(new TriangleIndices(9, 8, 1));

        // refine triangles
        for (int i = 0; i < recursionLevel; i++)
        {
            List<TriangleIndices> faces2 = new List<TriangleIndices>();
            foreach (var tri in faces)
            {
                // replace triangle by 4 triangles
                int a = getMiddlePoint(tri.v1, tri.v2, ref vertList, ref middlePointIndexCache, radius);
                int b = getMiddlePoint(tri.v2, tri.v3, ref vertList, ref middlePointIndexCache, radius);
                int c = getMiddlePoint(tri.v3, tri.v1, ref vertList, ref middlePointIndexCache, radius);

                faces2.Add(new TriangleIndices(tri.v1, a, c));
                faces2.Add(new TriangleIndices(tri.v2, b, a));
                faces2.Add(new TriangleIndices(tri.v3, c, b));
                faces2.Add(new TriangleIndices(a, b, c));
            }
            faces = faces2;
        }

        mesh.vertices = vertList.ToArray();

        List<int> triList = new List<int>();
        for (int i = 0; i < faces.Count; i++)
        {
            triList.Add(faces[i].v1);
            triList.Add(faces[i].v2);
            triList.Add(faces[i].v3);
        }
        mesh.triangles = triList.ToArray();
        mesh.uv = new Vector2[vertices.Length];

        Vector3[] normales = new Vector3[vertList.Count];
        for (int i = 0; i < normales.Length; i++)
            normales[i] = vertList[i].normalized;

        mesh.normals = normales;

        mesh.RecalculateBounds();
        mesh.RecalculateTangents();
        mesh.RecalculateNormals();
        //mesh.Optimize();
    }
}

```

Now we create the generator script. The method that I provide is by no means the best way to do this (especially since Unity itself complains that generating meshes in the editor will lead to memory leaks). Anyway, here's the generator script:

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

public class GeneratePlanet : MonoBehaviour
{
    public Material planetMaterial = ;
    public float planetSize = 1f;
    GameObject planet;
    Mesh planetMesh;
    Vector3[] planetVertices;
    int[] planetTriangles;
    MeshRenderer planetMeshRenderer;
    MeshFilter planetMeshFilter;
    MeshCollider planetMeshCollider;

    public void CreatePlanet()
    {
        CreatePlanetGameObject();
        //do whatever else you need to do with the sphere mesh
        RecalculateMesh();
    }

    void CreatePlanetGameObject()
    {
        planet = new GameObject();
        planetMeshFilter = planet.AddComponent<MeshFilter>();
        planetMesh = planetMeshFilter.mesh;
        planetMeshRenderer = planet.AddComponent<MeshRenderer>();
        //need to set the material up top
        planetMeshRenderer.material = planetMaterial;
        planet.transform.localScale = new Vector3(planetSize, planetSize, planetSize);
        IcoSphere.Create(planet);
    }

    void RecalculateMesh()
    {
        planetMesh.RecalculateBounds();
        planetMesh.RecalculateTangents();
        planetMesh.RecalculateNormals();
    }
}

```

Now at this point, you can just put the `CreatePlanet()` method inside the `Start()` method and slap this script on a game object, and you'll have a "planet" that is made in the Icosphere style. This differs greatly from the Unity's own primitive, which is made by six faces that are bent until they make a sphere (essentially a modified cube).

Anyway, if you want to use this as I do, then you can use this next script to create a button on the object itself so that you can create it in the editor (again, not recommended by the Unity editor itself):

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

[CustomEditor(typeof(GeneratePlanet))]
public class GeneratePlanetEditor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        GeneratePlanet myScript = (GeneratePlanet)target;
        if (GUILayout.Button("Create Planet"))
        {
            myScript.CreatePlanet();
        }
    }
}

```

The end result should be a good Icosphere with the shown vertices. (The vertex spheres are just drawn by gizmos on a simple loop).

The advantage of Icosphere is that its vertices are almost equidistant from each other and they're all almost the same distance from the center of the sphere. The disadvantage is that, if you want to make a more detailed sphere, you need quite a lot more vertices and that's going to be a bigger performance hit than some other methods.

Hope y'all find this as useful as I did!
> 7 votes

---
Tags: unity, procedural-generation, 3d-meshes
---


# Question
Title: vuforia unity how to detect that we have " lost track of" an object
I'm working on a vuforia project and would like to be aware when vuforia can no longer detect the object in unity. Is there an easy way to write a script that is executed opon loosing track of an object for a given time?

# Answer
You have by default the "DefaultTrackableEventHandler" attached to your Target. This script has a function called "OnTrackingLost()" which is doing exactly what you want to do. Maybe this functionality wasn't available as you asked this question.
> 1 votes

# Answer
That's correct, one way to do that is to have a script like the below attached to each Image Tracker object

```
using UnityEngine;
using Vuforia;
//Attach to the image tracker
public class ChildObjectsActivator : MonoBehaviour, ITrackableEventHandler
{
    private TrackableBehaviour trackableBehaviour;
    void Start()
    {
        trackableBehaviour = GetComponent<TrackableBehaviour>();
        if (trackableBehaviour)
            trackableBehaviour.RegisterTrackableEventHandler(this);
    }

    public void OnTrackableStateChanged(
      TrackableBehaviour.Status previousStatus,
      TrackableBehaviour.Status newStatus)
    {
        if (newStatus == TrackableBehaviour.Status.DETECTED ||
            newStatus == TrackableBehaviour.Status.TRACKED ||
            newStatus == TrackableBehaviour.Status.EXTENDED_TRACKED)
            OnTrackingFound();
        else
            onTrackingLost();
    }
    private void OnTrackingFound()
    {
        if (transform.childCount > 0)
            SetChildrenActive(true);
    }
    private void onTrackingLost()
    {
        if (transform.childCount > 0)
            SetChildrenActive(false);
    }
    private void SetChildrenActive(bool activeState)
    {
        for (int i = 0; i <= transform.childCount; i++)
            transform.GetChild(i++).gameObject.SetActive(activeState);
    }
}

```
> 0 votes

---
Tags: c#, unity, vuforia, augmented-reality
---


title: Using GLFW and GLUT together

text:
# Question
Title: Using GLFW and GLUT together
I'm new to OpenGL

Lets say I create an OpenGL window using glfw and I need the UI feature from glut (such as popup menu). Is it possible to use glfw and glut in one program?

Thank you

# Answer
> 0 votes
GLUT is just a quick and dirty way to get an os window open, create a gl context for it and handle basic input events. It also includes some UI features like popup menus and other window-ui related features

GLFW can do everything GLUT does, except for ui stuff. It has a much better structure, a callback system and different context options on the majority of platforms, at the cost of a more complex and verbose api.

I'd suggest you to evaluate what the application requirements are in your case, and then choose the best option.

Do you want more flexibility at the cost of ui features? use GLFW. Do you want less flexibility at the cost of ui features? use GLUT.

Alternatively, you can always use QT, GTK and other cross-platform ui toolkits.

So yes you can, but probably shouldn't.

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


# Question
Title: Jerky Character movement after adding mouse orbit script
I added a custom mouse orbit script to my project. When the right mouse button is clicked, the camera can be rotated around the player.

The issue, after this change, is my player movement has become jerky / choppy and not smooth. If I remove my mouse orbit script, player moment is back to normal i.e smooth. I can't seem to pin point what is causing this jerky movement withing MouseOrbit script

Video demo

Code

```
/* This is where we initialize our script */
void Start()
{
    Initialize();
}

/* This is where we set our private variables, check for null errors,
 * and anything else that needs to be called once during startup */
void Initialize()
{
    h = this.transform.eulerAngles.x;
    v = this.transform.eulerAngles.y;

    cameraTransform = this.transform;
    cam = Camera.main;
    smoothDistance = distance;
    timerot = TimeSignature((1 / rotationDampening)) * 100.0f;
    NullErrorCheck();
}

/* We check for null errors or warnings and notify the user to fix them */
void NullErrorCheck()
{
    if (!viewTarget)
    {
        Debug.LogError("Please make sure to assign a view target!");
        Debug.Break();
    }
    if (collisionLayers == 0)
    {
        Debug.LogWarning("Make sure to set the collision layers to the layers the camera should collide with!");
    }
}

/* This is where we do all our camera updates. This is where the camera
 * gets all of its functionality. From setting the position and rotation,
 * to adjusting the camera to avoid geometry clipping */
void Update()
{
    if (!viewTarget)
        return;

    if (Input.GetMouseButton(1))
        {
            Cursor.lockState = CursorLockMode.Locked;

            h += Input.GetAxis("Mouse X") * horizontalRotationSpeed * Time.deltaTime;
            v -= Input.GetAxis("Mouse Y") * verticalRotationSpeed * Time.deltaTime;

            h = ClampAngle(h, -360.0f, 360.0f);
            v = ClampAngle(v, minVerticalAngle, maxVerticalAngle);
            //              Debug.Log ("value of h: "+h);
            newRotation = Quaternion.Euler(v, h, 0.0f);
        }
        else
        {
            Cursor.lockState = CursorLockMode.None;
        }

    if (Input.GetKeyDown(KeyCode.D))
    {
        h = transform.eulerAngles.y + 90;
        newRotation = Quaternion.Euler(transform.eulerAngles.x, h, transform.eulerAngles.z);
    }

    if (Input.GetKeyDown(KeyCode.A))
    {
        h = transform.eulerAngles.y - 90;
        newRotation = Quaternion.Euler(transform.eulerAngles.x, h, transform.eulerAngles.z);
    }

    /* We set the distance by moving the mouse wheel and use a custom
     * growth function as the time value for linear interpolation */
    distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel") * 10, minDistance, maxDistance);
    smoothDistance = Mathf.Lerp(smoothDistance, distance, TimeSignature(distanceSpeed));

    /*We give the rotation some smoothing for a nicer effect */
    smoothRotation = Quaternion.Slerp(smoothRotation, newRotation, TimeSignature((1 / rotationDampening) * 100.0f));

    newPosition = viewTarget.position;
    newPosition += smoothRotation * new Vector3(0.0f, height, -smoothDistance);

    /* Calls the function to adjust the camera position to avoid clipping */
    CheckSphere();

    smoothRotation.eulerAngles = new Vector3(smoothRotation.eulerAngles.x, smoothRotation.eulerAngles.y, 0.0f);
    Vector3 dir = new Vector3(0, 0, -distance);

    cameraTransform.position = newPosition;
    //cameraTransform.position = viewTarget.position + smoothRotation * dir;
    cameraTransform.rotation = smoothRotation;
}

```

Time Signature with speed as input

```
private float TimeSignature(float speed)
{
    return 1.0f / (1.0f + 80.0f * Mathf.Exp(-speed * 0.02f));
}

```

# Answer
> 2 votes
It was a simple case of changing

```
void Update()

```

to

```
void LateUpdate()

```

https://docs.unity3d.com/ScriptReference/MonoBehaviour.LateUpdate.html

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


# Question
Title: How do I properly change the value of a prefab'd instance variable?
I am currently following a tutorial on how to make a 2D platformer in Unity.

The tutorial explains how to make an enemy wave spawner, but it doesn't explain how to make enemies stronger after I have completed a certain amount of waves.

So, to explain: I have an `Enemy` class, which has an `EnemyStats` class in it:

```
public class Enemy : MonoBehaviour
{
    [System.Serializable]
    public class EnemyStats
    {
        public int damage = 20;
        public int maxHealth = 100;

        public int CurrentHealth
        {
            get { return _currentHealth; }
            set { _currentHealth = Mathf.Clamp(value, 0, maxHealth); }
        }

        private int _currentHealth;

        public void Init()
        {
            CurrentHealth = maxHealth;
        }
    }

    public EnemyStats stats = new EnemyStats();

    private StatusIndicator statusIndicator;

    void Awake()
    {
        stats.Init();
        statusIndicator = transform.Find("StatusIndicator").GetComponent<StatusIndicator>();

        if (statusIndicator != null)
        {
            statusIndicator.SetHealth(stats.CurrentHealth, stats.maxHealth);
        }
    }
}

```

And in the `WaveSpawner` class I have the method to spawn the enemy:

```
private void SpawnEnemy(Enemy enemy)
{
    Transform sp = spawnPoints[UnityEngine.Random.Range(0, spawnPoints.Length)];

    if (CurrentWave % 5 == 0)
    {
        enemy.stats.maxHealth += 20;
    }

    Instantiate(enemy.transform, sp.position, sp.rotation);
}

```

In the `WaveSpawner` you can set a certain number of waves (let's say 5), and after you complete all of the waves I've set them to repeat. So after I beat the 5 waves, I want the 5 waves to repeat and the enemies to be stronger (for example to have their max hp increased by 20).

I do that with the line: `enemy.stats.maxHealth += 20;`

But the problem here is that after this line is executed and I `Instantiate` the enemy `prefab`, the `prefab` changes its value in the inspector. So let's say that the initial value of the `prefab` was 120, after I beat the 5 enemy waves, the value of the `prefab` is set to 140. Then, after I reset the game, the initial value of the `prefab` is 140 and the max health of the first enemies is 140 and not 120.

I have tried to not change the `maxHealth` variable of the `EnemyStats` class, but instead to have another variable `tempMaxHealth` and do the changes on it. This doesn't resolve my problem, as other problems arise and I don't know what to do anymore.

I hope that you have an answer for me, I would be grateful if that's the case.

# Answer
Remember, the variable called `enemy` here is your *prefab*.

Sometimes I'll name these variables something like `enemyPrefab` so I can't lose track of what's a source asset I shouldn't modify at runtime, versus what's a dynamic instance.

When we write it this way it's obvious:

```
if (CurrentWave % 5 == 0) {
    enemyPrefab.stats.maxHealth += 20;
}

```

We just changed the prefab with this line, so it's natural that we see it change in the inspector.

Instead we should do something like this - we capture *the instance of the enemy prefab that we just spawned* and modify *that*:

```
Enemy enemyInstance = Instantiate(enemyPrefab, sp.position, sp.rotation);

int numHealthBoosts = CurrentWave/5;
enemyInstance.stats.maxHealth += numHealthBoosts * 20;

```

Any code that works with the maxHealth should be moved from `Awake`/`OnEnable` (which run before `Instantiate` returns) and into `Start` or a custom initializer method so it runs after our spawning routine finishes and sees the updated value of the stats.
> 1 votes

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


# Question
Title: Disabling, overriding or hooking a VS warning to Unity's Vector's ToString()?
I've just spent 2 hours debugging a misbehaviour because **ToString() truncates to 1 digit** by default.

I want to **disable the parameterless version** so I won't use it by accident and I will **always have to define how much truncation** I want.

Or if this isn't possible I want to redefine it, so it will truncate to 3 digits for example.

Or somehow **hook a custom warning to it**, so *Visual Studio* will tell me that I'm using it?

Is this possible?

# Answer
> 1 votes
This is not possible. Unity Vectors are structs. Therefore you cannot derive your own vectors and of course not override `ToString()`. You will have to use this other overloaded version:

```
public string ToString(string format)

```

and call it with

```
string s = v.ToString("F3")

```

---

You could also declare an extension method

```
public static class VectorExtensions
{
    public string ToStrStd(this Vector3 v) => v.ToString("F3");
}

```

and use it like this

```
string s = v.ToStrStd()

```

---

I don't think there is an easy way to be warned if you are using the "wrong" version. If you are working with Visual Studio, you could Write your first analyzer and code fix.

---
Tags: unity, c#, visual-studio, .net
---


title: Use 2 values of a mask

text:
# Question
Title: Use 2 values of a mask
Let's say one has a black/gray/white mask and wants to draw picture A over the white/gray values and picture B over the black/gray values (the blacker the more B picture). The best I come up with would be something like:

1. Set to RenderTargetA
2. Draw Mask
3. Draw PictureA over Mask (using DepthStencilState)
4. Set to RenderTargetB
5. Draw Mask
6. Draw PictureB over Mask
7. Draw both RenderTargets over each other somehow

But that just seems a) overly complicated and b) both render targets still have the mask drawn on them so it wouldn't have worked anyway. So how would one achieve this?

# Answer
Yes. Shaders are the way. Just a simple shader worked. Here's the shader:

```
texture activeTexture;
sampler2D activeSampler = sampler_state {
    Texture = (activeTexture);
};

texture passiveTexture;
sampler2D passiveSampler = sampler_state {
    Texture = (passiveTexture);
};

texture visionMask;
sampler2D visionSampler = sampler_state {
    Texture = (visionMask);
};

sampler s0;
sampler ms0 : register(s0);

float4 MainPS(float2 coords: TEXCOORD0) : COLOR0
{
    float4 visionColor = tex2D(visionSampler, coords);
    float4 activeColor = tex2D(activeSampler, coords);
    float4 passiveColor = tex2D(passiveSampler, coords);

    float4 color = float4(0, 0, 0, 1);
    color.rgb = activeColor.rgb * visionColor.rgb + ((float3(1, 1, 1) - visionColor.rgb) * passiveColor.rgb);

    return color;
}

technique Technique0
{
    pass Pass0
    {
        PixelShader = compile ps_3_0 MainPS();
    }
}

```
> 1 votes

---
Tags: graphics, monogame, masking
---


title: Body inside other body after collision

text:
# Question
Title: Body inside other body after collision
I'm using bullet to create a 2D topdown game. In my physics proof of concept, I can walk around and push a box. However, if I walk too fast the character goes through the box, instead of colliding with it. See gif:

This seems like a common thing to me. However, I cannot find other people having the same problem, so that's why I'm asking a question directly. I'm using a DiscreteDynamicsWorld with two rigid bodies which I step through at 60Hz.

* Why does this happen?
* Is there a way to tune bullet to support higher speeds and prevent this issue?

Help is very much appreciated.

**Edit**

Regarding the question about how I setup collision shapes:

```
btConvexHullShape shape;
shape.addPoint({-size, size, 0.0f});
shape.addPoint({size, size, 0.0f});
shape.addPoint({size, -size, 0.0f});
shape.addPoint({-size, -size, 0.0f});

```

# Answer
> 1 votes
The issue you are describing is known as 'tunneling.'

By far the easiest way to fix this is to take smaller physics steps.

If you render at 60FPS, don't step through the simulation with 16.7ms. Instead, take two steps of 8.3ms (or even more and smaller steps than that.)

The alternative is to do continuous collision detection. There seem to be some hooks for that in Bullet Physics, but I can't find documentation nor example code for it. In case you want to track it down, start at btDynamicsWorld::btDynamicsWorldType = **BT\_CONTINUOUS\_DYNAMICS\_WORLD**

My guess is that continuous physics will be a lot more effort to make it work (if it works at all) when compared to the easy fix of smaller timesteps.

---
Tags: bullet-physics
---


title: How can I mask this CanvasRenderer?

text:
# Question
Title: How can I mask this CanvasRenderer?
I'm creating a text box that allows for selectable text, based off of Unity's InputField. An issue I am now facing is that the selection highlight does not respond to masks (The parent has a mask, but it is just ignored) depth is also ignored, this seems to render through any other UI element that's in-front of it.:

I'm completely lost on how to go about masking it, so it does not show up past the bounds of the box. The code I used to generate it is heavily based off of Unity's, it's a bit long and kind of hacked together at the moment, I'm including it for references sake.

The method that generates the verts for the highlight in the .gif is `GenerateHighlight`

```
        private void UpdateGeometry()
    {
        if(caretCanvasRenderer == null && textBacker != null)
        {
            GameObject caret = new GameObject(transform.name + "Caret");
            caret.hideFlags = HideFlags.DontSave;
            caret.transform.SetParent(textBacker.transform);
            caret.transform.SetAsFirstSibling();
            caret.layer = gameObject.layer;

            caretRectTransform = caret.AddComponent<RectTransform>();
            caretCanvasRenderer = caret.AddComponent<CanvasRenderer>();
            caretCanvasRenderer.SetMaterial(Graphic.defaultGraphicMaterial, null);
            //caretCanvasRenderer.isMask = true;

            caret.AddComponent<LayoutElement>().ignoreLayout = true;

            AssignPositioningIfNeeded();
        }

        if (caretCanvasRenderer == null)
            return;

        OnFillVBO(VBO);

        if (VBO.Count == 0)
            caretCanvasRenderer.SetVertices(null, 0);
        else
            caretCanvasRenderer.SetVertices(VBO.ToArray(), VBO.Count);

        VBO.Clear();
    }

    private void OnFillVBO(List<UIVertex> vbo)
    {
        //if (!isFocused)
        //    return;

        Rect inputRect = textBacker.rectTransform.rect;
        Vector2 extents = inputRect.size;

        // get the text alignment anchor point for the text in local space
        Vector2 textAnchorPivot = Text.GetTextAnchorPivot(textBacker.alignment);
        Vector2 refPoint = Vector2.zero;
        refPoint.x = Mathf.Lerp(inputRect.xMin, inputRect.xMax, textAnchorPivot.x);
        refPoint.y = Mathf.Lerp(inputRect.yMin, inputRect.yMax, textAnchorPivot.y);

        // Ajust the anchor point in screen space
        Vector2 roundedRefPoint = textBacker.PixelAdjustPoint(refPoint);

        // Determine fraction of pixel to offset text mesh.
        // This is the rounding in screen space, plus the fraction of a pixel the text anchor pivot is from the corner of the text mesh.
        Vector2 roundingOffset = roundedRefPoint - refPoint + Vector2.Scale(extents, textAnchorPivot);
        roundingOffset.x = roundingOffset.x - Mathf.Floor(0.5f + roundingOffset.x);
        roundingOffset.y = roundingOffset.y - Mathf.Floor(0.5f + roundingOffset.y);

        if (!hasSelection)
            GenerateCursor(vbo, roundingOffset);
        else
            GenerateHightlight(vbo, roundingOffset);
    }

    private void GenerateCursor(List<UIVertex> vbo, Vector2 roundingOffset)
    {
        if (!caretVisible)
            return;
        if(cursorVerts == null)
            CreateCursorVerts();

        float width = 1f;
        float height = textBacker.fontSize;
        int adjustedPosition = Mathf.Max(0, caretPositionInternal - drawStart);
        TextGenerator generator = textBacker.cachedTextGenerator;

        if(generator == null)
            return;

        if (textBacker.resizeTextForBestFit)
            height = generator.fontSizeUsedForBestFit / textBacker.pixelsPerUnit;

        Vector2 startPosition = Vector2.zero;

        // Calculate startPosition
        if (generator.characterCountVisible + 1 > adjustedPosition || adjustedPosition == 0)
        {
            UICharInfo cursorChar = generator.characters[adjustedPosition];
            startPosition.x = cursorChar.cursorPos.x;
            startPosition.y = cursorChar.cursorPos.y;
        }
        startPosition.x /= textBacker.pixelsPerUnit;

        // TODO: Only clamp when Text uses horizontal word wrap.
        if (startPosition.x > textBacker.rectTransform.rect.xMax)
            startPosition.x = textBacker.rectTransform.rect.xMax;

        cursorVerts[0].position = new Vector3(startPosition.x, startPosition.y - height, 0.0f);
        cursorVerts[1].position = new Vector3(startPosition.x + width, startPosition.y - height, 0.0f);
        cursorVerts[2].position = new Vector3(startPosition.x + width, startPosition.y, 0.0f);
        cursorVerts[3].position = new Vector3(startPosition.x, startPosition.y, 0.0f);

        if (roundingOffset != Vector2.zero)
        {
            for (int i = 0; i < cursorVerts.Length; i++)
            {
                UIVertex uiv = cursorVerts[i];
                uiv.position.x += roundingOffset.x;
                uiv.position.y += roundingOffset.y;
                vbo.Add(uiv);
            }
        }
        else
        {
            for (int i = 0; i < cursorVerts.Length; i++)
            {
                vbo.Add(cursorVerts[i]);
            }
        }

        startPosition.y = Screen.height - startPosition.y;
        Input.compositionCursorPos = startPosition;
    }

    private void GenerateHightlight(List<UIVertex> vbo, Vector2 roundingOffset)
    {
        int startChar = Mathf.Max(0, caretPositionInternal - drawStart);
        int endChar = Mathf.Max(0, caretSelectPositionInternal - drawStart);

        // Ensure pos is always less then selPos to make the code simpler
        if (startChar > endChar)
        {
            int temp = startChar;
            startChar = endChar;
            endChar = temp;
        }

        endChar -= 1;
        TextGenerator generator = textBacker.cachedTextGenerator;

        int currentLineIndex = DetermineCharacterLine(startChar, generator);
        float height = textBacker.fontSize;

        if (textBacker.resizeTextForBestFit)
            height = generator.fontSizeUsedForBestFit / textBacker.pixelsPerUnit;

        if (generator != null && generator.lines.Count > 0)
        {
            // TODO: deal with multiple lines with different line heights.
            height = generator.lines[0].height;
        }

        if (textBacker.resizeTextForBestFit && generator != null)
        {
            height = generator.fontSizeUsedForBestFit;
        }

        int nextLineStartIdx = GetLineEndPosition(generator, currentLineIndex);

        UIVertex vert = UIVertex.simpleVert;
        vert.uv0 = Vector2.zero;
        vert.color = selectionColor;

        int currentChar = startChar;
        while (currentChar <= endChar && currentChar < generator.characterCountVisible)
        {
            if (currentChar + 1 == nextLineStartIdx || currentChar == endChar)
            {
                UICharInfo startCharInfo = generator.characters[startChar];
                UICharInfo endCharInfo = generator.characters[currentChar];
                Vector2 startPosition = new Vector2(startCharInfo.cursorPos.x / textBacker.pixelsPerUnit, startCharInfo.cursorPos.y);
                Vector2 endPosition = new Vector2((endCharInfo.cursorPos.x + endCharInfo.charWidth) / textBacker.pixelsPerUnit, startPosition.y - height / textBacker.pixelsPerUnit);

                // Checking xMin as well due to text generator not setting possition if char is not rendered.
                if (endPosition.x > textBacker.rectTransform.rect.xMax || endPosition.x < textBacker.rectTransform.rect.xMin)
                    endPosition.x = textBacker.rectTransform.rect.xMax;

                vert.position = new Vector3(startPosition.x, endPosition.y, 0.0f) + (Vector3)roundingOffset;
                vbo.Add(vert);

                vert.position = new Vector3(endPosition.x, endPosition.y, 0.0f) + (Vector3)roundingOffset;
                vbo.Add(vert);

                vert.position = new Vector3(endPosition.x, startPosition.y, 0.0f) + (Vector3)roundingOffset;
                vbo.Add(vert);

                vert.position = new Vector3(startPosition.x, startPosition.y, 0.0f) + (Vector3)roundingOffset;
                vbo.Add(vert);

                startChar = currentChar + 1;
                currentLineIndex++;

                nextLineStartIdx = GetLineEndPosition(generator, currentLineIndex);
            }
            currentChar++;
        }
    }

```

**The gist of it**, is it creates a new gameobject. Adds a canvas renderer, and rect transform. Calls the appropriate method that generates the vertices, and then assigns those to the \`CanvasRenderer.

# Answer
> 2 votes
Take a look at UI.Graphic and UI.MaskableGraphic

You'll want to write a class that derives from \[MaskableGraphic\] then implement the methods to fill the VBO when the UI asks for it.

# Answer
> 1 votes
Add this to the new Input Caret `GameObject` created by the `InputField` and masking should work.

```
class Masker : MaskableGraphic
{
}

```

---
Tags: unity, c#, geometry, masking
---


# Question
Title: How to move a Line Renderer as its game object moves
I created an empty game object and added a Line Renderer component to it through a script. I thought that once I adjust the position of the game object, it would do likewise for the line rendeder, but that is not the case.

I tried `useWorldSpace = false` but it totally changed the positions making the following points a straight line, though I was able to move the game object to to the line.

```
public Vector3 beginPos = new Vector3 (-1.0f, -1.0f, 0);
public Vector3 endPos = new Vector3 (1.0f, 1.0f, 0);

```

Is there a way I can convert points to input what I am more familiar with (so that points like the above points don't create a straight line) or should I be approaching the problem in a different way? I am open to a different approach.

**UPDATE**

I think I left an import detail. I'll be using lines made with line renderer to create shapes. So I need to be able to be able to move the lines around to move the shapes so I don't have to always recalculate the start and end points for the lines.

# Answer
First of all make sure your LineRenderer component use World Position. then in your Update() method just assign points positions (this code works for 5.6.0):

```
void Update(){
        if (usingLineRenderer)
        {
            myLineRenderer.SetPosition(0, transform.position);
            if (hitBlocked == true) // we've hit something, so our line renderer end point should stop here
            {
                myLineRenderer.SetPosition(1, Hit.point);
            }
            else
            {
                myLineRenderer.SetPosition(1, transform.position + transform.forward * maxLaserDistance);
            }
        }

        if(Physics.Raycast(transform.position, transform.forward, out Hit, maxLaserDistance, ~ignoredLayers)){
             hitBlocked = true;
             // do stuff
        }
}

```

Particularly useful when using Virtual Reality Motion controllers, just assign it to the associated Hand Anchor.
> 1 votes

# Answer
According to this post, you can bake the line into mesh, then you can move the line (as mesh), here is the code from the post:

```
 public static void BakeLineDebuger(GameObject lineObj)
 {
     var lineRenderer = lineObj.GetComponent<LineRenderer>();
     var meshFilter = lineObj.AddComponent<MeshFilter>();
     Mesh mesh = new Mesh();
     lineRenderer.BakeMesh(mesh);
     meshFilter.sharedMesh = mesh;

     var meshRenderer = lineObj.AddComponent<MeshRenderer>();
     meshRenderer.sharedMaterial = s_matDebug;

     GameObject.Destroy(lineRenderer);
 }

```

Make sure `lineObj` has `LineRenderer` component.
> 1 votes

# Answer
Either update the line renderers positions yourself via script, or use a Trail Renderer
> 0 votes

---
Tags: unity
---