# Question
Title: Cumulative transformation matrices for hierarchical object transformations
I'm having a small issue with my design for hierarchical 3D objects. I'll try to sum things up concisely. Every object has a vector3 for its position, scale, and rotation, as well as a std::vector of children objects. An object's render function takes an optional parameter for a parent's transformation matrix, which defaults to the identity matrix. In this render function, the object's transformation matrix is computed with this form:

```
transformation = parentTransformation * translationMatrix * rotationMatrix * scaleMatrix;

```

After the matrix is computed, all of the childrens' render functions are called with the computed matrix being passed, then the actual render for THIS object happens.

My problem seems to be with the scaling bit. For this case, I have a wooden manikin built out of several spheres, all translated and scaled to give shape. For the legs and arms, I scaled the sphere pieces obviously not uniformly. To avoid the children objects of those body parts from also being scaled like that, I scale them by the inverse of that scale factor after scaling the particular body part. However, when I rotate a joint which is a child of one of these oddly scaled pieces, you can see how the scaling is really only in the childrens' "model space" and as a result, they get strangely contorted. Is there a misunderstanding on my part about how objects should inherit their parents' transformations?

Here are some images to demonstrate my results. The second image is after rotating the knee joint 80 degrees.

# Answer
> 3 votes
So firstly, I'd like to apologize if my question was poorly worded or if it was just confusing in general. I think I've figured out the proper solution now. It took a while because I had passed it off earlier after trying it and not immediately seeing desired results (I needed to basically remake my wooden manikin object from scratch).

Basically, I found that objects really shouldn't be inheriting their parents' scales to begin with, just for safety. I changed my design so that when a transformation matrix was to be recomputed, a scaleless transformation was computed and passed down to the children, but then the real transformation including scale was also computed to be used for rendering. What this ultimately means is that I had to also change my scale methods to take a "recursive" boolean as a parameter, where if true, the scale factor would be applied to all children objects recursively. I like having that functionality - the ability to scale an entire complex object, or just a piece of it - however I'm not sure if this is how it "should" be done, or if this is the most efficient way. If anybody has any feedback or advice for me on this topic, please share, but for now what I've learned is

> **scale should not be inherited from parent objects by means of inherited transformation matrices.**

My results - bending the knee by 80 degrees:

# Answer
> 0 votes
In my own project I suddenly came to the same conclusion - the parent scale shouldn't be passed down to the children's transformation matrix. And I thought it was weird too. I figured, if you want to stay consistent throughout your code, either you pass through all of it, or you pass through nothing. However, seeing how you came to the same conclusion is kind of reassuring, so I suppose I'm sticking with it.

I came to this conclusion while trying to roll my own GUI implementation. I had pixel art images of my GUI elements, and when I changed my monitor's resolution, the images rescaled automatically and quite frankly looked butt ugly. So I had to find a way to keep my images the same size (or rescaled in powers of 2 to keep the pixel art consistent). Dropping the parent scale from the hierarchy and keeping the scale of my objects absolute instead of relative seemed to be the obvious solution.

Now at some point I needed relative scale anyways, but this was easily fixed. Whenever one of my objects resizes, it calls a scaleTo(width, height) event. Now I can easily override this event and adjust the scale (and position) appropriately, i.e.

```
@Override
public void scaleTo(float w, float h)
{
    super.scaleTo(w, h);

    background.scaleTo(w - 210, h - 230);
    background.moveTo(85, -95);

    lblTitle.setFontSize(48);
    lblTitle.moveTo(220 - w / 2, h / 2 - 160);
    lblTitle.scaleTo(400, 50);
}

```

To keep my code consistent, I've made it a habit to always put my move and scale code inside this event.

One thing that might be worth noting: for every one of your objects, you're creating both a full transformation matrix and a scaleless matrix in the event of children. For performance sake, it may be a good idea to cache the result of these calculations, and not recalculate them every time you need them. Simply add an 'isChanged' flag to your transformations, which is set to true whenever the object is moved/scaled/rotated, and makes sure the matrix recalculation is delayed up until the moment you actually need it.

So yeah, this is how I'm doing it at the moment. I'd love to hear thoughts of anyone else who has worked on a similar problem. Also, Elephly, since this was posted several months ago, if by any chance you've further improved on the system since then, I'd love to hear that too.

---
Tags: opengl, mathematics, matrix, transformation, scene-graph
---


# Question
Title: Why have the player pick up loot manually?
From a game-design perspective, I was wondering what the mechanic of manually picking up items off the ground does for the player. Keep in mind that items that fall on the ground can most likely be put into one of two groups:

* Equipment Items: depending on the character the player is creating, the majority of these items might be ignored and left on the ground. Players will only pick up the ones that they want to "spend" inventory space and time (*by clicking and eventually having to go back to town*) on.
* Consumables: gold, gems, crafting materials, etc - which players generally always want to pick up and sometimes don't take up inventory space.

While I can see that making players choose which items to pick up is an interesting "collecting" mechanic for the Equipment group, why make the "Consumable" group require manual picking up as well?

---

Examples of games which do this: (*most diablo-esque dungeon crawlers*)

Diablo 3

Path of Exile

Grim Dawn

Torchlight 2

# Answer
Why are you giving the player loot in the first place?

It's a reward stimulus for the player. Games need a constant stream of reward stimulus (or at least the anticipation of a reward) to keep the player motivated to continue playing. The impact of a reward is not just determined by the mechanical effect (player now has 10 more gold to spend) but also by how much the player notices it.

By having the player interact with the reward in form of clicking to pick it up, you have the player notice it more which amplifies its psychological effect without changing its mechanical effect.

It also makes the player more aware of their current possessions. When you just put stuff into their inventory directly, they might easily miss that they just had the luck of finding the ultra-rare +99 sword of pwnage because they were focusing on something else. Then half an hour later they open their inventory for a completely different reason and wonder how they got it. The same applies to more generic resource-style items which the player collects in bulk. By getting a more direct feedback about the loot reward they get a clearer impression of which actions reward them with what kind of loot.
> 13 votes

# Answer
In some games, mainly in fps, it can create a bit more of a thrill. Ex. if you are behind cover and out of ammo and you see a gun. Maybe you can reach it or you have to sprint across the open to grab it. Making it manual adds a little more skill and requires a bit more attention to be played by the player.

Another reason is that a lot of games (like Skyrim) have a lot of junk loot. Stuff you don't really want but sometimes you take it just for the fun of it. So the game let's you. But it would suck if you had to constantly empty your inventory of cups because you walked over a table. Due to this they have to keep the pick up system constant through the game so every item becomes manual pick up.
> 1 votes

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


# Question
Title: (unity 2D) How to design valid playable levels?
I'm prototyping a 2D platofrm game with simple jump to tap mechanics. Here, the ball is constantly moving forward with a fixed velocity, and jumps when a key is pressed. For reference, image below :

This is one of the many scenarios in the game. Difficulty I have is determining the position of various obstacles. For example, in the attached image, how to determine how far the two obstacle pairs should be so that it's just right. Make sure player can jump through the first pair and clear the second pair without making it too easy or nearly impossible to clear. Any level design validation techniques?

# Answer
Make some levels just quickly. And have people play test them. Play testing is the best way to do anything. Have your play testers rate each levels difficulty and then you can organize them however. (sometimes always getting harder isn't the best way to do things) you will probably be surprised to find that your testers will find each level harder to complete than you did. And listen to everything your testers have to say about each level and implement what you find good. Repeat until you are done. Good luck! And have fun!
> 1 votes

# Answer
One good discussion I foThe guide to implementing 2D platformers. One particularly useful tip mentioned there is Tile based level design. This approach removes the guess work as it gives some fixed quantity which can be used as reference. For example, I can quantify mechanics as :

* player jumps two tiles high and 3 tiles long.
* obstacles should have minimum 4 tiles of distance between them (horizontal)

and so on. Still looking for some more discussion.
> 0 votes

---
Tags: unity, level-design
---


title: How create/draw faded circles in Java

text:
# Question
Title: How create/draw faded circles in Java
How do I create some circle - like the one on the image - in Java, and in various colors?

I would like to make more of these circles to fly from specific position to random direction.

# Answer
> 1 votes
I don't know android specifically, but if you are using OpenGL ES, you can use a shader to make this work. First create a image like this in black color. Then use a color tint.

Now use a fragment shader to draw this texture. The code looks like this.

```
#ifdef GL_ES
    precision mediump float;
#endif

varying vec2 texCoords;

uniform vec4 color;
uniform sampler2D image;

void main()
{
    vec4 texel = texture2D(texCoords, image);

    gl_FragColor = vec4(texel.rgb + color.rgb, texel.a * color.a);
}

```

This uses additive blending, and hence using an image with black color is very important. You can then draw this image using this shader at any scale you want.

Hope this helps.

---
Tags: java, android
---


# Question
Title: How to create a believable swimming fish animated Sprite in 2d?
I want to create a fishing game in which fish needs to be swam across in the ocean. I put static fish which just progresses across ocean but it does not look very realistic and interesting to attract users to play.

I have used minimal graphics style to design graphics for the game and want to put some animation, like, moving tails and fins which I can achieve by making multiple images. But I also want to put some big fishes like sharks and only animating fins and tails will not be enough for them. As player will die without touching body due to margin left for tails or fins animation, or consider an eel.

I can use the snake technology for eels but for fishes where only tails move, is there any other way I can use? Or consider the Jumping Fish game by Ketchapp.

Could anyone suggest me proper ways to achieve such animations?

# Answer
The usual way to animate 2d graphics is the good old method we use since the first days of animated cartoons: draw a separate graphic for each step of the animation and then display them in a loop.

To get the animation phases right it often helps to look at the real thing and study how it moves.
> 1 votes

---
Tags: animation, algorithm
---


title: Unwanted Perlin Noise result

text:
# Question
Title: Unwanted Perlin Noise result
I've finally managed to write a working Lua version of Perlin's improved noise for Love 2D. However, when I run it, i get this:

Which is just fine, I guess. But I would like something that looks more like this:

How can I achieve this?

# Answer
> 9 votes
You will need to learn how the terms Octave, Persistence, Frequency, and Lacunarity are used. What you have is a good first step, it looks just like noise should.

The basic idea is that you need to combine multiple noise sources into one result to achieve the final look. This combination can be something simple like addition, but you can take many mathematical operations.

In the end a typical example for your grainy clouds looks like this: Map = Map1 + (Map2 / 2) + (Map3 / 4) + (Map4 / 8)

For reference and examples: Start here

---
Tags: random, perlin-noise, noise
---


# Question
Title: Game asset "objects" consisting of several meshes vs continuous mesh
When building game objects in a 3D modeler like Blender I'm finding it's easier to get greater detail and still have fewer vertices if I separate certain elements. For example, I need to make cuts along certain edges to add appendages to that part of the mesh, which could potentially increase the poly count by a large number. If I simply add another mesh I don't need to cut new vertices into the mesh I'm extending. I'm talking about buildings and other structures that never move.

With static objects (that don't move, ever) I was thinking this wouldn't have any drawbacks... but someone may know otherwise. Will this have any visual artifacts or mess up lighting in an engine like Unity or UE4?

Thanks. Sorry if I didn't explain that clearly enough.

# Answer
> 0 votes
I will tell you otherwise: Never leave anything underneath that shall never be visible. 3 reasons:

1. If the rendering for some reason happens from back to front, the hidden surface may get rendered -\> consumes fillrate & time.
2. If the hidden suface is closeby underneath, it may cause z-fighting when seen from a slightly longer distance. This is superiorly annoying.
3. Your users get mad when 1, and especially 2, happen.

Apart from these, there may be good logical reasons to divide, but these should be relevant and are outside scope of this Q. On the other hand, multiple meshes -\> more code, more housekeeping, more render calls.

I'd say cut the single mesh carefully and group it logically, unless there is a good reason to divide it into multiple meshes (like some need to control the sub-parts individually).

---
Tags: models, assets, objects
---


# Question
Title: TiledMap renders but gets duplicated when I move the camera
I've created a map (TMX file) using Tiled, imported it and it shows great but when I move the camera, it duplicates itself and the whole screen flickers. In Tiled, I didn't use a spritesheet but rather a collection of images as they have different sizes.

See attached image:

Here is my game class:

```

public class MyGdxGame extends ApplicationAdapter {

    private IsometricTiledMapRenderer renderer;
    private OrthographicCamera camera;
    private TiledMap map;
    private Vector2 dragOld, dragNew;

    @Override
    public void create() {

        map = new TmxMapLoader().load("isometric_map.tmx");
        renderer = new IsometricTiledMapRenderer(map);

        camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        camera.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);

        Gdx.input.setInputProcessor(new InputAdapter() {
            public boolean touchDown(int screenX, int screenY, int pointer, int button) {
                if (button == Input.Buttons.LEFT) {
                    dragNew = new Vector2(Gdx.input.getX(), Gdx.input.getY());
                    dragOld = dragNew;
                    return true;
                }

                return false;
            }
        });
    }

    @Override
    public void render() {
        super.render();

        camera.update();

        renderer.setView(camera);
        renderer.render();

        if (Gdx.input.isTouched()) {
            dragNew = new Vector2(Gdx.input.getX(), Gdx.input.getY());
            if (dragOld != null && !dragNew.equals(dragOld)) {
                camera.translate(((int) dragOld.x - dragNew.x), ((int) dragNew.y - dragOld.y)); //Translate by subtracting the vectors
                camera.update();
                dragOld = dragNew; //Drag old becomes drag new.
            }
        }
    }

    @Override
    public void resize(int width, int height) {
        super.resize(width, height);

        camera.viewportWidth = width;
        camera.viewportHeight = height;
        camera.update();
    }

    @Override
    public void dispose() {
        super.dispose();

        map.dispose();
    }
}

```

What am I missing?

# Answer
Did you clear the screen? You have to use `glClear()` method to clear the screen before drawing the current frame.

```
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

```

Hope this helps.
> 1 votes

---
Tags: libgdx
---


# Question
Title: How to calculate the magnitude of the drag in Corona-sdk?
I'm making a game on Corona that launches a ball.

The force is based on the magnitude of the drag: the larger is the drag -\> the higher is the force.

I'm having some trouble to do this, because I can't calculate the magnitude of the drag.

I tried a simple (`finalX - initialX`) but that's not a good idea.

```
local function onTouch(event)

    if "began" == event.phase then

    end
    if "ended" == event.phase then
        local finalX = event.x
        local finalY = event.y

        forceX = event.x - event.xStart
        forceY = event.y - event.yStart

        print(forceX, forceY)

    end
end

local function gameComponents()
    local crate = display.newImageRect( "images/sonic.png", 90, 90 )
    crate.x, crate.y = 60, 360
    crate.rotation = 0
    --physics.addBody( crate, "static", { friction=0.3} )

    Runtime:addEventListener( "touch", onTouch )
    return crate

end

local Game = {}
Game.new = gameComponents
return Game

```

# Answer
> 0 votes
Use the hypotenuse lenght of the triangle described by the differences on th x and y axis. This traduces to:

```
dx = event.x - event.xStart
dy = event.y - event.yStart
force = math.sqrt(dx ^ 2 + dy ^ 2)

```

And that's it. Good luck with your game!

---
Tags: geometry, lua, corona-sdk
---


# Question
Title: Perlin noise looks uncoherent on higher z
I was experiencing with my Perlin noise function and I tried to animate a 2D noise by changing the z value of a small amount every frame. However, as z increases, the result becomes stranger and stranger, looking like this:

Why is this happening? How could I solve this?

Here's the Lua code that could be wrong (as asked):

```
function perlin.fade(t)
    return t * t * t * (t * (6 * t - 15) + 10)
end
function perlin.lerp(t, a, b)
    return a + t * (b - a)
end
function perlin.grad(hash, x, y, z)
    local h = hash % 16
    local u
    local v
    if (h < 8) then u = x else u = y end
    if (h < 4) then v = y elseif (h == 12 or h == 14) then v = x else v = z end
    local r
    if ((h % 2) == 0) then r = u else r = -u             end
    if ((h % 4) == 0) then r = r + v else r = r -v end
    return r
end
function perlin:noise(x, y, z)
    y, z = y or 0, z or 0
    local X = math.floor(x) % 256
    local Y = math.floor(y) % 256
    local Z = math.floor(z) % 256
    x = x - math.floor(x)
    y = y - math.floor(y)
    z = z - math.floor(z)
    local u = perlin.fade(x)
    local v = perlin.fade(y)
    local w = perlin.fade(z)
    local A  = self[X + 1] + Y
    local AA = self[A + 1] + Z
    local AB = self[A + 2] + Z
    local B  = self[X + 2] + Y
    local BA = self[B + 1] + Z
    local BB = self[B + 2] + Z
    return perlin.lerp(w, perlin.lerp(v, perlin.lerp(u, perlin.grad(self[AA + 1], x    , y    , z    ),
                               perlin.grad(self[BA + 1], x - 1, y    , z    )),
                       perlin.lerp(u, perlin.grad(self[AB + 1], x    , y - 1, z    ),
                               perlin.grad(self[BB + 1], x - 1, y - 1, z    ))),
               perlin.lerp(v, perlin.lerp(u, perlin.grad(self[AB + 2], x    , y    , z - 1),
                               perlin.grad(self[BA + 2], x - 1, y    , z - 1)),
                       perlin.lerp(u, perlin.grad(self[AB + 2], x    , y - 1, z - 1),
                               perlin.grad(self[BB + 2], x - 1, y - 1, z - 1))))
end

```

# Answer
Here:

```
    perlin.lerp(v, perlin.lerp(u, perlin.grad(self[AB + 2], x    , y    , z - 1),

```

This should have `AA + 2` instead.
> 3 votes

---
Tags: 2d, animation, perlin-noise, noise
---


# Question
Title: How to make a Sprite be displayed always behind everything else?
What I am in need to achieve is to have a Sprite always facing the camera identically to what happens with any simple game UI object, but instead of always displayed above everything else, it should be always displayed behind everything else.

How can I achieve that in Unity using C#?

Regarding the always-behind rendering, I tried setting the Sprite's "Order in Layer" to 0 or to negative values, with no success. I also tried setting all game objects to a greater value than the sprite's:

```
    go.GetComponent<Renderer>().sortingLayerName = "Test";
    go.GetComponent<Renderer>().sortingOrder = 1;

```

That did not work as well.

What would be the correct way of making a sprite to be always displayed behind everything else (other sprites, GUI and 3D meshes) - preferably not having to resort to shaders, if possible?

PS:regarding the effect of the Sprite always facing the camera as in a game UI, I suppose it will be only a matter of updating its rotation towards the camera - but I would be happy to find out if other approaches are avialable/more suited to the task.

# Answer
You can do this with two cameras with different culling masks.

When you have multiple cameras in your scene, each camera will be rendered separately. The culling mask decides what will be rendered by the camera. Then the output of all the cameras get drawn on top of each other in order of their "Depth" value.

* Click on "Layers -\> Edit Layers" and create a new user layer "Under".
* Assign that layer to the game object of your sprite.
* Make sure everything else has the "Default" layer assigned to it.
* Create a second camera which is identical to the first. Make sure it also maintains the same position, rotation and other settings so both cameras always show the exact same view frustum (assuming you want the back-sprite to move just like everything else moves).
* On the first camera (the "under"-camera) set:
    + Clear Flags: "Skybox" / "Solid color" (whatever you want to be the background)
    + Culling mask: "Under"
    + Depth: -1
* On the second camera (the "everything else" camera) set:
    + Clear Flags: "Depth Only"
    + Culling mask: "Default"
    + Depth: 0
> 2 votes

# Answer
Try drawing the sprite before anything else.
> -3 votes

---
Tags: unity, c#, rendering, camera, draw-order
---


# Question
Title: Multiple UV coordinates in Unreal Engine Procedural Mesh Component?
How can I have multiple UV coordinates per vertex in a Procedural Mesh Component? My goal is to create a UV editor.

I know it is possible to generate multiple vertices per corner, as in UKismetProceduralMeshLibrary::GenerateBoxMesh but that's 24 vertices instead of 8 for a simple box. Would this be a performance problem?

I know that FRawMesh (used when importing an FBX into a static mesh) contains multiple UVs per "wedge" (properties stored for each corner of each face). But I don't know how to set or create the equivalent in custom mesh component (except by duplicating vertices).

I know that casperjeff modified the Procedural Mesh Component plugin to add an additional UV set (as he explains here), but I don't really know how to make one UV set correspond to one face.

I am looking for an efficient solution in terms of performances.

# Answer
The only possibilty you have is to add the vertex twice, if no collision is generated, this will have almost no performance impact, if you do want collision, subclass the UProceduralmeshComponent yourself and override GetPhysicsTriMeshData to fill the collision array with non-duplicated vertices
> 3 votes

---
Tags: 3d-meshes, unreal, uv-mapping
---


# Question
Title: LibGDX - Trying to make a radar-like display
i have an interesting question about geometry. I have two or more moving objects outside of my stage's viewport (blue and red circle in the image below), which i want to point at with two arrows on the border of the screen (or better, viewport bounds). The black dot never moves, because it represents viewport's center.

So, arrows must always point at the objects and must always be "locked" on the border of the screen.

Can someone help me with this?

**UPDATE** Following @Stormwind answer, i managed to get a `Ray` from objects to screen center. Now my problem is defining the `BoundingBox`. I tried declaring it like this:

```
Vector3 v1 = new Vector3(0, 0, 0)
Vector3 v2 = new Vector3(screen.width, screen.height, 0)
BoundingBox box = new BoundingBox(v1, v2)

```

and then get the intersection by using the `IntersectRayBounds()` method, but behaviour is *funny*. I think i missed out something or mistakenly declared the `BoundingBox`.

# Answer
```
Depending on what program you are using, a simple draw line command would be the simplest of ways.

```

To provide the user with more target info, use the following.

```
P1x=230;
P1y=120;
P2x=20;
P2y=40;
Bearing=atan(No/Ea)*180/Pi;
Distance=sqrt((P1x-P2x)^2+(P1y-P2y)^2);

```
> 0 votes

# Answer
According to LibGDX documentation, it does this for you:

> ```
> intersectRayBounds
>
> public static boolean intersectRayBounds(Ray ray,
>                                          BoundingBox box,
>                                          Vector3 intersection)
>
> Intersects a Ray and a BoundingBox, returning the intersection point in intersection. This intersection is defined as the point on
>
> ```
>
> the ray closest to the origin which is within the specified bounds.
>
> ```
> The returned intersection (if any) is guaranteed to be within the bounds of the bounding box, but it can occasionally diverge slightly
>
> ```
>
> from ray, due to small floating-point errors.
>
> ```
> If the origin of the ray is inside the box, this method returns true and the intersection point is set to the origin of the ray,
>
> ```
>
> accordingly to the definition above.
>
> ```
> Parameters:
>     ray - The ray
>     box - The box
>     intersection - The intersection point (optional)
> Returns:
>     Whether an intersection is present.
>
> ```

Hence you should be able to define a bounding box and shoot a ray from object position towards world origin, and get the closest intersection point. This would be the arrow end position; arrow start is (0,0). If you work on 2D, the depth dimension (or one of the 3 dimensions) and it's values should be irrelevant in the whole, 3D -\> 2D should remain consistent.
> 0 votes

# Answer
I solved my problem by using `Intersector.intersectLines` method.

Basically the first line is the segment between object and screen center. Then i use an if else to check which side of the screen rectangle is intersecting the first segment.

Too bad that Intersector class doesn't have this method!

Storwind's answer `Intersector.intersectRayBounds` seemed ok, but for some reasons it didn't work, maybe because it is expecially for 3d geometry.
> 0 votes

---
Tags: libgdx, geometry, viewport
---


title: Recognizing runes drawn by user

text:
# Question
Title: Recognizing runes drawn by user
I want to implement a system where the player can draw runes on the screen with multiple gestures. Meaning its not just one motion it can be up to 3. So far I have implemented the $P Recognizer . In the example it works great and is exactly what I want. But its made with .Net 4.0 and the dll does not work with unity. I eventually managed to get it working by compiling down to 3.5. The problem is that the integration in unity does not work well at all. It recognizes the shape but when I draw wrong symbols it recognizes them as well. I'm completely lost as how to proceed fixing this. Here is my code that handles the integration.

```
if (Input.GetMouseButtonDown(0))
        {
            clone = Instantiate(trailHolderPrefab, transform.position, Quaternion.identity) as GameObject;
            clone.transform.SetParent(transform);
            i++;
        }
        if (Input.GetMouseButton(0))
        {

            points.Add(new Point(Input.mousePosition.x, Input.mousePosition.y, i));

            Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
            Vector3 pos = r.GetPoint(_distance);
            transform.position = pos;
        }
        if(Input.GetMouseButtonUp(0))
        {

            if(i>=3)
            {
                i = 0;
                Point[] _points = points.ToArray();
                Gesture candidate = new Gesture(_points);
                string gestureCLass = PointCloudRecognizer.Classify(candidate, trainingSet);
                spellname.text = gestureCLass;
            }
            clone.transform.parent = null;
            clone.GetComponent<TrailRenderer>().autodestruct = true;

          // GestureXML.GestureIO.WriteGesture(_points, "Triangle",Application.persistentDataPath+"test"+i.ToString()+".xml");
        }

```

# Answer
> 5 votes
Because you need it to be picky (like a security code \<- *hint* *hint*) use a more low-tech method.

Divide your rune drawing area into a grid of NxN (5x5 works well, 3x3 for a very small rune selection).

Consider the strike to hit the area only when it is within a certain distance from the center of the grid cell.

Record the cell hits in order as a string (e.g.: "E0D1C2B3A4,C1B2C3D2C1" below) compare the string to the valid runes.

You can (should) display a pattern to help the players line up their strokes. You can disguise it as some occult pattern in the style of the game.

Otherwise you may have to first rescale the gesture grid to fit the drawn area (or vice-versa) but that would limit you to edge-to-edge rune patterns.

---

Another method (below) is to only record the *direction* of the strokes with the distance filtered out regardless of the starting point: (north, north-west, west, east)

The difficult part is properly filtering out the bounces between directions. One way is to use 8 directions for the rune but detect 16 (north, NNW, north-west, NWW, west, ...) and retain the previous one-in-8 direction when you hit the in-between directions. And use a drag distance threshold before recording a direction.

So if you detect (N, NNW, NW, NNW, NW, NWW, W, E) the output will be (N, N, NW, NW, NW, NW, W, E) then filter out the duplicates giving you (N, NW, W, E).

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


# Question
Title: How to address raycast failures due to tiny holes in a mesh?
**Problem:**

I have a racing circuit that is made out of tiles, each of which is made out of 2 triangles. I need to know over which tile my craft is hovering on; but since there are tiny holes between some of the tiles, casting a ray fails sometimes.

Note: fixing the mesh from within a 3D modeler **is not** an option.

**Question:**

Is there a robust method for approaching this problem ?

# Answer
As DMGregory has pointed out in the comment, you can use SphereCast instead. A spherecast works a lot like a raycast, only that instead of checking for hits in a single line, it has a 'radius' parameter which defines the size of the sphere, effectively making it behave like a thick ray.

Example:

```
RaycastHit hit;

if(Physics.SphereCast(transform.position, 0.1f, Vector3.down, out hit)){
    ...
}

```

You can easily change your code by replacing `Physics.Raycast` with `Physics.SphereCast`, and passing a float value after the `origin` parameter depending on how big the holes are.
> 2 votes

# Answer
The only solution I can think of is to use two or more raycasts that are placed close together but not in the same position. That way if one misses due to a mesh seam, the other should hit.
> 0 votes

---
Tags: unity, raycasting, mesh
---


# Question
Title: When accessing components, is it better to do so in a script or to create a reference to them in the inspector?
I am accessing the variable of one script from within another and I noticed there are multiple ways to do this, but two that are very similar. The first is to simply find the game object and reference it within the other script like so:

```
void Start(){
    private int bye = 1;
    GameObject player = GameObject.Find("Meh");
    Test2 externalScript = player.GetComponent<Test2>();
    externalScript.hello *= bye;
    Debug.Log(externalScript.hello);
}

```

The other way is to create a global instance of the object the script is attached to and reference it within the inspector, like so:

```
private int bye = 1;
public GameObject player;
void Start(){
    Test2 externalScript = player.GetComponent<Test2>();
    externalScript.hello *= bye;
    Debug.Log(externalScript.hello);
}

```

Which way would be best in terms of performance and practice? Would one way be better than the other when it comes to larger games and/or scripts?

# Answer
> 3 votes
You can actually do one better. If it's the `Test2` component you care about, then make that the type of the inspector variable you expose:

```
private int bye = 1;
public Test2 playerTestScript;
void Start(){
    playerTestScript.hello *= bye;
    Debug.Log(playerTestScript.hello);
}

```

This way you have absolutely no searching to do at runtime. Everything is wired-up in the inspector, and the type information lets the editor enforce valid references.

(In the example in the question, if the `player` GameObject existed but did not have a `Test2` component attached, the editor would still let you assign the reference but you'd get a `NullReferenceException` at runtime when you try to access the `Test2` instance that isn't there. Also, since the type is shown in the field, this advertises to someone unfamiliar with the script exactly what kinds of inputs it needs, making wiring it up less error-prone.)

Overall, I would strongly recommend against looking up GameObjects by name whenever it can be avoided. It's brittle if you ever want to re-use the script in a different context, or want to have two instances referencing different objects, and generally makes it very easy to accidentally introduce bugs when renaming, or changing from objects loaded with the scene to those spawned at runtime (which have their name altered when `Instantiate()`d), or dealing with `Destroy()`ed objects (which still get found by name until the next frame).

Wiring up a reference in the inspector is a bit of work, but no more work than naming an object a very specific string, and unlike the named approach what you need to do is advertised in the inspector fields, rather than hiding in the code.

Lastly, if the component you need to reference will be living on the same object, there's another pattern I like to use:

```
[RequireComponent(typeof(PrerequisiteComponent))]
public class DependentComponent : MonoBehaviour
{
    PrerequisiteComponent _prerequisite;

    void Awake()
    {
         _prerequisite = GetComponent<PrerequisiteComponent>();
    }
}

```

(This is great to use with Renderers, Colliders, Rigidbodies, etc. for scripts that need them)

This is the one case where I prefer a script to wire-up itself: when it can unambiguously identify the component it needs (because it's on the same object) and the `[RequireComponent()]` attribute lets the editor enforce this prerequisite for us, so the level designer doesn't have to remember it.

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


# Question
Title: ScriptableObject not working after build in Unity?
I have a GameObject with a ScriptableObject on it, `stats`. It works fine in editor but when I try to build I get a message,

`A script behaviour (script unknown or not yet loaded) has a different serialization layout when loading.`

What is wrong here?

# Answer
> 1 votes
It turns out, I had changed the ScriptableObject (added a new property) after I'd already created the `.asset` file.

Going to the `.asset` file and re-setting the Script component fixed this. Making a new one would also work.

---
Tags: unity
---


# Question
Title: Rotate sprite along the angle between two objects
Im trying to make flames follow my object, I set the direction for my moving object using the points between it and another object (using static destination for testing).

No matter what I do I cannot use the radians (which I use to set the direction), translate them to degrees, then rotate my flames so it looks like they are following it (like a comet).

What I try:

```
sprite.setPosition(pos.x, pos.y);
radians = Math.atan2(0 - pos.y, 540 - pos.x); //set radians
degrees = radians * 180 / MathUtils.PI; //calculate degrees
fireSprite.setPosition(sprite.getX(), sprite.getY());
fireSprite.setRotation((float)degrees); //rotate according to degrees

```

I move the object like this:

```
pos.x += 200 * Math.cos(radians) * delta;
pos.y += 200 * Math.sin(radians) * delta;

```

Am I missing something in the math? I feel like it should work.

An example of result from calculations:

```
radians: -1.8745297149164084, degrees: -107.4026382478209
radians: -1.1776894171295331, degrees: -67.47663130103584
radians: -2.1756410640936705, degrees: -124.65504723907603
radians: -1.2244578042111383, degrees: -70.15626242087843

```

The flames face the wrong direction, and not in a any sort of pattern I can use to debug my problem.

# Answer
> 1 votes
You can try taking the vector from the ship (or whatever you have) to the target position, then get the angle of that. **libGDX**'s `Vector2` class has most of the methods you need.

Something like this might work for you;

```
// Get these from where ever you have them
Vector2 shipPosition = new Vector2(100, 100);
Vector2 targetPosition = new Vector2(0, 540);

// Calculate the vector from the ship to the target
Vector2 fromShipToTarget = new Vector2(targetPosition).sub(shipPosition);

// Get the angle of the ship-to-target
float angle = fromShipToTarget.angle();

// Set the origin so that the sprite is rotated around its center, not its corner
fireSprite.setOrigin(fireSprite.getWidth() / 2.0f, fireSprite.getHeight() / 2.0f);
fireSprite.setPosition(shipPosition.x, shipPosition.y);
fireSprite.setRotation(angle);

```

The `angle` method on `Vector2` will give you the angle of the vector towards the positive y-axis so if you have two points **(0, 0)** and **(1, 1)** the above example will yield a vector of **45** degrees.

# Answer
> -1 votes
Here is the code I use to get the angle of a 2d vector, hopefully it is what your are looking for. (using our own library functions, most of which should be obvious)

```
float zVec2f::getAngle () const
{
    //straight up, 0.0f degrees
    zVec2f up(0.0f, -1.0f);

    //angle between up vector and our vector
    zVec2f normal = *this;
    if ( normal.normaliseSafe() ) // returns true if it was possible to normalize vector
    {
        float angle = acosf(zDot(normal,up));

        //compensate for the fact that acos only
        //gives us 0->Pi (mirror along 180 degree line)
        if ( x < 0.0f)
        {
            angle += (2.0f * (zPIf - angle));
        }
        zASSERT(angle>=0.0f);
        zASSERT(angle<=zPI2f);

        return angle;
    }
    return 0.0f;
}

```

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


title: game server - fault tolerant

text:
# Question
Title: game server - fault tolerant
If you have for example an MMO with 2000 players, and players are constantly removing / creating / swapping items (and doing some other important things that can't be lost).

If the updates are saved instantly in the database, since they are too many, the database dies. If you save them every "x" minute, there's a window where if your server app dies, players may lose items, and sometimes they may be expensive, let's say 100$, so that can't happen.

Is there a design or a guide I could read that handles this issue? The games I play today do not have that problem.

# Answer
First, nothing is ever saved instantly in an MMO and there is always a delay specifically to keep the database running smoothly. For casual transactions the common delay seems to be 5-30 seconds, not minutes. Certain events like logging out or transitioning between world spaces will force a fast update.

If you watch carefully you'll hear of occasional roll-backs of items when a server area crashes, that delay chosen above is a compromise between optimal server updates and not annoying players too much on the rare crash.

Transactions between players should be handled as such, where the end result is only applied once all conditions of the transaction are complete. This is a standard database concept.

Second, items which cost real money should be handled the same way as a transfer between players. Wait to tell the player about the item until all conditions of the transaction are complete. Maintain a separate log of these kinds of important transactions, a player won't care if he loses 15 seconds of coins gathered but would care a lot if he lost that $100 item.

In the rare case of a database crash the database itself is backed up regularly (daily) and can be restored. At that point the logs you carefully created above that hold the big item transactions can be applied so at the very least the items show up in the player inventory again.
> 1 votes

---
Tags: architecture, server, databases
---


title: Scale a game object to Bounds

text:
# Question
Title: Scale a game object to Bounds
I'm trying to scale a lot of dynamically created game objects in Unity3D to the bounds of a sphere collider, based on the size of their current mesh. Each object has a different scale and mesh size. Some are bigger than the AABB of the collider, and some are smaller. Here's the script I've written so far:

```
private void ScaleToCollider(GameObject objectToScale, SphereCollider sphere) {
    var currentScale = objectToScale.transform.localScale;
    var currentSize = objectToScale.GetMeshHierarchyBounds().size;

    var targetSize = (sphere.radius * 2);

    var newScale = new Vector3 {
        x = targetSize * currentScale.x / currentSize.x,
        y = targetSize * currentScale.y / currentSize.y,
        z = targetSize * currentScale.z / currentSize.z
    };

    Debug.Log("{0} Current scale: {1}, targetSize: {2}, currentSize: {3}, newScale: {4}, currentScale.x: {5}, currentSize.x: {6}",
        objectToScale.name, currentScale, targetSize, currentSize, newScale, currentScale.x, currentSize.x);

    //DoorDevice_meshBase                   Current scale: (0.1, 4.0, 3.0), targetSize: 5, currentSize: (2.9, 4.0, 1.1), newScale: (0.2, 5.0, 13.4), currentScale.x: 0.125, currentSize.x: 2.869114
    //RedControlPanelForAirlock_meshBase    Current scale: (1.0, 1.0, 1.0), targetSize: 5, currentSize: (0.0, 0.3, 0.2), newScale: (147.1, 16.7, 25.0), currentScale.x: 1, currentSize.x: 0.03400017

    objectToScale.transform.localScale = newScale;
}

```

And the supporting extension method:

```
public static Bounds GetMeshHierarchyBounds(this GameObject go) {
    var bounds = new Bounds(); // Not used, but a struct needs to be instantiated

    if (go.renderer != null) {
        bounds = go.renderer.bounds;
        // Make sure the parent is included
        Debug.Log("Found parent bounds: " + bounds);
        //bounds.Encapsulate(go.renderer.bounds);
    }
    foreach (var c in go.GetComponentsInChildren<MeshRenderer>()) {
        Debug.Log("Found {0} bounds are {1}", c.name, c.bounds);
        if (bounds.size == Vector3.zero) {
            bounds = c.bounds;
        } else {
            bounds.Encapsulate(c.bounds);
        }
    }
    return bounds;
}

```

After the re-scale, there doesn't seem to be any consistency to the results - some objects with completely uniform scales (x,y,z) seem to resize correctly, but others don't :|

Its one of those things I've been trying to fix for so long I've lost all grasp on any of the logic :| Any help would be appreciated!

# Answer
## First idea:

**Rescale each object to `(1.0, 1.0, 1.0)` before applying your algorithm**. But then I thought that maybe the objects look good when they are non-uniformly scaled to begin with.

## Second idea:

I think that the problem is that the algorithm is mixing *scale* and *size* values. If your `var newScale = new Vector3(...)` code only works for uniform scales of 1.0, then the `currentScale.<x/y/z>` parts in it could be replaced by `1.0` which means that they are effectively doing nothing.

## Suggestion (which I haven't tried):

Calculating the `targetSize / currentSize` (for each of x,y,z) will give you the `newSizeRatio` for each dimension. Take the minimum of them and multiply the scale vector by it:

```
float newSizeRatioX = targetSize.x / currentSize.x;
float newSizeRatioY = targetSize.y / currentSize.y;
float newSizeRatioZ = targetSize.z / currentSize.z;

float minimumNewSizeRatio = Math.Min(newSizeRatioX, Math.Min(newSizeRatioY, newSizeRatioZ));

Vector3 newScale = currentScale * minimumNewSizeRatio;

```

I believe this will work because:

* Multiplying all dimensions with the same ratio will probably produce a uniformly scaled object.
* Multiplying with the minimum ratio will guaranty that the object will fit inside the circle.

I hope this works :-)
> 2 votes

# Answer
use a mesh collider instead !

i just had the same problem.

but then i just used a mesh collider instead of a sphere collider and the problem almost solved itself

just be sure to update the mesh collider shared mesh as well:

```
var meshInstance = Instantiate(meshes[type]);
gameObject.GetComponent<MeshFilter> ().mesh = meshInstance;
gameObject.GetComponent<MeshCollider> ().sharedMesh = meshInstance;

```
> 1 votes

---
Tags: c#, unity, aabb, scale
---


# Question
Title: CPU and RAM usage in OpenGL too high in Swift
My game is set up so the the display controls the game loop, usual in Cocoa. The callback function calls `run()` which is this. The thing is, the thread running the callback is using 63% CPU and the RAM is constantly rising, slowly (memory leak?). I fixed it up a bit, before RAM used was 2.32 GB. The code in question is meant to draw one rotating emoji on the screen, which it does.

```
func run(){
    update()
    render()
}

```

Where `render()` calls `draw()` for all GameObjects is this:

```
func draw(graphic: Graphic2D) {

    programID = 0
    vaoID = 0
    vboID = 0
    eboID = 0
    vertexShader = 0
    fragmentShader = 0

    let vertices: [GLfloat] = [ -0.25, -0.25, graphic.colors[0].r, graphic.colors[0].g, graphic.colors[0].b, graphic.colors[0].a, 0.0, 0.0,
                                -0.25,  0.25, graphic.colors[1].r, graphic.colors[1].g, graphic.colors[1].b, graphic.colors[1].a, 0.0, 1.0,
                                 0.25,  0.25, graphic.colors[2].r, graphic.colors[2].g, graphic.colors[2].b, graphic.colors[2].a, 1.0, 1.0,
                                 0.25, -0.25, graphic.colors[3].r, graphic.colors[3].g, graphic.colors[3].b, graphic.colors[3].a, 1.0, 0.0 ]

    let indices: [GLuint] = [ 0, 1, 2,
                              2, 3, 0 ]

    let translationMat = GLKMatrix4Translate(GLKMatrix4Identity, graphic.position.x, graphic.position.y, 0)
    let rotationMat = GLKMatrix4RotateZ(GLKMatrix4Identity, graphic.rotation)
    finalTransform = GLKMatrix4Multiply(translationMat, rotationMat)

    let texURL = NSBundle.mainBundle().URLForResource(graphic.textures[0].pathName, withExtension: graphic.textures[0].fileType)

    let texInfo: GLKTextureInfo? = try? GLKTextureLoader.textureWithContentsOfURL(texURL!, options: [GLKTextureLoaderGenerateMipmaps : 1 , GLKTextureLoaderOriginBottomLeft : 1])

    var shaderSource: String

    glGenBuffers(1, &vboID)
    glGenBuffers(1, &eboID)

    glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR)
    glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GL_LINEAR)
    glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GL_CLAMP_TO_EDGE)
    glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GL_CLAMP_TO_EDGE)

    glGenVertexArrays(1, &vaoID)

    vertexShader = glCreateShader(GLenum(GL_VERTEX_SHADER))
    fragmentShader = glCreateShader(GLenum(GL_FRAGMENT_SHADER))

    shaderSource = graphic.shaders.vertexShader
    var vsptr = getShaderRef(shaderSource)
    glShaderSource(vertexShader, 1, &vsptr, nil)
    glCompileShader(vertexShader)

    var success: GLint = 0
    glGetShaderiv(vertexShader, GLbitfield(GL_COMPILE_STATUS), &success)
    if success <= 0 { Swift.print("ERROR O00:: vertex shader compile error")
                      Swift.print(shaderSource)}

    shaderSource = graphic.shaders.fragmentShader
    var fsptr = getShaderRef(shaderSource)
    glShaderSource(fragmentShader, 1, &fsptr, nil)
    glCompileShader(fragmentShader)

    glGetShaderiv(fragmentShader, GLbitfield(GL_COMPILE_STATUS), &success)
    if success <= 0 { Swift.print("ERROR O01:: fragment shader compile error")
                      Swift.print(shaderSource)}

    programID = glCreateProgram()

    glAttachShader(programID, vertexShader)
    glAttachShader(programID, fragmentShader)
    glLinkProgram(programID)

    glGetProgramiv(programID, GLbitfield(GL_LINK_STATUS), &success)
    if success <= 0 { Swift.print("ERROR O02:: program compile error") }

    glDetachShader(programID, vertexShader)
    glDetachShader(programID, fragmentShader)

    glDeleteShader(vertexShader)
    glDeleteShader(fragmentShader)

    glBindVertexArray(vaoID)

        glBindBuffer(GLenum(GL_ARRAY_BUFFER), vboID)
        glBufferData(GLenum(GL_ARRAY_BUFFER), vertices.count * sizeof(GLfloat), vertices, GLenum(GL_STATIC_DRAW))

        glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), eboID)
        glBufferData(GLenum(GL_ELEMENT_ARRAY_BUFFER), indices.count * sizeof(GLuint), indices, GLenum(GL_STATIC_DRAW))

        glVertexAttribPointer(0, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 32, UnsafePointer<GLuint>(bitPattern: 0))
        glEnableVertexAttribArray(0)

        glVertexAttribPointer(1, 4, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 32, UnsafePointer<GLuint>(bitPattern: 8))
        glEnableVertexAttribArray(1)

        glVertexAttribPointer(2, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 32, UnsafePointer<GLuint>(bitPattern: 24))
        glEnableVertexAttribArray(2)

    glBindVertexArray(0)

    glActiveTexture(GLenum(GL_TEXTURE0))
    if texInfo != nil {
        glBindTexture(texInfo!.target, texInfo!.name)
    }

    let transLocation = glGetUniformLocation(programID, "transform")

    glUseProgram(programID)

    glBindVertexArray(vaoID)

    glUniformMatrix4fv(transLocation, 1, 0, finalTransform.array)
    glDrawElements(GLenum(GL_TRIANGLES), 6, GLenum(GL_UNSIGNED_INT), UnsafePointer<Void>(bitPattern: 0))

    glBindVertexArray(0)

    if texInfo != nil {
        var name = texInfo?.name
        glBindTexture(texInfo!.target, 0)
        glDeleteTextures(1, &name!)
    }

    glDeleteVertexArrays(1, &vaoID)
    glDeleteBuffers(1, &vboID)
    glDeleteBuffers(1, &eboID)
    glDeleteProgram(programID)

}

```

# Answer
> 3 votes
The first issue is that you are re-creating and destroying the buffers, reloading the texture, and recompiling the shader on every single draw loop.

This is the source of the huge CPU usage.

As for the memory going up, there could be a memory leak in the scripting language you are using.

Not recreating everything on every loop will probably reduce the impact to practically nothing.

Create a LoadEverything() function that is called once when your program start.

Cheers,

---
Tags: opengl, game-loop, memory-efficiency, swift
---


# Question
Title: intellectual property and non disclosure agreements on artwork
I am developing a game and would like to work with an artist. I am interested to know what other developers have done with regards to creating characters. How does one draft up agreements that might be fair to both parties?

What I think might be good is: give the artist proper attribution and the right to display the work in portfolio, and agreement to pay the commission fee for the work, but let the game designer (the commissioner of the art) own the character and can do what he/she wants with the character in the future, including choose another artist if desired.

Just wondering how other people might have done it.

# Answer
> 2 votes
You should look up "work for hire." It's a common contractual term that describes the agreement you're looking for. I also recommend talking to a lawyer to draw up the contract for you. Any lawyer should understand what "work for hire" means.

---
Tags: legal, art
---


# Question
Title: How to achieve a sheet of paper unfolding from the center in XNA 2D?
I need to create an effect like a folded sheet of paper unfolding.

I was thinking about transforming an image so it "scales" from the center to the borders by cutting the image in half and scaling both parts to create this effect.

Is there a better way?

# Answer
If you want to accomplish something like this:

You can do this pretty easily. If you create 3 different gameobjects, each with a SpriteRenderer:

The Gameobject on the left, has a blank image with a pivot set to TopLeft. The Gameobject on the right, has the same image, however, the pivot is set to the TopRight.

Re-position these gameobjects, so that they are over top the Center object:

Then all you have to do is attach a script like this to both Blue gameobjects:

```
bool Opening = true;

void Update () {
    if (Opening) {
        transform.localScale = new Vector2 (transform.localScale.x - (0.5f * Time.deltaTime), transform.localScale.y);
        if (transform.localScale.x < -0.5f) {
            transform.localScale = new Vector2 (-0.5f, transform.localScale.y);
            Opening = false;
        }
    }
}

```
> 1 votes

# Answer
Take a look at this overload of the `SpriteBatch.Draw()` method. What you want to do is have the `origin` argument be a `Vector2` with its x-coordinate set to half the width of your final image (and whichever y-coordinate you feel is appropriate), and increase the `scale` argument from `(0,1)` to `(1,1)` over the course of time it takes to "unfold" the paper.

Since unfolding paper occurs in 3D, and moves (roughly) like the arc of a circle, what you might consider doing is setting the x-coordinate of `scale` use cosine to regulate its movement. Your code should end up looking something like this:

```
// In your initialization code:
Vector2 origin = new Vector2(paperObject.Width/2f, 0);
// In your Update():
unfoldTimer += gameTime.ElapsedGameTime.Milliseconds;
paperScale = new Vector2(Math.Cos(unfoldTimer/UnfoldTime * Math.PI * 0.5d), 1);

```

Note that this is only an approximation of what unfolding would look like, and it's probably the closest you're going to get by just scaling.
> 0 votes

---
Tags: xna, 2d
---


# Question
Title: unity - get component variable from object in trigger
i want to get a component value from the game object which collides with my trigger's object script. this is my code on the trigger:

```
 void OnTriggerEnter (Collider obj){
     if(obj.GetComponent<motor>().enabled == true){
         passed = true;
     }
 }

```

and this is the error i get:

```
NullReferenceException: Object reference not set to an instance of an object
 cp.OnTriggerEnter (UnityEngine.Collider obj) (at Assets/Scripts/cp.cs:15)

```

also when changing the code on the trigger:

```
 motor mObj = obj.gameObject.GetComponent();
    if(mObj != null){
         //code here
         Debug.Log("mObj not null");
     }else{
             Debug.Log("mObj is null");
     }

```

it returns

> mObj is null

but the parent obj does have that 'motor' script, other scripts in the car which enter the trigger can access it

# Answer
```
void OnTriggerEnter (Collider obj){
     if(obj.GameObject.GetComponent<motor>().enabled == true){
         passed = true;
     }
 }

```

adding this GameObject --\> obj.GameObject.GetComponent().enabled would just work :)

let me know if it works
> 3 votes

# Answer
Make the following changes to the code.

```
    motor mObj = obj.gameObject.GetComponent<motor>();
    if(mObj != null){
         //code here
         Debug.Log("mObj not null");
     }else{
             Debug.Log("mObj is null");
     }

```

On trigger will only work if the game object to which this script is attached have a collider. It won't work if only the children have colliders.
> 0 votes

# Answer
i found that it must be the wheel collides or some other child causing the issue anyway here is the code i now use

```
    void OnTriggerEnter (Collider obj){

    motor mObj = obj.transform.parent.gameObject.GetComponent<motor>();
    if(mObj != null){
        //code here
        Debug.Log("mObj not null");
        if(mObj.enabled == true){
            Debug.Log("cp passed");
        passed = true;
        }
    }else{
        Debug.Log("mObj is null");
    }

}

```

thank you for helping
> 0 votes

---
Tags: unity
---


title: Simplifying Object Factory

text:
# Question
Title: Simplifying Object Factory
I'm making a game for Android using Libgdx with Android Studio in Java. In my game, I have a class called ObjectFactory which has a method createGameObject(int objectType) which receives an integer from ObjectIds (a static class that hold a final static numbers for every object type: PLAYER = 0, BULLET = 1, ENEMY = 2 and etc...).

This method has a switch condition and 'till now I have reached 69 types of objects. The method gets the id, looks for it using the switch, creating that object and returns it. At the beginning it was comfortable using this way, but now it's really annoying looking for stuff over there because the switch statement is huge. This is an example of a case:

```
        case Rules.GameObjectIds.EXPLOSION:
            Explosion explosion = Pools.obtain(Explosion.class);
            explosion.init(getTextureAtlas(explosion, AssetsPaths.Gfx.Sheets.Misc.Explosion.DATA_FILE), AssetsPaths.Gfx.Sheets.ImagesNames.BIG_EXP, x, y, AssetsPaths.Configs.ParticleEffects.EXPLOSION);
            explosion.setDistanceInteraction(Rules.Misc.Explosion.BLAST_RADIUS);
            gameObject = explosion;
            listName = Rules.System.GameObjectTypes.EXPLOSIONS;
            createEffect(AssetsPaths.Configs.ParticleEffects.BLAST_RING, gameObject);
            createLight(explosion);
            break;

```

I'm thinking about a way to simplify the Object Factory, any suggestions? Thanks in advance

# Answer
> 1 votes
The nice thing about the Factory pattern is that the base class can be abstract and you can have different derived Factory classes.

That means you can have an `ExplosionFactory`, a `BulletFactory`, an `EnemyFactory` and so on, which all inherit from the basic class `GameObjectFactory`. Any code which is common to all objects would be in the GameObjectFactory while the derived classes only do what's unique to that particular object type and call a method from the base-class to do the rest.

An abstract base-class doesn't need to know anything about the classes derived from it. So when you want to add a new factory, you don't need to edit the base-class at all. You could even ditch that `Rules.GameObjectIds` enum.

When you want to create an object of the specific type, you just get an instance of a factory of the desired type.

You can also make your factories type-safe by declaring the GameObjectFactory as a generic class and the derived class as an extensions with a more specific type:

```
public abstract class GameObjectFactory<T extends GameObject> {

     public T createGameObject() { ...
}

public class ExplosionFactory extends GameObjectFactory<Explosion> {

     @Override
     public Explosion createGameObject() { ...
}

```

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


# Question
Title: Signed Distance Fields: How are different colour channels used to improve output of sharp corners?
The naive approach to implementing signed distance field font rendering suffers quality issues where sharp corners get softened (either outward- or inward-facing corners, i.e. convex or concave corners).

Step-by-step, just how are a second and third channel used to improve the final output? How are these channels produced, as compared with a single channel (for which the process is straightforward)?

# Answer
I have solved this exact problem for my master's thesis over a year ago and have already talked about it here. Yesterday, I released an open source program with my multi-channel distance field construction algorithm, **msdfgen**, which you can try out right now.

It is available on GitHub: https://github.com/Chlumsky/msdfgen

If you are interested in how it works, I will be also publishing a short paper about the method soon, or you can examine the source code. Here is a preview of how it compares to monochrome distance fields, but it really depends on the particular font and other factors.
> 6 votes

# Answer
One distance field cannot represent sharp corners, because within the space between 4 samples (i.e. inside each "square pixel", even though pixels are not little squares), the value of the distance field is a quadratic function due to bi-linear interpolation. This class of quadratics cannot represent sharp corners well, because they are polynomials and cannot have their derivatives change quickly enough (except in a few pathological cases, but these are not general enough to be useful).

It is easy to make sharp corners on the border between regions, on the gridlines connecting samples, because here the samples which are used change abruptly. You can see this on the last page of this paper from Valve.

By using two channels, and thus two functions, we can have two lines (or curves, in the general case), in each cell. Then, as long as there is only one corner per cell, we can easily define two lines whose intersection is at the corner we seek. Using two channels, we can use AND of the two regions to define convex corners. If we assume + is outside, and - is inside, then AND is the same as taking the MAX of both channels, after interpolation. The max function can have sharp corners, even if the two functions it operates on are smooth.

We could use OR to get sharp concave corners. And with clever uses of three channels, we could use both AND and OR to get concave and convex corners in the same image. Of course, setting up those two or three channels to get the desired effect is quite complicated.
> 2 votes

---
Tags: opengl, directx, algorithm, signed-distance-field, image-processing
---


# Question
Title: OpenGL [LWJGL3] - Matrix4x4 not rotating correctly
I tried today to make my own matrix4f class because of that LWJGL 3 does not include a class for it. So I arrived at rotation and it does not seem to work. I tried using the old util from LWJGL 2 and then it worked fine. Here's a screenshot of how it looks like.

Here's a gif animation of how it looks. It's supposed to be a cube but as you can see it stretches when it rotates. Not only the x axis but the y and z axis to. Here's the code:

```
public Matrix4f rotate(Vector3f rotation) {
    Matrix4f xRotation = new Matrix4f();
    xRotation.setIdentity();

    float x = rotation.x;
    float y = rotation.y;
    float z = rotation.z;

    xRotation.m11 = (float) cos(x);
    xRotation.m21 = (float) -sin(x);

    xRotation.m12 = (float) sin(x);
    xRotation.m22 = (float) cos(x);

    Matrix4f yRotation = new Matrix4f();
    yRotation.setIdentity();

    yRotation.m00 = (float) cos(y);
    yRotation.m20 = (float) sin(y);

    yRotation.m02 = (float) -sin(y);
    yRotation.m22 = (float) cos(y);

    Matrix4f zRotation = new Matrix4f();
    zRotation.setIdentity();

    zRotation.m00 = (float) cos(z);
    zRotation.m10 = (float) -sin(z);

    zRotation.m01 = (float) -sin(z);
    zRotation.m11 = (float) cos(z);

    return multilpy(xRotation).multilpy(yRotation).multilpy(zRotation);
}

```

Can someone point the problem because I cannot find it.

Edit: The multiplication and the projection code:

```
public Matrix4f multilpy(Matrix4f matrix) {
    // Row 0
    m00 = m00 * matrix.m00 + m10 * matrix.m01 + m20 * matrix.m02 + m30 * matrix.m03;
    m10 = m00 * matrix.m10 + m10 * matrix.m11 + m20 * matrix.m12 + m30 * matrix.m13;
    m20 = m00 * matrix.m20 + m10 * matrix.m21 + m20 * matrix.m22 + m30 * matrix.m23;
    m30 = m00 * matrix.m30 + m10 * matrix.m31 + m20 * matrix.m32 + m30 * matrix.m33;

    // Row 1
    m01 = m01 * matrix.m00 + m11 * matrix.m01 + m21 * matrix.m02 + m31 * matrix.m03;
    m11 = m01 * matrix.m10 + m11 * matrix.m11 + m21 * matrix.m12 + m31 * matrix.m13;
    m21 = m01 * matrix.m20 + m11 * matrix.m21 + m21 * matrix.m22 + m31 * matrix.m23;
    m31 = m01 * matrix.m30 + m11 * matrix.m31 + m21 * matrix.m32 + m31 * matrix.m33;

    // Row 2
    m02 = m02 * matrix.m00 + m12 * matrix.m01 + m22 * matrix.m02 + m32 * matrix.m03;
    m12 = m02 * matrix.m10 + m12 * matrix.m11 + m22 * matrix.m12 + m32 * matrix.m13;
    m22 = m02 * matrix.m20 + m12 * matrix.m21 + m22 * matrix.m22 + m32 * matrix.m23;
    m32 = m02 * matrix.m30 + m12 * matrix.m31 + m22 * matrix.m32 + m32 * matrix.m33;

    // Row 3
    m03 = m03 * matrix.m00 + m13 * matrix.m01 + m23 * matrix.m02 + m33 * matrix.m03;
    m13 = m03 * matrix.m10 + m13 * matrix.m11 + m23 * matrix.m12 + m33 * matrix.m13;
    m23 = m03 * matrix.m20 + m13 * matrix.m21 + m23 * matrix.m22 + m33 * matrix.m23;
    m33 = m03 * matrix.m30 + m13 * matrix.m31 + m23 * matrix.m32 + m33 *    matrix.m33;

    return this;
}

public static Matrix4f perspective(int width, int height, int fov, float zFar, float zNear) {
    Matrix4f matrix = new Matrix4f();

    float aspectRatio = (float) width / (float) height;
    float fovY = (float) ((1f / tan(Math.toRadians(fov / 2f))) * aspectRatio);
    float fovX = fovY / aspectRatio;
    float frustum_length = zFar - zNear;

    matrix.m00 = fovX;
    matrix.m11 = fovY;
    matrix.m22 = -((zFar + zNear) / frustum_length);
    matrix.m23 = -1;
    matrix.m32 = -((2 * zNear * zFar) / frustum_length);
    matrix.m33 = 0;

    return matrix;
}

```

Vertex Shader:

```
#version 400 core

in vec3 position;
in vec2 textureCoord;

out vec2 textureCoords;

uniform mat4 tranformation;
uniform mat4 projection;

void main(void) {

    gl_Position =  projection * tranformation * vec4(position,1.0);

    textureCoords = textureCoord;
}

```

Fragment Shader:

```
#version 400 core

in vec2 textureCoords;

out vec4 out_Color;

uniform sampler2D sampler;

void main(void) {
    vec4 color = texture(sampler, textureCoords);

    //if(color.a < 0.5) discard;

    out_Color = texture(sampler, textureCoords);
}

```

# Answer
> 0 votes
The problem is your multiplication code. When you do:

```
m00 = m00 * matrix.m00 + m10 * matrix.m01 + m20 * matrix.m02 + m30 * matrix.m03;

```

You change `m00`, so you are not allowed to reuse it later in that function. Same for `m01` and all the other ones. Use temporary values instead:

```
float temp_m00 = m00 * matrix.m00 + m10 * matrix.m01 + m20 * matrix.m02 + m30 * matrix.m03;

```

Also, as suggested in the comments, try to use arrays instead of the `m00` `m01` etc. notation; you will have much shorter code and it will be easier to debug.

# Answer
> 0 votes
Your z rotation is messed up, it should be negative at (0; 1), and positive at (1; 0)

---
Tags: opengl, java, glsl, lwjgl
---


# Question
Title: Animator.Play() only works the first time
I am creating a game in Unity 3d that is using an animation to move an object. For some reason the animation only works the first time it is accessed and from then on it acts as if it is not being called even though I have debugged and I see that it is being called. Here is the code I use to call the animation:

```
if (anim == null)
{
    foreach (Transform component in myObject.transform)
    {
        anim = components.GetComponent<Animator>();
    }
}
anim.Play("Flip-Forward");
anim.enabled = true;

```

As you can see I have an animator connected to myObject that I access in order to plan an animation. "Flip-Forward" is one of the animations I have created.

# Answer
> 3 votes
Animator.Play() works with the state in the Animator not the actual animation. I'm guessing you are not returning from the Flip-Forward state. Make sure to create a transition from to that state back to the default state and that the transition Has Exit Time property be ticked.

This is a simple example of how the state machine should look. However I suggest that you use triggers on the transitions between states rather than playing the states directly. Also make sure to pass 0 to the Play() method after the state name to ensure you are using the base layer.

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


# Question
Title: How to display sprites on a 2D canvas, using Unity 5 and C#
I want to show a mini-map on the screen, but I don't have any idea to how to paint something in a panel on a canvas by code. The mini-map would look like this prototype I made some time ago, in Visual Studio.

I've tried instantiating a prefab image, but couldn't get it to work. I have two problems.

Firstly, I have 25 `Image` objects created in the scene, and 25 in the `PlayerController` script, but I can't get it to change the sprite. I am currently declaring them as follows:

```
public Image minimap0, minimap1, minimap2, minimap3, minimap4, minimap5,
        minimap6, minimap7, minimap8, minimap9, minimap10, minimap11,
        minimap12, minimap13, minimap14, minimap15, minimap16, minimap17,
        minimap18, minimap19, minimap20, minimap21, minimap22, minimap23,
        minimap24;

```

Lastly, I don't know how to change all 25 object sprites with a `for` loop, similar to the code that follows:

```
public void DrawMiniMap() {
    // mapXCord = miniMapPanel.transform.position.y;
    // mapXCord = 0;
    // mapYCord = 0;

    mapY = playerYPost - 2;
    int contadorArray = 0;
    Vector2 position = new Vector2 (mapXcord, mapYCord);

    for(int i = 0; i < 5; i++) {
        mapX = playerXPos - 2;
        string actualMiniMap = "minimap" + contadorArray;

        // mapXCord = miniMapPanel.transform.position.x;

        for(int j = 0; j < 5; j++) {
            position = new Vector2 (mapXCord, mapYCord);

            if (MapCreator.mapa [mapX, mapY] == 0) {
            } else if (MapCreator.mapa [mapX, mapY] == 1) {
            } else if (mapX == playerXPos && mapY == playerYPos) {
                if (playerOrientation == 'n') {
                } else if (playerOrientation == 'e') {
                } else if (playerOrientation == 's') {
                } else if (playerOrientation == 'w') {
                }
            }
            // mapXCord += 15;
            contadorArray += 1;
        }
        // mapYCord += 15;
    }
}

```

The map is stored in an array for checking positions.

# Answer
> -1 votes
Under canvas create empty GameObject, add Image component, assign sprite to Image.sprite

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


# Question
Title: How do I communicate that something is a tutorial button
I made an (ios) arcade game that is rather unconventional, and as a result many people wont exactly know what to do or what the controls are when they first open it. As a results I have had to add a rectangular "Tutorial" button on my main menu screen so that when I hand it to people, or other people hand it to people (etc) its all ok. FYI: When the game first opens it does go to a tutorial, I just wanted it to be accessible for repeats if necessary

In the original build I designed all the buttons and had labels on them, however the artist inside of me says that doesn't look good, so I had a friend redesign them.

The new buttons are bi-colored and very minimalist (usually with the outline of a shape in them). We came up with simbols that work for "return", "play", and "leaderboard" that work... however we can not come up with one for "tutorial".

What would be a clear symbol that could be put on a "tutorial" button?

Here is a picture of the screen. That grey shape is meerly a placeholder. The button on the top right opens a "Credits" page.

# Answer
The most common glyph/icon I've seen for a tutorial is a Question Mark (?), although of course this can also mean a more general 'help' area. Other icons I have seen are a book or a blackboard.

To give anything more specific than that, I'd have to know more about what sort of game it is, what other icons you're using.
> 1 votes

# Answer
There is a common image used for a tutorial. Use it.

(But not this one...this one I grabbed off of google at http://wiki.minetest.net/images/thumb/3/3b/Tutorial\_logo.png/150px-Tutorial\_logo.png)
> 1 votes

---
Tags: touch, interface
---


title: Bullet: No Bouncing off the walls

text:
# Question
Title: Bullet: No Bouncing off the walls
I'm using Bullet Physics for Collision Detection in a first person game. The collision basically work fine, I cannot walk through objects. But if I walk against the wall and release the key I get bounced back and automatically move backwards. This is something I do not want. The player should not be bouncing off when walking into a wall, it just shouldn't be possible to pass through it.

Here are some code snippets.

Creating the Player-RigidBody (class Camera):

```
btCollisionShape* _collisionShape = new btCapsuleShapeZ(0.2f, 1.0f);
btDefaultMotionState* _motionState = new btDefaultMotionState(btTransform(
    btQuaternion(1, 0, 0, 1),
    btVector3(_position.x, _position.y, _position.z)
    ));
btRigidBody::btRigidBodyConstructionInfo cameraRigidBodyCI(
    10,
    _motionState,
    _collisionShape,
    btVector3(0, 0, 0)
    );
_rigidBody = new btRigidBody(cameraRigidBodyCI);
_rigidBody->setActivationState(DISABLE_DEACTIVATION);

```

Creating the RigidBody of the Walls and other box-objects:

```
btVector3 rigidBodyPos;
btCollisionShape* collisionShape;
glm::vec3* minMax = getMinMaxVertexCoords();
glm::vec3 minCoords = minMax[0];
glm::vec3 maxCoords = minMax[1];
glm::vec3 middleSize = glm::vec3((maxCoords.x - minCoords.x) / 2, (maxCoords.y - minCoords.y) / 2, (maxCoords.z - minCoords.z) / 2);
glm::vec3 middlePos = glm::vec3((maxCoords.x + minCoords.x) / 2, (maxCoords.y + minCoords.y) / 2, (maxCoords.z + minCoords.z) / 2);

collisionShape = new btBoxShape(btVector3(middleSize.x, middleSize.y, middleSize.z));
rigidBodyPos = btVector3(middlePos.x, middlePos.y, middlePos.z);

btMotionState* motionState = new btDefaultMotionState(btTransform(
    btQuaternion(0, 0, 0, 1),
    rigidBodyPos
    ));
btRigidBody::btRigidBodyConstructionInfo* rigidBodyCI = new btRigidBody::btRigidBodyConstructionInfo(
    0,
    motionState,
    collisionShape,
    btVector3(0, 0, 0)
    );
if (_rigidBody != nullptr){
    delete _rigidBody;
    _rigidBody = nullptr;
}
_rigidBody = new btRigidBody(*rigidBodyCI);
_rigidBody->setActivationState(DISABLE_DEACTIVATION);
_rigidBody->setRestitution(0.0f);

```

The Collision-Detection itself:

```
dynamicsWorld->updateAabbs();
dynamicsWorld->stepSimulation(1 / 60.f, 10);
//...
btTransform cameraTrans = camera->getRigidBody()->getWorldTransform();
camera->setPosition(glm::vec3(cameraTrans.getOrigin().getX(), cameraTrans.getOrigin().getY(), cameraTrans.getOrigin().getZ()));

```

How can I change this behaviour?

# Answer
It's possible the player object moves into a wall and the position is updated, then collision is detected and the players position is then corrected creating a "bouncing" effect. To correct this, compute your collisions prior to moving the player (or probably any object).
> 1 votes

---
Tags: c++, collision-detection, bullet-physics, rigid-body-dynamics
---


# Question
Title: Creating a set of islands by subtracting gradient values from a Perlin noise
The answers to this question explains fairly well how to create a big island in the center of the screen by setting up a gradient and then subtracting its value from a Perlin Noise.

Anyway they explain how to create only one gradient at the center of the screen to create a big, sort of circular island.

But what if I want to create an island which has more than one gradient to create a less regular shape, or if I want to create multiple separated islands by setting multiple gradients in different positions? What value should I subtract from the Perlin Noise function for each point? The sum of the distance from each gradient to that point? The average?

Edit: Jon's method of multiplying and normalizing worked, got this result with 4 gradient points:

# Answer
> 3 votes
You can blend noise together easily, the concept is pretty simple. You essentially loop through each noise value, and perform an operation on the data, and then save the result. It is also a good idea to normalize this data as it makes it easier to use for future operations.

Here is a simple container class to hold resulting noise data:

```
public class MapData {

    public float[,] Data;
    public float Min { get; set; }
    public float Max { get; set; }

    public MapData(int width, int height)
    {
        Data = new float[width, height];
        Min = float.MaxValue;
        Max = float.MinValue;
    }
}

```

Using this class, we can generate and store our noise data. You don't have to use this, but it makes it easier to have something to manage your generated noise data. We will use this to blend the gradients together:

```
blendData = new MapData (Width, Height);

```

Grab your data and blend it, keeping track of your upper/lower limits:

```
// first pass - blend gradient values
for (var x = 0; x < Width; x++) {
    for (var y = 0; y < Height; y++) {

        // Get both gradient values
        float gradValue1 = (float)GradientMap1.Get (nx, ny);
        float gradValue2 = (float)GradientMap2.Get (nx, ny);

        // Multiply
        float blendValue = gradValue1 * gradValue2;

        // keep track of the max and min values found
        if (blendValue > blendData.Max) blendData.Max = blendValue;
        if (blendValue < blendData.Min) blendData.Min = blendValue;

        blendData.Data[x,y] = blendValue;
    }
}

```

Normalize the resulting data, so that you don't have crazy values to deal with in the future:

```
// secondary pass to normalize the blended values
for (var x = 0; x < Width; x++) {
    for (var y = 0; y < Height; y++) {
        blendData.Data[x,y] = (blendData.Data[x,y] - blendData.Min) / (blendData.Max - blendData.Min);
    }
}

```

---
Tags: procedural-generation, perlin-noise
---


# Question
Title: In 2d, how do I discern when a character is on top of an object, from when it is on the side?
I am building an auto-run platforming game. I have code so that if the character collides with a wall, they are pushed back until they are able to get past the wall. Unfortunately, this means that when the character tries to jump on an object, he just gets pushed backward.

How do I discern when a character is on top of an object, from when it is on the side?

My Current Algorithm (c-ish because i like c-ish syntax):

```
if(  wall.Top  < (character.Top + character.Height)
 &&  wall.Left < (character.Left + character.Width)
 && (wall.Top  + wall.Height) > character.Top
 && (wall.Left + wall.Width ) > character.Left)
{
  #code here#
}

```

# Answer
It isn't that clear what you mean with top and height, but let's say you have your character's x, y, width and height, and so you do for the wall (assuming the x and y values are on the top-left corner of the character/wall, and the y axis gets greater when going downward)

```
if (character.y + character.height > wall.y && charcter.x + character.width > wall.x) {
//collision happening: push character left
}

```
> 1 votes

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


# Question
Title: Basic billiards game: Can't detect collision between cuestick and cueball
I have a basic Unity project on GitHub.

Basically, I have a Cuestick that aims and shoots using the mouse. You can rotate around the cueball with your mouse and when you're ready to shoot, you can hold down the right mouse button and move the mouse forward. The game came follows the cuetip.

However, the collision between the cuestick and cueball is wonky. The cuestick protrudes through the ball and only pushes the ball forward only a little bit.

I've created rigid bodies and colliders for both cuestick and cueball. I've set the cuestick's rigid body to kinematic (if it's unchecked, the poolstick will barely dent the ball). I've tried using `OnCollisionEnter` and a `Debug.Log` statement to no avail.

Any help would greatly be appreciated. You can find my scripts in /GameLogic (they're F# sharp scripts whose binaries get compiled and outputted into the /assets folder).

# Answer
> 1 votes
Why using a complicated collision detection algorithm? Just calculate the distance from the center of the ball to the end of the cuestick. If it's less than or equal to the ball's radius, the cuestick is colliding with the ball.

---
Tags: unity, collision-detection, physics, billiards
---


title: Unity Teleport Script issue

text:
# Question
Title: Unity Teleport Script issue
I wrote this script quickly just for moving across my map for testing purposes. I created a prefab with this script on it and gave it the Destination GameObject which works fine, it teleports me as it should. However when I attach this script to another object with an new destination, it still takes me to the one on the prefab. What am I doing wrong?

```
public class TeleportationDevice : MonoBehaviour {
    public Transform destination;
    public GameObject interaction;
    public GameObject model;

    private GameObject player;
    private bool isInRange = false;

    void Update()
    {
        if (isInRange)
        {
            if (Input.GetKeyDown(KeyCode.E))
            {
                Teleport();
            }
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player")
        {
            // Show the interaction canvas
            interaction.transform.position = model.transform.position;
            interaction.SetActive(true);

            // Set player GameObject
            player = other.gameObject;

            // Make sure the player is within range
            if (other.transform.position.x <= this.transform.position.x + 20f)
            {
                isInRange = true;
            }
            else
            {
                isInRange = false;
            }
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.tag == "Player")
        {
           interaction.SetActive(false);
        }
    }

    void Teleport()
    {
        player.transform.position = destination.position;
    }
  }

```

# Answer
Rather than checking whether the player is in range when the player presses the activation button, this script has each teleporter remember whether the player is in range.

It does this by remembering `isInRange = true` when the player enters its trigger volume, and then trusting that this memory still accurately reflects the state of the world sometime later when the player presses the activation button.

The trouble is, after the player has entered the trigger, it doesn't check their range again and update their `isInRange` value to false if they wander away (either still inside the trigger, or exiting it and not re-entering - `isInRange` only gets changed within `OnTriggerEnter`)

So if I visit two teleporters in a row, entering each one's trigger volume within range and then exiting it, *both* teleporters think I'm in range.

If I press the activation button, both will teleport me to their destination. Whichever one happens to update later will be the result I observe, since it stomps over the changes made by the earlier one.

There are a number of ways to fix this:

* Have each teleporter/activatable object **check the range every time the player presses the activate button**. This is blunt, but range checks are cheap, especially if you avoid square roots. (As an aside, your range checks here look... unorthodox - you're only checking distance along one half-axis? Is this deliberate?)
* **Move the activation check out of `Update`** and into a coroutine that you start `OnTriggerEnter()` and stop in `OnTriggerExit`. That way, only things whose trigger volumes the player is in will listen to key presses.
* Flip it around, so instead of every object listening for input and checking if the player is near, **the player object listens for input then checks its vicinity** for something to activate. This player script can either use a `Physics` query to find them each time, or keep a list of nearby objects that it updates in its trigger enter/exit methods.
> 0 votes

# Answer
I made some changes and simplified the code for you. You will need to set the collider on the Teleporter as a trigger and then drag in the object that you want your destination to be as well as your player character.

```
using UnityEngine;
using System.Collections;

public class playerTeleport : MonoBehaviour {

  bool isInRange = false;
  public Transform destination;
  public GameObject player;

  void Update()
  {
    if (isInRange && Input.GetKeyDown(KeyCode.E))
      Teleport();
  }

  void OnTriggerEnter (Collider other)
  {
    if(other.gameObject == player)
      isInRange = true;
  }

  void OnTriggerExit (Collider other)
  {
    if(other.gameObject == player)
      isInRange = false;
  }

  void Teleport()
  {
    player.transform.position = destination.position;
  }
}

```
> 0 votes

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


title: Fade to first level, on click

text:
# Question
Title: Fade to first level, on click
Good evening all, about to pull my hair out because I cant figure out why I keep getting this error. The problem is this, I need the player to click on the start button, then, the screen will fade to black and load level 1. (logic and code was provided by a Brackeys tutorial(https://www.youtube.com/watch?v=0HwZQt94uHQ), awesome guy)

here is the code for the button.

```
public void OnPointerClick(PointerEventData eventData)
{
    float fadetime = GameObject.Find("_GM").GetComponent<FadeScreen>().BeginFade(1);
    yield return new WaitForSeconds(fadetime);
    SceneManager.LoadScene("Level_01");
}

```

Now the error is highlighted with a red line under OnPointerClick just after "public void".

And the error is - The body of 'StartGame.OnPointerClick(PointerEventData)' cannot be an iterator block because 'void' is not an iterator interface type. Ive been googling for around four hours now and I'm coming up blank.(lack of sleep might be causing me to miss something)

Please can someone point out what I cannot see myself? Also I do apologize if this has been asked before, I was not able to find anything on the subject. Thank you kindly.

# Answer
> 2 votes
The `yield return new WaitForSeconds(time)` construct only works in Coroutines.

A coroutine must be started with the `StartCoroutine(name)` method and must itself be a method which returns an IEnumerator.

So first you need to write your coroutine as a new method:

```
IEnumerator FadeToNextLevel() {
    float fadetime = GameObject.Find("_GM").GetComponent<FadeScreen>().BeginFade(1);
    yield return new WaitForSeconds(fadetime);
    SceneManager.LoadScene("Level_01");
}

```

And then you need to launch that coroutine from the method which is your button handler:

```
public void OnPointerClick(PointerEventData eventData) {
    StartCoroutine("FadeToNextLevel");
}

```

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


# Question
Title: using Mathf.Clamp in Vector3 to restrict object drag
I'm making a checkers game and I've got a movement controller working to move the pieces. I want to restrict the drag to be within the board. The center of the board is 0,0 so the far left side's x value is -4, top of the boards y is 4, etc...

This is my drag script so far

```
void OnMouseDrag()
{
        float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
        transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance_to_screen));
}

```

but when I try to clamp my new Vector3's x and y between -4 and 4 like this,

```
transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Mathf.Clamp(Input.mousePosition.x,-4f,4f), Mathf.Clamp(Input.mousePosition.y,-4f,4f), distance_to_screen));

```

it shoots the pieces way off camera. This may be because don't truly understand Camera.main.ScreenToWorldPoint, is it returning different x,y coordinates than the global ones?

# Answer
> 0 votes
Since your bounds (-4,-4) -\> (4, 4) are world space coordinates, your error is that you're clamping the input (screen space) instead of the output of `ScreenToWorldPoint`.

`Input.mousePosition` will give you pixel coordinates between (0,0) and the max resolution of your screen (`Screen.width`, `Screen.height`).

Try clamping the result *after* the call to `ScreenToWorldPoint`:

```
void OnMouseDrag() {
    float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
    Vector3 before_clamp = Camera.main.ScreenToWorldPoint(new Vector3(
        Input.mousePosition.x,
        Input.mousePosition.y,
        distance_to_screen));
    transform.position = new Vector3(
        Mathf.Clamp(before_clamp.x, -4, 4),
        Mathf.Clamp(before_clamp.y, -4, 4),
        before_clamp.z);
}

```

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


title: InputProcessor without stage

text:
# Question
Title: InputProcessor without stage
I have a GameScreen where I'd like to have a pause button. I've tried using an Image with a listener, but since my GameScreen isn't a stage, I can't use that in the inputProcessor. So my question is how should one create a clickable button outside a stage class?

# Answer
In general you need two textures, an up and a down to be displayed. Then you need to check to see if the touch coordinates is in bounds. Something like the below should work for your needs with little modification:

```
public class MyButton
{
    private Texture imgUp;
    private Texture imgDown;
    private Rectangle bounds;

    public MyButton(Texture imageUp, Texture imageDown, Rectangle bounds)
    {
        this.imgUp = imageUp;
        this.imgDown = imageDown;
        this.bounds = bounds;
    }

    public Rectangle getBounds()
    {
        return bounds;
    }

    public void update(SpriteBatch batch)
    {
        if(isTouched())
        {
            batch.draw(imgDown, bounds.getX(), bounds.getY());
        }

        else
        {
            batch.draw(imgUp, bounds.getX(), bounds.getY());
        }
    }

    public boolean isTouched()
    {
        if(bounds.contains(Gdx.input.getX(), Gdx.input.getY())
        {
            return true;
        }
        return false;
    }
}

```

If you want you can also define your own implementation of InputProcessor and libGdx comes with a few implementations aside from `Stage`. You can set InoutProcessor with:

```
Gdx.input.setInoutProcessor(processor);

```
> 1 votes

---
Tags: java, libgdx, pausing
---


# Question
Title: Webgl, weird rendering with sprite that has alpha
So I have a webgl application where I render all kinds of objects, but in this specific example, I have two shaders. One that renders sprites and one that renders colored polygons. In this example I draw a rectangle and two sprites. The rectangle is drawn first and the sprites are drawn second. The rectangle has a lower z and the the sprites have the same z that is higher then the rectangle. This is the result with depth test function of gl.LESS and gl.BLEND enabled with blend function gl.blendFunc(gl.SRC\_ALPHA, gl.ONE\_MINUS\_SRC\_ALPHA). The texture is a png. Here is the result

This is not the correct result obviously as the sprite below is somewhat cut off. Also, if I draw the sprites before the rectangle, I get this

At first, I figured that that black around the sprites was just the pixel not being blended as alpha, but as it turns out from changing the clear color, that black is actually the background, so it looks like the rectangle is literally being cut out.

What could cause this behavior?

There is a lot of code, so tell me what is relevant and I will post it.

# Answer
> 1 votes
This is due to depth testing.

You need to order your sprite rendering back to front and either disable depth test or set it to gl.LEQUAL.

Sprites will not render if the pixel depth is equal to a previously drawn sprite when the depth function is set to gl.LESS.

---
Tags: javascript, webgl
---


# Question
Title: How to resize 2D Java game without “squeezing” it?
I am trying to make my second java game (2D) but i have run in a problem: The game will be in fullscreen, but how can i make it so it is scaled properly for each screen? While researching i found out that (almost) everyone is saying the same thing: render it on a Buffered image first and then render the image on the screen resolution, which i understund how to do ( BufferedImage i = new BufferedImage(width, height, 1); BufferStrategy bs = this.getBufferStrategy();

```
Graphics2D g2 = i.createGraphics();
if(bs == null){
    this.createBufferStrategy(3);
    return;
}

Graphics g = bs.getDrawGraphics();
//g2.draw....

g.dispose();
bs.show();

```

) but wont that make everything look squeezed or streched? P.s. if you know any way of making it scale only by keeping the starting resolution (leaving black on both sides) i would accept it

P.s.Sorry for my english.Hope i explained it good enough (if not ask me to clarify)

# Answer
> 1 votes
Just render the image on your JFrame/JPanel using `g.drawImage(img, x, y, width, height, obs)` with this trick:

```
JPanel panel = ...; // Your target panel
Graphics g = ...; // The graphics object of this panel (argument of paintComponent)

float scale = Math.min((float) panel.getWidth() / i.getWidth(), (float) panel.getHeight() / i.getHeight());

int displayWidth = (int) (i.getWidth() * scale);
int displayHeight = (int) (i.getHeight() * scale);

g.drawImage(i, panel.getWidth()/2 - displayWidth/2, panel.getHeight()/2 - displayHeight/2, displayWidth, displayHeight, null);

```

This way you keep the aspect ratio of the `BufferedImage` but scale it to take the maximum place of the panel.

Also, if the `BufferedImage` is smaller than the panel, then you might notice some artifacts. The easiest way to fix them is to set the rendering hint INTERPOLATION to something better, like BILINEAR:

```
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

```

---
Tags: java, jframe
---


# Question
Title: Streaming player voice (client -> server) without (minimal) noticeable voice breaking
I recently started to jump into voice streaming for my RPG game, for players to communicate by a central server point. I use TCP packets to communication from client-\>server and from server-\>client(s).

What I currently do is streaming the microphone from the client (push-to-talk), send the voice data in 4096 bytes chunks, and send them to the client. However, since TCP packets take some time to send and process, as well as standard latency issues, the server forwards the packets to other clients with a certain delay (sometimes up to half a second).

How should I compensate for this delay? (What technique do you recommend?)

# Answer
> 3 votes
I would use UDP since it has lower latency. When a packet is lost, UDP carries on with the next packet instead of waiting for the previous packet to be sent. UDP will also reorder packets, since it is just sending blocks of data, not a stream like TCP. You would need to track the packets as you will have to manually sort the order of the incoming data. Normally you establish an acceptable latency, reordering the packets as they come in (as long as they arrive before your artificial latency) and reject those that are older than your established latency. This packet loss/drop will cause gaps in your audio, but you can mitigate it somewhat by sending redundant audio data in each packet. By detecting and tracking packet loss you can establish a 'quality of service' of the connection and reduce/increase the amount of duplicated data sent per packet.

UDP's lower latency with *some* drop out is preferable, IMHO, as it lets players have closer-to-realtime conversations.

Alternatively, you could consider slowing down your entire game so the voice matches in game events, but that's not going to make round-trip conversations work very well.

As for how you track packet ordering, I think that's a different question, but basically you need to establish some amount of 'acceptable' latency - say 100ms. You buffer up in-coming packets, putting them back in order as they arrive. Once you have 100ms or more of data you start pulling the data off the front, consuming the now in-order packets. Of course there will likely be dropped packets so you would want to either use the redundant data or incorporate an resend system using ACK/NAK, which sounds like re-inventing TCP but the results are more light weight - for example if the 100ms buffer has been consumed, there's no point requesting data that has already been 'played through'. It's the back bone of most reliable-over-UDP protocols used in most realtime networked games for the past couple of decades.

---
Tags: networking
---