title: Manipulating sprite shape rendered

text:
# Question
Title: Manipulating sprite shape rendered
I wish to create a game object where you can start dragging it by touching somewhere on the line of its collision and to create these "dynamic shapes" by stretching the sprites and readjusting the sprite look and collision according to the drag point.

Adding an illustration for clearance:

Started playing with `Sprite Shape Renderer` to create these curved sprite tiles but I need to be able to create dynamic ones using the mouse cursor and adjust all collisions.

I've tried to add an `AnchorDragger` script to the `Sprite Shape Renderer` object:

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

public class AnchorDragger : MonoBehaviour
{
    const int INVALLID_INSERTED_POINT_INDEX = -1;

    public SpriteShapeController spriteShapeController;
    private Spline spline;
    private int inseretedPointIndex = INVALLID_INSERTED_POINT_INDEX;

    void Start()
    {
        spline = spriteShapeController.spline;
        int pointCount = spline.GetPointCount();
        for (var i = 0; i < pointCount; i++)
        {
            Vector3 currentPointPos = spline.GetPosition(i);
            Debug.Log("Point " + i + " position: " + currentPointPos);
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (inseretedPointIndex != INVALLID_INSERTED_POINT_INDEX)
        {
            spline = spriteShapeController.spline;
            spline.SetPosition(inseretedPointIndex, Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f)));
            // Debug.Log("Setting position to: " + Camera.main.ScreenToWorldPoint(Input.mousePosition));
        }
    }

    void OnMouseDown()
    {
        Debug.Log("Mouse Down Position:" + Input.mousePosition);
        Vector3 mouseDownPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f));
        Debug.Log("World Position: " + mouseDownPos);
        spline = spriteShapeController.spline;
        int pointCount = spline.GetPointCount();
        int closestPointIndex = int.MaxValue;
        float minDistance = int.MaxValue;
        for (var i = 0; i < pointCount; i++)
        {
            Vector3 currentPointPos = spline.GetPosition(i);
            float distance = Vector3.Distance(currentPointPos, mouseDownPos);
            if (distance < minDistance)
            {
                minDistance = distance;
                closestPointIndex = i;
            }
        }
        spline.InsertPointAt(closestPointIndex, mouseDownPos);
        spline.SetTangentMode(closestPointIndex, ShapeTangentMode.Continuous);
        inseretedPointIndex = closestPointIndex;
        Debug.Log("Inserted point index: " + inseretedPointIndex);
    }

    void OnMouseUp()
    {
        Debug.Log("Mouse Up");
        spline = spriteShapeController.spline;
        spline.RemovePointAt(inseretedPointIndex);
        inseretedPointIndex = INVALLID_INSERTED_POINT_INDEX;
    }
}

```

Basically tried to figure the closest point on the spline where I've clicked and then inserting a new point and setting its position on `Update` to where the mouse is and delete the point on mouse up.
Right now I'm having a problem where the drag position is not correct for some reason.
Where I clicked, where the new point position is set:

Even when I tried to play with where I click and where I take my mouse to while dragging, not sure why, could use help!

Also I'm not sure how I would update the `EdgeCollider2D`? I know I can get it in the `Update` method using:

```
EdgeCollider2D edgeCollider = gameObject.GetComponent<EdgeCollider2D>();

```

But how would I actually update it correctly to fit the new sprite?

# Answer
You need to rebake the collider to force the update. wrote this last December but should help you get the position correct.

```
        var insertPoint = Input.mousePosition;
        insertPoint.z = 10.0f;
        insertPoint = Camera.main.ScreenToWorldPoint(insertPoint);
        var m = Mathf.Abs((insertPoint - lastPosition).magnitude);
        if (Input.GetMouseButton(0) && m > minimumDistance)
        {
            var spriteShapeController = gameObject.GetComponent<SpriteShapeController>();
            var spline = spriteShapeController.spline;

            spline.InsertPointAt(spline.GetPointCount(), insertPoint);
            var newPointIndex = spline.GetPointCount() - 1;
            spline.SetTangentMode(newPointIndex, ShapeTangentMode.Continuous);
            spline.SetHeight(newPointIndex, 1.0f);
            lastPosition = insertPoint;
            spriteShapeController.BakeCollider();
        }

```

here is a gif of it working dynamically
> 1 votes

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


# Question
Title: Want to stop instantiating objects when timescale is set to zero
I have my enemies being instantiated from both left and right sides and I've used Time.timescale=0; for the pause menu script so whenever i pause my game everything stop other than the instantiating objects and when i resume the game all the instantiated objects come as bunch. I really need a solution.

# Answer
just put this line of code on first line of function that instantiates enemies:

```
  if (Time.timeScale == 0) return;

```

time scale basically work for objects Movement if you have used delta-Time in their movement function as delta time is multiplied with movement amount.
> 1 votes

# Answer
The other answer will work for your *current* need, but it will not work when you'll actually start using the timescale for purposes other than pausing the game, such as creating slow motion effects or when you'll want to debug and accelerate the process to attain certain events faster.

The first thing to do is decide the rate at which your enemies spawn: you can use "enemies per minute".

At the initialization, translate this value to a "per second" value.

Then every update, accumulate your deltaTime, and while the accumulator is higher than the spawn rate, spawn an enemy.

Pseudo code:

```
float spanwRatePerSecond = spawnRatePerMinute/60.0;
float spawnAccumulator = 0.0;

update()
{
  spawnAccumulator += Time.deltaTime
  while ( spawnAccumulator >= spanwRatePerSecond )
  {
    spawn()
    spawnAccumulator -= spanwRatePerSecond
  }
}

```

---

Keep in mind that using the timescale variable to pause your game has its disadvantages: at some point, you might want to keep some things moving and animated on the screen when you'll pause the game. Using `timeScale = 0` will make it harder to achieve.

---

Finlay, as it's stated in the documentation, you could prevent the spawning of your enemies by putting the spawn code in the `FixedUpdate` function, because it is not called when the `timeScale` is zero.
> 0 votes

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


# Question
Title: 3D line segment AABB collision, with hit normal?
I'm embarrassed I can't find this, but I'm wanting to detect intersection with a 3D line segment (not an infinite ray) with a 3D AABB, the AABB being defined as two Vec3f's which represent the Min and Max extents. So the AABB can be arbitrarily-sized. I also need the surface normal of the AABB, if there was a hit.

From looking at similar algorithms I at least know it seems good to calculate the inverse direction of the line beforehand, at least, if you're needing to check against multiple AABBs per frame.

I have

```
struct AABB
{
    VEC3F min;
    VEC3F max;
};

// a and b representing start/end points of the line segment
// returns true if intersects, also fills out "normal" if true
bool LineIntersectsAABB(const VEC3F& a, const VEC3F& b,
    const VEC3F& inv_dir, const AABB& aabb,
    VEC3F* normal);

```

The implementations I've found either do not find the hit normal, and/or they're intended for boxes/cubes where the three dimensions of the box are always equal length, which doesn't work for me. Implementations seem to vary greatly, which is confusing for me (since I'm still trying to learn it), and, considering that I need the hit normal, I'd imagine that that may rule out certain implementations.

# Answer
> 2 votes
> but I'm wanting to detect intersection with a 3D line segment (not an infinite ray) with a 3D AABB

Most of these ray intersection algorithms return the hit distance. All you need to do is check that the hit distance is less than the length of your line segment.

For your normal calculation, find the plane on the cube which contains the intersection point closest to the ray, where the ray still intersects the cube.

1. Use a ray intersection algorithm, `ray_box_intersection(ray, box, &out_distance)`
2. If there is an intersection, check that the distance is \< the length of the line segment, otherwise exit
3. To get the normal, take the ray plane intersection of each plane in the box.
4. Ray plane intersection distance = `((plane_offset - ray_origin) * plane_normal)/(ray_direction * plane_normal)`, where if the distance \< 0, there is no intersection (the intersection is behind us), and if the `ray_direction * plane_normal == 0`, the ray is travelling parallel to the plane, and there will be no intersection.
5. If this `ray_plane_intersection(ray, plane, &out_distance)` returns true, we will still need to test if the point was inside the box. If the test is true, remember this plane's normal and the distance.
6. Repeat 6 for every plane around the box, keeping the plane with the smallest distance, and keeping its normal
7. You now have the normal.

In my code don't treat the intersection code as a black box, and I typically modify this answer for best AABB 3d box intersection tester, and check which of the `t1 t2 ... t6` values ended up being used for the final output `t` ray distance value in addition to giving the distance. Each of these t's correspond to a side of the AABB, which tells you which normal you use.

---
Tags: collision-detection, 3d, raycasting, aabb, line-of-sight
---


# Question
Title: how to build release version mac cocos2dx?
do you know how to build mac build release version? in this case i use cocos2dx framework.

in vs2013 we easyly choose the build version but in xcode i dont know.

the indication release build is all CCLOG would disappear in the game. but i have try toggle it in buildsetting pane. CCLOG still displayed in my console.

any suggestion? thanks.

# Answer
haha, solved in here http://applehelpwriter.com/2013/10/01/change-between-debug-and-release-build/. its too fast question :P
> 0 votes

# Answer
Another option is using the cocos console to compile, add the tag

> -m release

which means **mode release**
> 0 votes

---
Tags: cocos2d-x, xcode, release
---


# Question
Title: "Your license does not cover Android Publishing" error
I recently installed Unity 2017.1.0f3. I imported a project from an older version of Unity it worked perfectly and allowed me to build for Android. I logged in to the Asset Store through the tab in the Unity editor, now I can no longer build for Android.

This is the error I receive:

I created my Unity account before Android was free. Is there a way to update my account to allow me to build with Android again?

# Answer
Trial and error solved my problem:

1. Sign out, In the top right hand corner of the the editor click Account \> Sign out \[Your Name\]:

2. Close Unity.
3. Re-open Unity.
4. It will ask you to login and choose your licence.
5. You will now have the latest licence file.
> 6 votes

# Answer
In my case, I'm using unity hub and seems that it is the reason for the problem because I'm signed in the unity hub but not signed-in in the unity version I'm using

The solution is 1- Close current running version 2- Browse for your unity setup folder then open unity.exe (Not Open unity hub) 3- login and you can find everything is working fine
> 0 votes

# Answer
I had to update my license in Unity Hub.

Preferences -\> License Management -\> Check for Updates
> 0 votes

---
Tags: unity, build-process
---


# Question
Title: How do I make an object look at an angle in a top-down persepective?
Given a top-down persepective and lets say I know the angle I want to look at, how do I make a gameobject look into that angle? I currently have code like this:

```
if (directionX != 0 && directionZ != 0)
{
    transform.rotation = Quaternion.LookRotation(new Vector3(directionX / 2, 0, directionZ / 2));
}
else if (directionX != 0 || directionZ != 0)
{
    transform.rotation = Quaternion.LookRotation(new Vector3(directionX, 0, directionZ));
}

```

which allows me to move look into 8-directions. I am now looking to make it so I can look in any angle and I've got the angle using:

```
var angle = Mathf.Atan2(directionZ, directionX) * Mathf.Rad2Deg;

```

but I don't know how to use it to make my object look into that angle.

# Answer
> 1 votes
Store the position into a `Vector3` and you can use that to LookAt

```
Vector3 lookAtObj

        Quaternion newRotation = Quaternion.LookRotation(lookAtObj);
        transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, 1);

```

If you want to avoid Lerp or Slerp then I would suggest something like LookAt

```
    transform.LookAt(transform.position + lookAtObj.transform.rotation * Vector3.forward,
    lookAtObj.transform.rotation * Vector3.up);

```

---
Tags: unity
---


# Question
Title: Can letting players take resources from others prevent inflation despite the lack of money sinks?
For a long time I've been idly thinking about a competitive game with strong collection elements with such a rule that players will win or lose resources at the expense of each other during each match.

Sorry if this seems unclear; let me provide a concrete example: Chess with an ecosystem.

Each player starts with a standard set of a king, a queen, two bishops, two knights, two rooks, eight pawns. Each time, during a match, a figure or pawn is captured, it permanently goes to the player who captured it (promoted pawns count as pawns for this purpose, not as whatever they were promoted to). This is the only way players can earn pieces¹.

The game is divided into several leagues: each league restricts the total value of pieces both players may start with. As long as each player only uses pieces they own and their value doesn't exceed their league's maximum, they can start with any pieces they desire. Thus each player who's just founded their account will start at a mediocore league that enforces the total value of pieces of up to 43 (8 pawns * 1 + 2 bishops * 3 + 2 knights * 3 + 2 rooks * 5 + 1 queen * 9 + one king * 4 = 8 + 6 + 6 + 10 + 9 + 4 = 43); if they lose pieces they will lose access to the starting league and be demoted to lower leagues, down to the lowest league that only accepts the total value of pieces of 5 (meaning that, aside from the mandatory king, it only allows one pawn); if they earn pieces they are promoted to higher leagues that allow them to start with more total material. (Players may also play lower leagues than their league if they wish, but not higer). If they lose so much pieces they cannot even play at the lowest league, they lose permanently and have to start with a fresh account.

Now from this follows that since there are no sinks and the total material of the game will only be increasing with people founding more and more accounts. From this we can expect that as more and more players lose permanently, we will have more and more players having hundreds and thousands of pieces, so inflation happens.

But if, regardless of their league, players are always matchmade according to their elo and if there are so many players that the matchmaking works and is unpredictable (granted, big 'if's...), their winrates should sit at 50%! Thus their earn/lose balance should be around zero. Pieces have a fixed cost: Getting them requires winning against an opponent of equal skill.

Ugh... Looking at the problem from these two different perspectives yields conflicting results. What am I missing? Would inflation happen in such a game?

Note this chess example is really only an example: I only provided it because it is the only **concrete** example I could muster. However, we can easily think about a collectible card game with a system similar to this, and I suppose such a TCG example would be even better here.

¹ Well, almost. If a player loses a king and have no more kings they must buy another king. To this end they must sell other pieces: pawns for one gold piece each, knights and bishops: three pieces each, rooks for 5 gold pieces each, queens for 9 gold pieces each; this in-game currency goes to the 'king fund' that will be used to buy kings from the in-game shop, 4 gold pieces for each king. No other pieces can be purchased for gold gained in such a way.

# Answer
The average winrate between a player who loses all their pieces and one who gains all those pieces is 50%, but the player who loses all their pieces then goes on to make a new account, so now amongst those two people there are three complete sets of pieces, and you have inflation.

As for the middle and high-rank players accumulating more pieces over time despite not getting any better in rank: Imagine a ladder of people who are each just a tiny bit better than the one before them, close enough that they get matched against the adjacent players: on average, each player will collect pieces from the slightly worse player, and give pieces to the slightly better player, so over (a probably pretty long) time pieces will go up the chain, from the bottom where new pieces are generated, to the top where the greatest players are.
> 4 votes

# Answer
## This will cause inflation.

Having the total material increase with people creating more and more accounts is a sound argument.

The argument that win rates should be around 50% and thus the pieces will remain constant is flawed:

**For the *average* win rate**: Initially, how many pieces a player has corresponds to their win rate. Players who lost all their pieces would have a win rate of less than 50%. When you give a player pieces to "reset" them, you're increasing how many pieces they have, but you're not increasing their win rate, so the number of pieces no longer corresponds to the win rate. Thus the win rate can remain 50% while the total number of pieces increases.

Alternatively, if you consider these to be *new* accounts, you're removing accounts with a sub-50% win rate and replacing them with new accounts. This would increase the average win rate and thus also the total number of pieces.

**For the *individual* win rate**: every player will not have a win rate of 50%, even in a perfectly balanced skill-based game. The best players can consistently win, since there's no-one who can beat them. The worst players can consistently lose. If these players are put back in the middle, they will likely drop again and other players at the same ranking will win more often. The ranking of those players will increase, which will pit them against stronger players, who will beat them, which will decrease the ranking of the weaker player back to where it was and increase the ranking of the stronger player. This effect will keep going (albeit slowly) until it gets to the top players, who have no stronger players to play against, thus their win rate and ranking will simply increase.

## Players quitting can also cause inflation

The above only exactly applies to a closed system (one where no players are added or removed) or when players are added and removed *randomly*.

If players at the top no longer feel challenged or like there isn't anything more to achieve, they may stop playing. This could cause negative inflation to counteract the inflation discussed above, but frequently having your best players quit is usually a pretty bad sign.

Players at any level may simply get bored with the mechanics of the game. For arguments sake, one might assume this happens at every level with equal likelihood (although this may happen more frequently at lower ranking, since these players may miss some of the nuances and complexity making the game more fun for higher ranking players).

Other players may quit out of frustration. This would almost certainly happen much more frequently with players losing too often, especially ones who has mostly been losing since they started. These players would likely have a sub-50% win rate and thus them quitting would increase the average number of pieces per player, which is inflation.

## What to do instead

Having ranking tied so directly to strength (through number of pieces) will always be a problem.

If you want to do something like this, you could:

### Limit the number of pieces per player

There are two ways this could be done:

* Limit on the number of pieces each player can have.

This may cause a whole lot of players eventually reaching the maximum instead of fewer players having more and more pieces, which is still not great, but may be preferable.
* Have players pick a subset of pieces to play with (and there's a limit on how many they can pick).

Having players constantly gain unusable pieces may not be that much fun for them, but this may also be better than the alternative.

### A piece upgrade system

You could have players upgrade pieces to improve them by combining pieces together. This is assuming you can define an upgrade system which makes sense in the context of your game.

If pieces are taken, the other player gets a piece with no upgrades.

This would be a sink for pieces, which could counteract inflation.

Alternatively, you can let players take the upgrades too. In that case, the upgrades should probably be very minor, so a better player can still beat a weaker player with much better upgrades. There would still be inflation, but this could slow it down an extreme amount.

### A minimum number of pieces

I'm assuming that playing with very few pieces wouldn't be all that much fun.

So I'd suggest, instead of having players go down to zero pieces, you can have them go down to a minimum. When at the minimum, any taken pieces will not be removed from the losing player, but instead just give the winning player a duplicate.

Then remove the idea of "resetting" a player's pieces, since this is no longer necessary.

This doesn't really address inflation, but should make the game more fun for the players with lower ranking.

This also has the added benefit of not constantly resetting weak players, where they'll then play against stronger players.

### Take only one piece per game

When winning, you only get *one* of the opponents pieces (either one which was taken or any which was played with, which can either be picked or random).

This wouldn't stop inflation, but it would be slower than having *all* taken pieces go to the other player.

### Tournament format

Have constant tournaments, each with a fixed start and end date. Pieces only last for the duration of the tournament and gets reset when another tournament starts.

There would be inflation, but this might even be a good thing when you're just resetting everything at some point.
> 0 votes

---
Tags: game-design, mmo, economy, competition
---


# Question
Title: Higher order splines for use with pathfinding
In this page, Amit explains that splines can be used to achieve movement on a found path.

In the picture below, he explains that:

> The blue paths use splines, with dark blue being low order splines and light blue being a higher order spline.

What are exactly high order splines? How to achieve the light blue movement?

# Answer
> 1 votes
A spline is a curve built from a number of conjoined polynomial equations. Higher order splines are splines built of higher order polynomials. Generally speaking the higher the order, the more fluid the curve (sort of), with linear splines being a series of straight lines.

Here are some examples or different orders (from the Wikipedia page on Bézier curves, a type of spline).

**Linear**:

**Quadratic**:

**Cubic**:

These GIFs show generally how these curves are constructed, and `higher order = more control points`. In Amit's example, those control points are consecutive points along the path, so a higher order spline means that there is a smoother interpolation along a larger set of those points at a time.

Put another way, instead of looking at just the next point to move toward (linear), it might look at the next two points (quadratic) or next three points (cubic). This allows for more natural movement of your game entities along the path that has been constructed - the underlying logical path doesn't change, just the actual movement on screen.

There is more information on the Wikipedia page about how to construct these curves.

---
Tags: movement, path-finding, splines
---


# Question
Title: Problem displaying drawing of a path in camera/viewport
**I have an adm object, which draws the path in the room like this (Object ADM - Draw Event):**

```
draw_set_color(c_black);

repeat(5){
    repeat(5){
        draw_path(circuito_australia,684+i,568+j,false);
        j+=1;
    }
    i+=1;
    j=0;
}

i=0;
j=0;

```

**Result:**

**I created 2 viewports, to more closely display specific cars:**

**And this problem happens, parts of the circuit in the view of these cameras are wrong/bugged:**

The reason I know (or at least I imagine) is because I'm taking a part of the room and doubling its display.

Any ideas on how to get around this?

# Answer
> 0 votes
I believe the solution I found is not unique.

Just on the game screen (with the code of the question itself) take a printscreen and add as a sprite in the game.

**Problem and printscreen:**

Obviously the printscreen has to be taken without the objects present in the circuit being visible. Just disable the visibility of objects.

**The code looks like this:**

```
draw_sprite(spr_circuit,0,0,0);

repeat(5){
    repeat(5){
        draw_path(circuito,x0+i,y0+j,false);
        j+=1;
    }
    i+=1;
    j=0;
}

```

**Result:**

**I did a test and found that after drawing the circuit image, the following part of the code becomes unnecessary (draw\_path):**

```
repeat(5){
    repeat(5){
        draw_path(circuito,x0+i,y0+j,false);
        j+=1;
    }
    i+=1;
    j=0;
}

```

Just need to draw the printscreen you took (`draw_sprite(spr_circuit,0,0,0);`).

So you only need to use the function (`draw_path`) to get the printscreen out.

---
Tags: camera, game-maker, viewport, path
---


# Question
Title: How should I load/change/activate scenes?
Scenes are confusing the hell out of me and I'm pretty sure they should be simple to understand.

When the game loads, only the current scene has a buildIndex != -1. In order give it a 'real' build index I need to load it by path or name (because there's no build index).

The scenes are ten game scenes, one title scene and one persistent scene (which has the player and the status bar with the score etc.).

Should I load a scene every time I change scene and then load additive afterwards or should I be using Set Active Scene?

All the scenes are ticked in the *Build Settings*.

I'm looking at the index with this:

```
private void Start()
{
    var sceneName = "Persistent";
    var sceneBeforeLoading = SceneManager.GetSceneByName(sceneName);
    Debug.Log($"Scene {sceneBeforeLoading.name}, BI = {sceneBeforeLoading.buildIndex}");
    SceneManager.LoadScene(sceneName);
    var sceneAfterLoading = SceneManager.GetSceneByName(sceneName);
    Debug.Log($"Scene {sceneAfterLoading.name}, BI = {sceneBeforeLoading.buildIndex}");
}

```

Which outputs:

```
----------------------------------------------
Scene , BI = -1
UnityEngine.Debug:Log(Object)
Title:Start() (at Assets/Scripts/Title.cs:10)
----------------------------------------------
Scene Persistent, BI = 1
UnityEngine.Debug:Log(Object)
Title:Start() (at Assets/Scripts/Title.cs:13)
----------------------------------------------

```

# Answer
> 1 votes
I am not sure if you have read the documentation or not on the matter but I would review here SceneManager

The build index is the numbers to the right on your pic of the build settings so you have a choice of 0-12 to load by index.

if loading by name you can load it

```
 SceneManager.LoadScene(scenename);

```

or by index

```
SceneManager.LoadScene(sceneANumber);

```

you can also load the scene asynchronously using the index

```
SceneManager.LoadSceneAsync(0);

```

or by path if you have them bundled in a assetbundle of scenes

```
 private AssetBundle myLoadedAssetBundle;
private string[] scenePaths;

// Use this for initialization
void Start()
{
    myLoadedAssetBundle = AssetBundle.LoadFromFile("Assets/AssetBundles/scenes");
    scenePaths = myLoadedAssetBundle.GetAllScenePaths();
}

void OnGUI()
{
    if (GUI.Button(new Rect(10, 10, 100, 30), "Change Scene"))
    {
        Debug.Log("Scene2 loading: " + scenePaths[0]);
        SceneManager.LoadScene(scenePaths[0], LoadSceneMode.Single);
    }
}

```

---
Tags: unity, c#, .net, scene, scenemanager
---


# Question
Title: How to use Animation Player in Godot like Animated Sprite
So currently I am using the following code to play my sprites (AnimatedSprite Node).

```
$Sprite.play("Animation Name")

```

However now I want to use the AnimationPlayer Node to play my sprites. How can I do this? I have searched the docs and there is no tutorial and I have searched online but they have to use AnimationTree or a sprite sheet which I don't have. (I have individual sprites).

So my question is how can I use the AnimationPlayer Node in the same way as AnimatedSprite Node.

Note: The reason I am using AnimationPlayer instead of AnimatedSprite because I would like to change collisions during certain frames, but that's for another time.

Disclaimer: To prevent false answers I don't have a sprite sheet. I have individual sprites

# Answer
Found the answer. In Animation Player I just needed to add keys for each frame from my AnimatedSprite Node. Then I would also need to add an animation key to trigger the animation. Hope this helped anyone in the same situation as me. I changed collision by adding keys to change the shape of the collision shape.
> 2 votes

# Answer
The godot docs have a whole section on just this.

To summarize:

1. Just use a regular `Sprite` instead of `AnimatedSprite`
2. Set the `texture` to your spritesheet
3. Set `hframes`/`vframes` to tell the `Sprite` how to divide up your spritesheet
4. Add keyframes for the `Frame` property of the `Sprite` to the `AnimationPlayer`
> 2 votes

---
Tags: animation, sprites, godot, gdscript
---


# Question
Title: How can I make my animation switch frames automatically without pressing any keys?
So I have been trying to figure out for so long how I can loop the frames on my animation automatically without entering user input to prompt movement of my object. I have four different frames for a sprite which I would like to loop, but at the moment it only shows the first frame. Here is the relevant code for my Play class (as the entire thing is too long):

```
package simpleslickgame;

import org.newdawn.slick.*;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

import java.util.Random;

public class PlayScreen extends BasicGameState {

    Image enemy;
    int enemyX = 800;
    int enemyY = 500;

    int RandomX;
    int RandomY;

    Animation blobfish, one, two, three, four;

    public PlayScreen(int state) {
    }

    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
        enemy = new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\enemy.png");

        Image[] blobfishOne = {new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-one.gif"), new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-one.gif")};
        Image[] blobfishTwo = {new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-two.gif"), new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-two.gif")};
        Image[] blobfishThree = {new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-three.gif"), new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-three.gif")};
        Image[] blobfishFour = {new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-four.gif"), new Image("C:\\Users\\User\\IdeaProjects\\Slick2D\\src\\main\\resources\\blob-four.gif")};

        one = new Animation(blobfishOne, 200,true);
        two = new Animation(blobfishTwo, 200, true);
        three = new Animation(blobfishThree, 200, true);
        four = new Animation(blobfishFour, 200, true);
        blobfish = one;

    }

    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {

        blobfish.draw(RandomX, RandomY);

        Random enemyX = new Random();
        Random enemyY = new Random();
        RandomX = enemyX.nextInt(1500);
        RandomY = enemyY.nextInt(1000);

    }

    public void update(GameContainer gc, StateBasedGame sbg, int delta) {
        Input input = gc.getInput();
        blobfish.start(); //I thought this would have ran the animation.

        isMoving = true;
        keyispressed = true;

        if (keyispressed) {
            isMoving = true;
        }

    }

    public boolean mouseClicked() {
        return true;
    }*/
    }
        public int getID () {
            return 1;
        }
    }

```

I did think that the 'blobfish.start();' line would have started the animation. The variable 'blobfish' is the animation and 'enemy' is the image.

I'm a serious noob when it comes to Java game dev so any help as to why the animation is not running would be greatly appreciated.

# Answer
Your main game loop should usually loop through 3 main processes.

Each of these processes usually run in context to a specific scene/screen in your game .. menu screen, gameplay screen, exit screen , etc.

Process input: this is usually where people use an observer design pattern and create an event dispatcher which dispatches events to game objects who are interested in receiving certain events .. mouse move events, keyboard events the game objects interpret those lower level events to “game events” and call functions on themselves

Update: this is where your game logic is updated where players positions should be. What everything should be “doing”

Render: this is where everything will finally get drawn.. sounds play all the magic of your game

All of these processes should follow ideas of single responsibility your characters shouldn’t know how to animate or draw .. that’s the responsibility of your render system to know how to draw characters.
> 1 votes

---
Tags: java, game-loop, slick
---


# Question
Title: Repeated nested game objects (UnityEngine.GameObject.gameObject)
I created a `UnityEngine.GameObject` and inspect its properties while in debug mode.

```
GameObject obj = new GameObject();

```

When I inspect the object, it has a property hierarchy similar to:

```

active:true
activeInHierarchy:true
..
gameObject:New Game Object (UnityEngine.GameObject)
    active:true
    activeInHierarchy:true
    ..
    gameObject:New Game Object (UnityEngine.GameObject)
      active:true
      activeInHierarchy:true
      ..
      gameObject:New Game Object (UnityEngine.GameObject)

```

If I execute, something like, in a debugger console:

```
new UnityEngine.GameObject().gameObject.gameObject.gameObject;

```

it would still return the same `New Game Object`.

Is the problem in my debugger or Unity? I'm using Unity 2018.4.11f1.

# Answer
> 3 votes
`.gameObject` returns the current GO. This is the intended behaviour.

---
Tags: unity
---


title: Unusual leveling up mechanism?

text:
# Question
Title: Unusual leveling up mechanism?
About player leveling up, most (or maybe all..?) RPG games are like this:

1. Kill enemies (for experience points)
2. Level up (for more attack power)
3. Repeat

It's fun in the low levels, but later, it gets dull and boring; the game becomes more like increase your numbers to see more numbers.

I'm making an RPG game. I'm thinking of giving the player mini-quest(s) for each level to level up. For example, to reach level 2, player must fulfill the following:

* Gain 10 EXP points.
* Find an Ancient Jar.
* Kill a Blue Wolf with a single attack.

**So my question is:** Are there games that have done this (I haven't seen/heard of any)? Is it good or bad idea? Even if there are games that have done this technique, why most (or all) RPG games are going with the kill-levelup-repeat process?

# Answer
## Leveling as a progression systems

Although leveling is almost a synonym of RPG, in that I say RPG and you imagine levels – and this has its roots in table top, pen and paper, RPGs and war games – as game designer, you should be thinking of progression systems.

*RPG is a label, used to classify games, you do not have to be limited to it (unless you are submitting to a game development competition or something like that).*

First of all, experience and levels are means to simulate characters getting stronger. You need to decide on theme of your game. On its "fantasy". Often, we have power fantasy, then getting stronger is part of the theme, and then leveling is a core mechanic. However, that might not be the case for a given particular game.

---

A vanilla leveling system has a couple distinctive characteristics when it comes to progression systems:

* They are linear. You earn level 1, then level 2, and so on.
* They are not locked to an area or boss.

Your variation is still leveling, still linear. Except, the player has to figure out what exactly to do for each level. You are removing to option to decide where to go for leveling.

I suppose, in that case, it make sense to allow to get them out of order. However, then, it also makes sense to scale them, so that whatever the player chooses to do first, is the easier, and whetever the player chooses to do later is harder.

---

By the way, one motivation for a grindy game, is to extends game play time, and that is a selling point. In the case MMOs it is also so that it allows time to create more content. Although, sometimes an RPG is grindy because the quests are not great.

---

## Other progression systems

You can, of course, mix and match progressions systems. Give them flavor. In fact, it is very easy to use levels to unlock progression mechanics instead of simply having curves for the different stats as a function of the level.

For example, some RPGs grants you points to allocate upon level up. Some will grant particular abilities at certain levels, some even make you choose between abilities. There could also be items that directly affect stats or straight up grant a level up, etc…

**Addendum**: I also want to mention that some games level up abilities or weapons instead of characters.

---

Now, take, for example, games such as Metroid or Zelda, where the player will find items that increment their stats (more missiles, more hit points, etc…) or grant new abilities (often in the form of unique items). They are not labeled as levels, however they are a valid progression system.

Pay particular attention to abilities, because they are not just numbers. In particular if used as they are in Metroid and Zelda games, where they allow access to new areas.

Upgrades are not inherently linear, it is possible to allow the player to acquire – at least some – of these upgrades out of order. However, they are tied to a location.

**Note**: Using procedural generation to place upgrades in the game world is viable.

I also would like to mention card collecting games, where getting more and rarer cards is the progression system.

---

Progression does not have to be in-game. If the game is heavily skill based, then the progression is just the players improving their skill. There is also knowledge as progression, that is, the progression is figuring out what to do.

---

## The scaling problem

Let us consider scaling. If we have a character that gains experience by defeating enemies… this experience becomes levels… but the enemies scale with the level of the character… then the character might not feel stronger. The character would be becoming stronger and the enemies too, at the same rate. So, why would you do that? Instead you do not scale the enemies… the result is that after a while they are not a challenge but a chore.

Scaling enemies with level is something that should be used sparingly. In particular, it makes sense for bosses and unique enemies, but not for the fodder enemies.

When enemies are becoming too weak for the player, you want to encourage them to go to a new area where enemies are stronger. This is usually done with a quest to go the new area. Also, enemies could give less experience the higher level the character is, making it inefficient for leveling to stay in the same place.

**Addendum**: To be honest, the loop of enter new area, then do quests for the area, then quests move you to new area, can be boring. *I no longer find it appealing.* Not only it is repetitive, but also, it is hand-holding. *Plus, it can lead to towns that do not feel alive.* This is not about leveling, so I'll leave it at that.

---

## On quest design

What you suggest is not entirely unprecedented. There have been games that tie a progression system to something similar to your mini-quests. Think achievements, which grant titles, which have status bonuses. So, you kill a blue wolf and you gain the title blue wolf slayer, which grants extra damage… or something like that. We have seen this in games. It is a progression system. Just, not as a leveling mechanic.

We need to think about the ways the player can interact with the world. If the answer is going (to new areas) and killing (enemies). Well, you are going to gain experience by killing stuff (and perhaps entering new areas). Guess what player will be doing 99% of the time. Don’t get me wrong, it can be very engaging if the mechanics have intrinsic rewards (people enjoy killing enemies, so that killing enemies is the motivation, not the means for something else).

You do not need to grant experience from killing enemies (you can, you do not have to). In fact, quests could be the sole source of experience. And the fact that they are finite works well with a level cap. *There could be, of course, quest that can be repeated.* Then people would not be grinding for levels, but questing... your job is then to make those quests interesting.

---

There are four common kinds of interactions we find in RPGs: “**go**”, “**talk**”, “**take**” and “**kill**”, these give you some variety in quest design (being “**go** to area w and **kill** x and from them **take** y amount of z and **talk** to me” very prominent)… but, yeah, that is what they all do, isn't it?

It becomes boring because it does not deviate much from the same formula. In fact, deviating too much is a risk. For example escort missions are often not very engaging, despite the addition of a quest mechanic which technically mean variety.

Ideally you have a greater variety of quest types, but not by convoluted quest mechanics, but by more kinds of interactions. In fact, quests that have more than one way to complete them are often more appealing. *However, consider it in the context of the theme of the game.* Failure in executing these quests one way could results in the player falling back to a different way to approach them. *I'll suggest old Fallout games and Hitman for inspiration.*

Having more kinds of interactions makes a huge difference. See for example Pokémon. You can “kill” or you can “capture” the enemies. You build the game on top on that, and you get something that feels very different to the traditional RPGs. *And probably gets labeled as a Pokémon clone.*

There are other things that you can include in your quest design for extra variety. For example, “craft” and “build” are kinds of interactions that have earned their place in gaming. *Building your game on top of these will lead to something like Minecraft, or Factorio.*

I would also suggest to separate “talk” and “give”. *And also, depending on the game, stuff like “steal”, “persuade”, “hack”… which are great for alternative ways to complete quests.*

---

By the way, each one of these kinds of interactions could have their own progression system associated with them. For example, traversing progression could be mounts, or unlocking fast travel points.
> 5 votes

# Answer
Beacuse RPG Games are level orianted. Player's level gets up. Unlock new things. Gets gold. Buys something on shop. You can't change this formula this is part of RPG Games. Main part of RPG games was story part with this formula this will be bad but some developers adds good thing to game for example bad endings/good endings/shops etc.... Actually real life was a Rpg game . Beacuse you earn money buy new things upgrade your life and die. Rpg games formula was similar to real life.
> 0 votes

---
Tags: game-design
---


# Question
Title: Unity - Save/load in a sandbox game, how to instantiate saved objects
I have a game where a player can place GameObjects.

I can save/load this GameObjects data with using JSON, for example its position, but I cannot think of a good way to tell my save-file (and my load) what Prefab it needs to instantiate at position X.

How I could this be done in a clever way?

# Answer
> 1 votes
Several possibilities here. But you could simply have a dictionnary of ID/Prefab saved in a Scriptable Object that would act as a database for you. Then you would just have to save the ID of the prefab you want in your JSON save file. At runtime, when you load your JSON file, you'll end up with a bunch of IDs, and the only thing you'll have to do is to go to your Scriptable Object that contains the ID / Prefab relation and instantiate the right prefab for the given ID.

If you're not familiar with Scriptable Object you can find the documentation here. All it will require is to create a Serializable Class that contains an integer variable for the ID and a transform variable for the Prefab. Then create a simple Scriptable Object with a list of that class you've just wrote. Et voila, your "database" with ID / Prefab relation has been created.

# Answer
> 0 votes
what you are looking for is called serialization and deserialization.

you want to serialize your environment on save and deserialize it on load.

for this you have lots of options.

you can make it on your own using json or XML that makes everything much more controlled for you or use unity plugins.

what can i suggest is to use put your prefabs in Resources folder as makes you access your prefabs with string using **`Resources.Load()`** you just have to make you prefab same name of what you serialized in json or xml the just using any json or xml parser get all of your objects an components.

---
Tags: unity, savegame, json
---


# Question
Title: OpenGL Water reflection seems to follow camera yaw and pitch
I'm attempting to add reflective water to my procedural terrain. I've got it to a point which seems like it's reflecting however when I move the camera left/right/up/down the reflections move with it.

I believe the problem has something to do with the way I convert from world space to clip space for the projective texture mapping.

Here is a gif of what is happening. http://i.imgur.com/PDta5Qu.gifv

**Vertex Shader**

```
#version 400
in vec4 vPosition;
out vec4 clipSpace;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main ()
{
  clipSpace = projection * view * model * vec4(vPosition.x, 0.0, vPosition.z, 1.0);
  gl_Position = clipSpace;
}

```

**Fragment Shader**

```
#version 400
in vec4 clipSpace;
out vec4 frag_colour;
uniform sampler2D reflectionTexture;

void main ()
{
    vec2 ndc = (clipSpace.xy / clipSpace.z) / 2.0 + 0.5;
    vec2 reflectTexCoords = vec2(ndc.x, -ndc.y);
    vec4 reflectColour = texture(reflectionTexture, reflectTexCoords);

    frag_colour = reflectColour;
}

```

**I'm using this code to move the camera under the water's surface to get the reflection**

```
float distance = 2 * (m_camera->GetPosition().y - m_water->GetHeight());
m_camera->m_cameraPosition.y -= distance;
m_camera->m_cameraPitch = -m_camera->m_cameraPitch;

```

If this is insufficient code to diagnose the problem, I'll post more. I tried to keep it to what I thought could be the problem.

# Answer
The code corresponds to the very good Water Tutorials from ThinMatrix. I also had the same problem with the camera today. I forgot that changing the Pitch requires an update of the camera vectors - especially the Front-Vector. In the InvertPitch() function, the Update function of the camera class must be called:

```
void sg::ogl::camera::LookAtCamera::InvertPitch()
{
    m_pitch = -m_pitch;

    // Update Front, Right and Up Vectors using the updated Euler angles.
    Update();
}

void sg::ogl::camera::LookAtCamera::Update()
{
    // Calculate the new Front vector.
    glm::vec3 front;
    front.x = cos(glm::radians(m_yaw)) * cos(glm::radians(m_pitch));
    front.y = sin(glm::radians(m_pitch));
    front.z = sin(glm::radians(m_yaw)) * cos(glm::radians(m_pitch));
    m_front = normalize(front);

    // Calculate the new Right and Up vector.
    m_right = normalize(cross(m_front, m_worldUp));
    m_up = normalize(cross(m_right, m_front));
}

```

Now the right ViewMatrix can be created:

```
glm::mat4 sg::ogl::camera::LookAtCamera::GetViewMatrix() const
{
    return lookAt(m_position, m_position + m_front, m_up);
}

```
> 2 votes

---
Tags: opengl, c++, water, reflection-rendering
---


# Question
Title: Complicated How to create objects that fill a specific area?
How to create objects that fill a specific area? How to instantiate cubes within a random 2D form ... Trying not to leave the black lines.

@ JaamiParvez

Objetive:

# Answer
I'm not very familiar with C# so most of the code will be pseudo code. You probably have to adapt it to work for you. You wrote in a comment that you were okay with using triangles instead of squares, so the example below is generating triangles and edge shapes.

I also don't know anything about the coordinate system that you're using in your code, what engine you're using etc. In my code example below, the coordinate system has (0, 0) in the upper left corner of the window, with X+ pointing to the right and Y+ pointing down.

I can't help you with the rendering of the triangles and how the rigid bodies should be created, based on the triangles' information etc, since I, like I said, don't know what engine/library and physics library etc that you're using.

An example picture has also been attached below to show how the triangles are placed and how I've numbered the points of the triangles.

```
// Convenient way to store an X- and Y position in one combined unit
public struct Vector2D
{
    public Vector2D(void)
    {

    }

    public Vector2D(const float xPosition, const float yPosition)
    : x(xPosition)
    , y(yPosition)
    {

    }

    public x;
    public y;
};

// A simple 2D triangle struct containing 3 positions, one for each point in the triangle
public struct Triangle2D
{
    public Triangle2D(void)
    {

    }

    public Triangle2D(const Vector2D& rPoint1, const Vector2D& rPoint2, const Vector2D& rPoint3)
    : point1(rPoint1)
    , point2(rPoint2)
    , point3(rPoint3)
    {

    }

    public Vector2D point1 = new Vector2D(0.0f, 0.0f);
    public Vector2D point2 = new Vector2D(0.0f, 0.0f);
    public Vector2D point3 = new Vector2D(0.0f, 0.0f);
};

// The list containing the points that's forming the shape
List<Vector2D> pointList = new List<Vector2D>();

pointList.Add(new Vector2D(0.0f, 0.0f));
pointList.Add(new Vector2D(0.7f, 0.5f));
pointList.Add(new Vector2D(0.8f, 0.4f));
pointList.Add(new Vector2D(1.0f, 0.8f));
pointList.Add(new Vector2D(0.0f, 0.8f));

// Creating the collision triangles

// A list containing the generated triangles, based on the above shape's points
List<Triangle2D> triangleList = new List<Triangle2D>();

// The red triangle in the image below
triangleList.Add(new Triangle2D(pointList[0], pointList[1], pointList[4]));

// The purple triangle
triangleList.Add(new Triangle2D(pointList[1], pointList[2], pointList[4]));

// And the orange triangle
triangleList.Add(new Triangle2D(pointList[2], pointList[3], pointList[4]));

```

And if you would like to generate edge shapes / collision lines instead:

```
// A simple 2D line struct containing 2 positions, one for each point in the line
public struct Line2D
{
    public Line2D(void)
    {

    }

    public Line2D(const Vector2D& rStart, const Vector2D& rEnd)
    : start(rStart)
    , end(rEnd)
    {

    }

    public Vector2D start   = new Vector2D(0.0f, 0.0f);
    public Vector2D end     = new Vector2D(0.0f, 0.0f);
};

// Creating edge shapes / collision lines

// A list containing the generated lines, based on the above shape's points
List<Line2D> lineList = new List<Line2D>();

// Line 1 - point 0 = start, point 1 = end
lineList.Add(new Line2D(pointList[0], pointList[1]));

// Line 2 - point 1 = start, point 2 = end
lineList.Add(new Line2D(pointList[1], pointList[2]));

// Line 3 - point 2 = start, point 3 = end
lineList.Add(new Line2D(pointList[2], pointList[3]));

// Line 4 - point 3 = start, point 4 = end
lineList.Add(new Line2D(pointList[3], pointList[4]));

// Line 5 - point 4 = start, point 0 = end
lineList.Add(new Line2D(pointList[4], pointList[0]));

```

Result:
> 2 votes

---
Tags: c#
---


# Question
Title: How to attach main camera to script component of a prefab?
So I have a prefab which is an item drop and a timer attached to the main camera. When the player collides with the item, I need the item to destroy then add time to the timer.

The itemdrop handling script looks like this:

```
   public LifeTimer LifeTimer;

   // Destroy sprite once player collides into it
   void OnCollisionEnter2D(Collision2D col){
       if(col.gameObject.name=="Player"){
           Destroy(gameObject);
           LifeTimer.currentTime += 10;

       }
   }

```

The life timer is a reference to my script as follow which is attached to the main camera.

```
public class LifeTimer : MonoBehaviour
{

    // Once level initializes, start current time to starting time
    public float currentTime = 0f;
    public float startingTime = 10f;

    [SerializeField] Text lifeTimerText;

    void Start(){
        currentTime = startingTime;
    }

    void Update(){

        // Decrement time per second every second
        currentTime -= 1*Time.deltaTime;
        // Set currentime to text on screen
        lifeTimerText.text = currentTime.ToString ("0");

        // Load Game Over Screen when time goes to 0
       if(currentTime <= 0){
            Application.LoadLevel(0);
        }
    }
}

```

I realized I can't attach the main camera to the life timer component of the item drop script because the item prefab is not instantiated yet. What would be the best way to do what I'm trying to do, which is to add time to the timer. The on collision and destroying aspect works perfectly.

Thank you for any guidance

# Answer
Let's do it the other way ;) When you Instantiate ItemDrop, you can retrieve `LifeTimer` from the Camera and save it. For instance, right after the instantiate of your prefab, the method `Start()` of your object `ItemDrop` will be called by Unity. In this, you could easily get the Camera (via `Camera.main`if it's the main camera of your game), and get the `LifeTimer` component that's attached to it (via a simple `GetComponent()`). When the `OnCollisionEnter2D` is called, everything is set up and ready for the `ItemDrop` to add updat `LifeTimer`.

As a side note and for the only sake of learning and optimizing I'd suggest you to consider the following suggestions:

* Consider this line of your code: `public LifeTimer LifeTimer;`. Using the same case for a variable name and its type can be REALLY confusing. Like at first I thought that your `LifeTime` class was static, when it was just a regular class field. I'm not 100% fond of it but I'd suggest you to have a look at the C# coding convention (in there, every variable name is written in lower case).
* I don't know what the game is about and how many type of itemdrop you could have or even the number of them, or what object is in charge of instantiate them, but it looks like the perfect playfield for design patterns: Observer. I'd suggest you to have a look at it to have a clean and solid architecture with good responsibility about what is calling what and when. More about the observer pattern here.
> 2 votes

---
Tags: unity, unityscript
---


# Question
Title: How to access the parent of a cloned prefab?
I have a menu that gets populated at runtime with buttons whose text components are based on objects that the game manager has in its databases. At the start, the menu is empty:

See that "A" graphic? It's a button called **Button\_Magic\_DropDown** that activates/deactivates the panel called **Panel\_MagicMenu**. At runtime, regardless of whether the panel is active, its child panel **Empty\_Inset\_MagicMenu** gets 6 children, which are all instances of the button prefab, **Button\_BattleMenu**. When one of these buttons are clicked, I want the panel called **Panel\_MagicMenu** to get deactivated. See image below:

What I am struggling with is deactivating \[the parent panel of a \] panel that a button sits in when it is clicked. I am trying to do this by getting the second parent programmatically and deactivating it. Here is the script containing that function **OnClickDeactivatePanel()**, which I am assigning in the button *prefab*:

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

public class BattleUI : MonoBehaviour
{
    public void ToggleActive(GameObject panel)
    {
        panel.SetActive(!panel.activeInHierarchy);
    }

    public void OnClickDeactivatePanel()
    {
        //On click, deactivates the panel that the button sits in, two parents up
        GameObject secondParent = gameObject.transform.parent.parent.gameObject;
        //Debug.Log("Second parent is " + secondParent);
        secondParent.SetActive(false);
    }
}

```

As you can guess, this didn't work. Unity is unable to identify the parents of an instanced object this way. I get a null-reference error. What can I do?

Here is the button prefab, **Button\_BattleMenu**, if it helps:

This is obviously an encapsulation issue. The buttons are cloned into the menu during an Awake() function in another script.

**EDIT:** Changing **Awake()** to **OnEnable()** and **OnStart()** didn't work, but I appreciate the help. Here is the script that loads the buttons (you can see I have an impending decoupling problem on my hands:

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

public class _CharStatManager : MonoBehaviour
{
    public float scaleFactor = 0.75f;
    public float resolution = 100f;
    [SerializeField] GameObject entry;
    private TMP_Text tmpText;

    // MAGIC
    public List<SpecialAttack> magicList = new List<SpecialAttack>();
    private uint magicList_size;
    [SerializeField] GameObject magicContainer;
    [SerializeField] GameObject magicContainerParent;

    // ITEM
    public List<Item> itemList = new List<Item>();
    private uint itemList_size;
    [SerializeField] GameObject itemContainer;
    [SerializeField] GameObject itemContainerParent;

    // ATTACK
    [SerializeField] GameObject attackContainer;
    [SerializeField] GameObject attackContainerParent;

    //DEFENSE
    [SerializeField] GameObject defenseContainer;
    [SerializeField] GameObject defenseContainerParent;

    void Awake()
    {
        //Don't Destroy:
        DontDestroyOnLoad(this.gameObject);
        float multiplier = Mathf.Pow(resolution * scaleFactor,-1);
        //=================================================================
        //=================================================================

        //+==================================+
        //|$$$$$$$$$$$ MAGIC MENU $$$$$$$$$$$|
        //+==================================+

        //Populate list of all Special Attacks (magic)
        magicList.Add(new SpecialAttack("Jump", -15, -2,SpecialAttack.Types.PhysDamage));
        magicList.Add(new SpecialAttack("Fireball", -15, -2,SpecialAttack.Types.Fire));
        magicList.Add(new SpecialAttack("Super Jump", -20, -5, SpecialAttack.Types.PhysDamage));
        magicList.Add(new SpecialAttack("Super Flame", -20, -5, SpecialAttack.Types.Fire));
        magicList.Add(new SpecialAttack("Ultra Jump", -25, -8, SpecialAttack.Types.PhysDamage));
        magicList.Add(new SpecialAttack("Ultra Flame", -25, -8, SpecialAttack.Types.Fire));

        magicList_size = (uint)magicList.Count;
        float buttonHeight = entry.GetComponent<RectTransform>().sizeDelta.y;

        /*This is where it gets tricky: Need to expand the height of the
         * magic menu "container" before we instantiate more buttons.
         * Those buttons will be offset automatically thanks to Vertical Layout Group component.*/

        // Resize Container:
        float magicContainerHeight = magicContainerParent.GetComponent<RectTransform>().sizeDelta.y;
        float magicTargetHeight = magicContainerHeight + buttonHeight * (magicList_size - 1);
        magicContainerParent.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, magicTargetHeight);
        // Instantiate children of Container (Vertical Layout Group component will take care of alignment for me)
        for (int i = 0; i < magicList_size; i++)
        {
            GameObject newMagicButton = Instantiate(entry, magicContainer.transform, false);
            newMagicButton.GetComponentInChildren<TMP_Text>().text = magicList[i].menuName;
        }

        //=================================================================
        //=================================================================

        //+==================================+
        //|$$$$$$$$$$ DEFENSE MENU $$$$$$$$$$|
        //+==================================+

        GameObject newDefenseButton = Instantiate(entry, defenseContainer.transform, false);
        newDefenseButton.GetComponentInChildren<TMP_Text>().text = "Defend";

        //=================================================================
        //=================================================================

        //+===================================+
        //|$$$$$$$$$$$ ATTACK MENU $$$$$$$$$$$|
        //+===================================+

        PhysicalAttack onlyAttack = new PhysicalAttack("Punch Glove", -10);
        GameObject newAttackButton = Instantiate(entry, attackContainer.transform, false);
        newAttackButton.GetComponentInChildren<TMP_Text>().text = onlyAttack.menuName;

        //=================================================================
        //=================================================================

        //+=================================+
        //|$$$$$$$$$$$ ITEM MENU $$$$$$$$$$$|
        //+=================================+

        //Populate list of items (magic)
        itemList.Add(new Item("HP Shroom","Recover 30hp."));
        itemList.Add(new Item("Power Star","Strength + 3"));
        itemList.Add(new Item("Chocolate Mousse","A treat you shouldn't keep to yourself."));
        itemList_size = (uint)itemList.Count;

        // Resize Container:
        float itemContainerHeight = itemContainerParent.GetComponent<RectTransform>().sizeDelta.y;
        Debug.Log(itemContainerHeight);
        float itemTargetHeight = itemContainerHeight + buttonHeight * (itemList_size - 1);
        Debug.Log(itemTargetHeight);
        itemContainerParent.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, itemTargetHeight);
        // Instantiate children of Container (Vertical Layout Group component will take care of alignment for me)
        for (int i = 0; i < itemList_size; i++)
        {
            GameObject newItemButton = Instantiate(entry, itemContainer.transform, false);
            newItemButton.GetComponentInChildren<TMP_Text>().text = itemList[i]._menuName;
        }
    }
}

```

# Answer
> 1 votes
Swap the `Awake()` to either `OnEnable()` or `Start()` just to be sure you are not referencing the panels before they are fully loaded, sized and able to cache.

If it still shows a null then you can use `transform.root` to get the top transform then perform `tansform.GetChild(index)` with index being the panel you want to disable.

If neither help but you must have dynamically I would suggest to get the root then load those children into a array to loop through and change as you want.

A better solution may be to just cache the windows and set Active to false on Start or the simplest solution would be to make public so they are always ready and available.

# Answer
> 0 votes
Well, it works folks. In fact, it works exactly as it was supposed to. Why didn't it before? Because the OBJECT I was using in the Editor that had the same script on it was the WRONG OBJECT! I was using the Canvas, not the button prefab, both which have the same script. This makes PERFECT SENSE because the canvas is the root, and would not have a parent! XD

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

```
public class BattleUI : MonoBehaviour
{

    public void ToggleActive(GameObject panel)
    {
        panel.SetActive(!panel.activeInHierarchy);
    }

    public void CloseOnClick()
    {
        //On click, deactivates the panel that the button sits in, two parents up

        GameObject secondParent = gameObject.transform.parent.transform.parent.gameObject;
        //Debug.Log("Second parent is " + secondParent);
        secondParent.SetActive(false);
    }
}

```

Thank you so much @Draco18s and @Justin Markwell for helping me

**EDIT: @JUSTIN MARKWELL WAS RIGHT!** So I just realized on demonstration to a colleague that it is possible to open multiple menus at the same time with this script. That must not be. So I realized that @JustinMarkwell's answer was the best option. It goes to the root (Canvas) and deactivates every panel under it:

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

public class BattleUI : MonoBehaviour
{

    private void ToggleActive(GameObject panel)
    {
        panel.SetActive(!panel.activeInHierarchy);
    }

    private void CloseOnClick()
    {
        Transform root = transform.root;
        GameObject magicPanel = root.GetChild(0).transform.GetChild(0).transform.GetChild(2).gameObject;
        GameObject attackPanel = root.GetChild(0).transform.GetChild(1).transform.GetChild(2).gameObject;
        GameObject defensePanel = root.GetChild(0).transform.GetChild(2).transform.GetChild(2).gameObject;
        GameObject itemPanel = root.GetChild(0).transform.GetChild(3).transform.GetChild(2).gameObject;
        magicPanel.SetActive(false);
        attackPanel.SetActive(false);
        defensePanel.SetActive(false);
        itemPanel.SetActive(false);
    }
}

```

This takes us (halfway) there because it closes every open panel. Of course, multiple panels should not be open in the first place--UGH! So what I really want to do then is stick to my original script and use Justin's idea to make sure all other buttons' panels are deactivated when clicked. This post will be updated again.

**EDIT 2: ARMAGEDDON**

Ok, now we have it! I took the BattleUI script off all UI elements (except the button prefab) and stuck them only to the dropdown menu buttons. Then I updated the ToggleActive() script (renaming it TogglePanel(), for clarity). The OnClick Editor will only list functions that have a maximum of 1 input (I guess) so all the panels I want to turn off must be accessed from the parent of the dropdown button the script is attached to:

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

public class BattleUI : MonoBehaviour
{
    public void TogglePanel(GameObject thisPanel)
    {
        int thisButtonIndex = gameObject.transform.GetSiblingIndex();
        thisPanel.SetActive(!thisPanel.activeInHierarchy);
        Transform firstParent = gameObject.transform.parent;
        for (int i = 0; i < 4; i++)
        {
            if (i != thisButtonIndex)
            {
                firstParent.GetChild(i).transform.GetChild(2).gameObject.SetActive(false);
            }
        }
    }

    public void CloseOnClick()
    {
        //On click, deactivates the panel that the button sits in, two parents up
        GameObject secondParent = gameObject.transform.parent.transform.parent.gameObject;
        secondParent.SetActive(false);
    }
}

```

This allows makes sure that no other menu is open when I click a dropdown button, and I have only 2 lines of code to close a menu once an instantiated button (option) is clicked:

So now the actual solution has been found! Thanks to Justin Markwell for pointing me in the right direction, he gets all the credit

---
Tags: unity, gui, instancing
---


title: Continents with Simplex noise

text:
# Question
Title: Continents with Simplex noise
How do I turn Simplex noise like:

into something like:

or

The noise has too many white spots and varies too much to represent things like continents. Where it's water, water, water, and then land with cut out edges.

# Answer
It looks like you're looking for "Turbulence", "Fractional Brownian Motion", or something similar.

This is where we take multiple samples of the noise at different scales - like the different panes in your first image - and add them together.

Each noise sample is commonly called an "octave". For each octave we add, we sample at a higher frequency (so the noise gets denser), but we also scale its output to a smaller amplitude (so the noise gets fainter).

So we might sample the lowest octave (one big white blob) with amplitude 1, then the next octave at amplitude 1/2, then the next at amplitude 1/4...

This gives large variation over long scales (the difference between continent and ocean), with each added octave having a more and more gentle influence, shaping the highs and lows and adding more variation to the coastline in-between.

Here are the 8 panes of noise from your image at the top, averaged together with the weight reduced by about half at each octave:

Note how we get a cloudy-looking noise, with feature variation at all scales. There are global highs and lows created by the low octaves (the bright white on the left / dark black along the top and bottom), but also smaller highs and lows everywhere in-between. This gives the noise a fractal quality similar to real landscapes, where the closer you look, you keep finding more detail.

Now if we just colourize this map, drawing the dark greys as blues, and the lighter greys as sandy/leafy/rocky, we get something that begins to look like continents!

One thing to watch out for: usually we'll want to de-correlate the noise we use at each octave, by changing the hash function or applying a spatial offset. That way you avoid artifacts from repeated features in the vicinity of the origin (which doesn't automatically change as we increase our frequency scale)

You can play with how you generate and scale your noise at each octave to get different effects - taking the absolute value to get "ridge noise" for mountain spines, squaring the noise to change its distribution, etc. There are lots of great articles with different suggestions about how to craft your noise for just the right kind of terrain.
> 32 votes

# Answer
Not with noise alone.

The other answer is correct, you overlay several octaves of noise to get a realistic structure. But you need to bring in physics as well or it won't be a result resembling reality.

The first approach is to add an erosion model. There's a lot of good sources for how to do that available. This will create ridges and channels in your mountains and get rid of the ten thousand tiny islands problem.

The second approach is to more straighforward modulate the results. Run a calculation of land size just above the waterline and remove small islands.

If your goal is realistic continents, you can also go away from noise and use plate tectonics, like here: http://davidson16807.github.io/tectonics.js/
> 10 votes

---
Tags: procedural-generation, simplex-noise
---


# Question
Title: SpriteBatch.Draw has Padding on Monogame.Android
I am using Monogame to create a small Android game. I am trying to draw a sprite to the Android screen but it seems to have a padding of some pixels. The same game works fine on desktop.

How can I remove the padding? The graphic itself has no borders etc; the problem is also reproducible with any other sprite.

I have created a new project in VS2019 with the Monogame templates for VS2017 and tried to reproduce this behavior in a new project.

It seems that the problem has something to do with the notch of my emulator. In an emulator without a notch the problem seems to be non existent. I found this thread on the Monogame community but it hasn't got any answers.

My source code looks in its simplest form now as follows:

```
    private Texture2D _texture;

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        _texture = Content.Load<Texture2D>("BasicTV");
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();

        spriteBatch.Draw(_texture, Vector2.Zero, Color.White);

        spriteBatch.End();
        base.Draw(gameTime);
    }

```

The result of this code is this:

The Game is compiled for Android 8.1 and I use the Monogame framework 3.7.1.

# Answer
> 2 votes
After trying several things it seems that it is a problem with version 3.7.1 of Monogame. I switched to Version 3.6 and the padding is gone. I will update this answer/question if I find the reason why 3.6 behaves differently then 3.7.1

Edit: I switched to version 3.8 and the problem seemed to still exist. But it seems that with this little snippet the problem could be fixed (found here) .

```
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        //...
        HideSystemUI();
        g.Run();
    }
    private void HideSystemUI()
    {
        SystemUiFlags flags = SystemUiFlags.HideNavigation | SystemUiFlags.Fullscreen | SystemUiFlags.ImmersiveSticky;
        this.Window.DecorView.SystemUiVisibility = (StatusBarVisibility)flags;
    }

```

---
Tags: c#, android, monogame, visual-studio
---


# Question
Title: How to handle forward/backward movement in an oblique top-down view
I'm making a pseudo-2D top-down game, where my assets are actually 3d but I use an orthographic projection to introduce more depth.

I saw a picture of how the game "Enter the Gungeon" was actually made in unity 3d.

When I tried doing something likes this I put the camera in orthographic view and after some adjusting I got it to look kind of like this.

The problem is that movement in the z-axis (away / toward the viewpoint, or up and down on the screen) feels very slow because of the whole orthographic thing. You can notice this when moving a player for example.

When I simply increased the speed of the player in the z-axis it felt pretty normal, but I am wondering if that would introduce some unforeseen consequences?

I couldn't find any guides, posts or videos about this. How should I solve this movement problem?

# Answer
It sounds like you're dealing with foreshortening.

When you look down at the z-axis along a diagonal, only part of the length of a z-pointing vector goes into climbing your screen. The other part goes into receding into the depth "behind" your screen.

So a given worldspace distance along the x axis — which points perpendicular to your view — covers more on-screen pixels than the same worldspace distance along the z, where part of the length recedes away from the view.

As you pointed out, scaling your z movement to compensate can fix the most obvious consequences of foreshortening. So if that works for your game, do it.

There are situations where we wouldn't want to patch the artifact this way though. Let's say our game involves dodging the circular blast radius of bombs. If the radius is computed in world space, then players will find they can dodge faster along the z-axis than they can along the x, adding a bias in your strategy you might not have intended. And making all your circle checks into ellipses to compensate for foreshortening would get super messy fast.

Another solution is to eliminate foreshortening on your z axis altogether. It's optional. You can use an oblique projection to effectively scale the vertical axis of your camera's image sensor, so that 1 unit along the z translates to the same number of pixels as 1 unit along the x. This approach also saves you from having to lean your vertical assets back away from the camera as they do in some games to mitigate the foreshortening on wall/character/prop art.
> 4 votes

---
Tags: unity, 2d, 3d, movement
---


# Question
Title: Making a 2d shooting game. need a working shoot function
I tried to follow some guides but couldn't get their functions to work in my program. What i tried is commented out in my code(the for loop). I want a working function on space press create a bullet that goes right.

here is a fiddle: https://jsfiddle.net/tmanrocks999/7mLpo8uj/

code:

```
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
    border:4px solid #d3d3d3;
    background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>

var myGamePiece;
var endGoalPiece;
var Enemy1;
var bullet;

function startGame() {
    myGameArea.start();
    myGamePiece = new component(30, 30, "red", 0, 240);
    endGoalPiece = new component(30, 30, "black", 450, 240);
    myEnemy1 = new component(30, 30, "green", 200, 240);
}

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.interval = setInterval(updateGameArea, 20);
        window.addEventListener('keydown', function (e) {
            myGameArea.key = e.keyCode;
        })
        window.addEventListener('keyup', function (e) {
            myGameArea.key = false;
        })
    },
    clear : function(){
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

function component(width, height, color, x, y) {
    this.gamearea = myGameArea;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    //this.gravity = 0.05;
    //this.gravitySpeed = 0;
    this.x = x;
    this.y = y;
    this.color = color;
    this.update = function() {
        ctx = myGameArea.context;
        ctx.fillStyle = this.color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
    this.newPos = function() {
        this.gravitySpeed += this.gravity;
        this.x += this.speedX;
        this.y += this.speedY; //+ this.gravitySpeed;
        this.hitBottom();
        this.hitTop();
        this.hitRight();
        this.hitLeft();

    }

   this.hitBottom = function() {
        var rockbottom = myGameArea.canvas.height - this.height;
        if (this.y > rockbottom) {
            this.y = rockbottom;

        }
        }
        this.hitTop = function() {
        var rockTop = 0;
        if (this.y < rockTop) {
            this.y = rockTop;

        }
        }
        this.hitRight = function() {
        var rockRight = myGameArea.canvas.width - this.width;
        if (this.x > rockRight) {
            this.x = rockRight;

        }
        }
        this.hitLeft = function() {
        var rockLeft = 0;
        if (this.x < rockLeft) {
            this.x = rockLeft;

        }
        }

function jump() {
  myGamePiece.gravitySpeed=-1;
}

}
 function shootGun(){

//var b = new bullet();
//var bullets = []
//bullets.push(b)

//for (var i = 0; i < bullets.length; i++) {
 bullet = new component(11, 5, "blue", myGamePiece.x+27 , myGamePiece.y+13 );
 bullet.newPos();
 bullet.speedX=1;
 }

function updateGameArea() {
    myGameArea.clear();
    myGamePiece.speedX = 0;
    myGamePiece.speedY = 0;
    if (myGameArea.key && myGameArea.key == 37) {myGamePiece.speedX = -1; }//left
    if (myGameArea.key && myGameArea.key == 39) {myGamePiece.speedX = 1; }//right
    if (myGameArea.key && myGameArea.key == 38) {myGamePiece.gravitySpeed = -1; }//jump
    if (myGameArea.key && myGameArea.key == 32) {shootGun()}//shoot gun
   //if (myGameArea.key && myGameArea.key == 40) {myGamePiece.speedY = 1; }// down
    myEnemy1.update();
    endGoalPiece.update();
    myGamePiece.newPos();
    myGamePiece.update();
    bullet.newPos();
    bullet.update();
}
</script>
<p>use the arrow keys on you keyboard to move the red square.</p>
</body>
</html>

```

I expect on space press for a bullet to keep being created like shooting a gun. but at the moment only 2 bullet is made then if you press space again it resets the bullet. I get why this is happening but cant get my for loop to work. I will add something to happen if it hits a enemy later.

# Answer
> 1 votes
The array which contains your bullet (`var bullets`) is declared as a local variable within the `shootGun()` function. This already can't work on the conceptual level, because it means that the list of bullets which are currently active in your game area only lives during the execution of the `shootGun` function and is discarded afterwards.

It needs to be a variable with global scope, just like the variables `var myGamePiece;` or `var Enemy1`.

Then it makes no sense for a loop `for (var i = 0; i < bullets.length; i++) {` to exist in the `shootGun` function. Yes, you need to do a loop over all bullets each frame in order to update their positions. But that loop belongs into your `updateGameArea` function, not the function which is supposed to create the bullets.

Also, `new bullet();` won't work because you didn't write the `function bullet()` yet. But the concept to use a constuctor-function to initialize the bullets seems sound. If you want `bullet` to have all the features of `component` and then some, then you might want to check out prototype inheritance in JavaScript.

---
Tags: javascript, html
---


# Question
Title: Programming logic to 2D point and click adventure/puzzle?
I am totally new to game development. I want to create a 2D Puzzle/Adventure point and click game similar to like 'Rooms' but scenes are connected. I have already done the inventory system but currently lack the functionality to be used with an object in a scene.

My question is how do I approach creating a system that will take in dynamic number of events? For example, I have key that will unlock the door, and the next scene I want to use it again without pre-programming this action specifically. I want to approach this in an efficient way so that I can use the system again for future games similar to this.

Can someone give me an idea because I am really stuck at this point. I don't want to program the game assigning individual scripts to each objects but rather do this systematically.

I am using Unity and C#

# Answer
First, we need to make an architecture decision: Where does the logic "key opens door" belong to? Is it a behavior of `Door` that it can be opened by `Key`? Is it a behavior of `Key` that it is able to open `Door`? Or is it something which belongs into neither class and should instead be encapsulated in an entirely separate `InteractionManager` which knows how each inventory object interacts with each environment object in the game?

There are good arguments to be made for each of these solutions. Which one to pick is mostly a subjective choice. The only thing that's important is that you stay consistent throughout your game. If you implement the Door-Key interaction in this way but other interactions between inventory items and environment objects a different way, you are going to end in chaos. So make sure you pick a solution which plays well with all the use-cases you plan to have in your game.

For sake of this answer, let's assume you picked the solution where the interaction logic is implemented in the item. In that case I would create a MonoBehaviour `Door` which serves as a marker for environment objects which can be opened with a key and a MonoBehaviour `Key` which has a method `Interact` and a property `Door fitsInto`. The `fitsInto` property would then get assigned to the right door in the inspector.

The `Interact` method gets called when the player uses a key on a door. How to implement *that* is outside of the scope of this answers because it is heavily influenced by how your game's UI works.

The Key class would then work like this (untested code!):

```
public Door fitsInto;

public void Interact(GameObject other) {
     // first, check if the other object actually has the "Locked" component:
     Locked locked = other.GetComponent<Locked>();
     if (locked == null) {
          // handle the case that this object isn't a door:
          Console.log("You can't find a keyhole on the " + other.name);
     } else {
          // check if it's actually the "Locked" object for this key:
          if (locked != fitsInto) {
               Console.log("The key doesn't fit.");
          } else {
               Console.log("The key fits!");
               // TODO: Replace the closed door with an open door, or change its state from closed to open
          }
     }
}

```

But you can of course also do it the other way around and have `Door` implement the `Interact` method while also knowing which key opens it. (again, untested code!)

```
public Key openedBy;

public void Interact(GameObject other) {
     // first, check if the other object actually has the "Key" component:
     Key key = other.GetComponent<Key>();
     if (key == null) {
          // handle the case that this object isn't a key at all:
          Console.log("You need a key to open this door, not a " + other.name);
     } else {
          // check if it's the right key for this door:
          if (key != openedBy) {
               Console.log("The key doesn't fit.");
          } else {
               Console.log("The key fits!");
               // TODO: Replace the closed door with an open door, or change its state from closed to open
          }
     }
}

```

And last but not least, let's look at the Interaction Manager solution. This architecture was used by a lot of classic point and click adventures, like those based on the SCUMM engine by Lucas Arts.

This solution is usually based on a large table which maps pairs of inventory items and scenery objects to the functions which implement their interaction logic.

If you want to create a new interaction, you just add it to the table.

When the player uses an inventory item with a scenery object, you search that table for an entry with that item and that object, and execute the function it maps to.
> 1 votes

# Answer
Polymorphism seems to be what you're looking for.

In the case you're describing, you could design your code to have a `PuzzleManager` object in your scene (that would inherit from `MonoBehaviour`), that would contain a list of `Puzzle` objects. The `Puzzle` could simply be an interface or a base class (if you're not comfortable with interfaces) with a unique method that would return a boolean `bool IsPuzzleComplete()`. Every class that would inherit from `Puzzle` would be in charge of the specific logic of the puzzle it describes.

In the case of a key/door puzzle, the `KeyDoorPuzzle` class would inherit from `Puzzle` and simply wait for the right key to be matched with the door it opens. When it happens, you just have to make the method `IsPuzzleComplete()` of the parent `Puzzle` class returning `true`. Now if you have that `PuzzleManager` object that is mainly a list of `Puzzle` it will be very simple to loop through the list and check the status of `IsPuzzleComplete()` of every contained `Puzzle`.

Bonus: You could even add a simple Observer pattern to this, to let your `PuzzleManager` be warned when a `Puzzle` is complete, without having to check the whole list of `Puzzle` every frame.
> 1 votes

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


# Question
Title: Need to programatically muffle game sounds
So I work on a multiplayer game that is set in space. There are essentially two environments for players to be in: inside a sealed space station (where there is air and thus sounds) and outside the station in the vacuum of space (where there is no air and no sound to hear).

For a while now, we've had it so that you cannot hear any of our game's sound effects while floating in a space with no air, and while that might be realistic, it's not very fun when the game is completely silent sans background music.

I'd much rather find some way to dynamically distort the sounds on the fly before they are played so that they seem to be muffled or dampened. I have no sort of background in making sounds or doing much of anything with them and all my searches have amounted to nothing; mostly finding things about sound editing programs.

The project is made in a C based language for game programming that is really obscure called Dream Maker or Byond. I can't seem to find any built-in features that are able to solve this problem for me. Any help would be much appreciated.

# Answer
A simple approximation for muffled sound is reducing the volume based on frequency.

High frequency sound is dampened more than low frequency sound.

Imagine standing in the street near a discotheque.... you hear base thump, but not the higher frequencies.

So with an equalizer, do something like this:

```
  |    |    |    |    |    |    +6
  |    |    |    |    |    |
  |    |    |    |    |    |
  |    |    |    |    |    |
  |    |    |    |    |    |
 [=]   |    |    |    |    |     0
  |   [=]   |    |    |    |
  |    |   [=]   |    |    |
  |    |    |  [=]    |    |
  |    |    |    |   [=]   |
  |    |    |    |    |   [=]   -6

 base                    treble

```

You need to do this filtering in the frequency domain, or maybe your sound library has a provision for this.
> 1 votes

# Answer
I think the simplest way to do this, at least as far as programming goes, is to have two sets of audio resources and switch between them. Not a great solution, I know.

---

I would argue for using OpenAL, or similar (DirectSound, for example). They already do some effects. There are also libraries for use them, making them easier to use or adding extra features.

---

As per Byond, the sound function takes a file name, and can do a few effects out of the box.

A simple effect you can do with what comes with it is to lower the frequency, lower the volume and add echo.

I found a couple Byond libraries that are either useful, or worth to study to figure out how to manipulate audio in Byond:

See also:

*By the way, I am not familiar wit that syntax. You say this is C?*

---

Baring that, to be able to apply effects in real time you will need to be in control of loading the audio buffer for playback. Any good old playback library will do. What matters is having the the opportunity to manipulate whatever you read from your resources before you send it to the audio buffer.

Assuming you have such playback library, what you are looking for is programmatic signal processing, programmatic audio signal processing to be more precise. I suggest to pick a library that already has them built in. Baring that, one that can do fast fourier transform and its inverse.

I think many people began by reading RIFF WAVE format (.wav) and working from there. However, given that that is an uncompressed format (which is great for ease of reading), you probably want to work with something else... for example Ogg files.

Try the library libsndfile, which sould allow you read multiple free audio formats (the linked page also has a list of a few similar libraries).

---

I found a couple documents that could help you implement some of those effects (assuming you are not using a library):
> 0 votes

---
Tags: c, sound, sound-effects
---


# Question
Title: frustum culling and exporting a big scene model
Let's assume that I created in Blender a race track with landscape. I can export it to single wavefront obj file and then load in my graphics engine using assimp but it doesn't allow to use frustum culling. Should I split such big scene too seperate objects or some model formats allow to split object within single file. How graphics engines load such big scenes ? Do you know some useful techniques/articles ?

# Answer
> 1 votes
In short, yes, you should split the scene. But I would advise that you use a more programmatic method rather than splitting by hand. And as below, will document my own approach and thoughts. You will reach your own conclusions on what you want to do, I hope this is guide in what does and doesn't work.

A lot of game engines to pre-process their scenes prior to use in, quake developers actually had a BSP tool that used to take the original editor maps and convert them to BSP files (Binary space partitioning). Some games just in-game cut the world up there an then, I personally went the preprocess route.

There are a few very tried and tested methods, mostly using tree structures (Binary, Quad and Oct are the most popular), Rastertek has some great tutorials on how to use your your cut up terrain, just search for "quadtree implementation", lots of tutorials on that. Before you go and do this, understand that each has its pros and cons. There are other methods apart from this ,but I will only go on what I have done so far.

There is a wealth of documentation and tutorials out there on how to technically do each of these approaches. So I will go with what I have done in my own game.

For my own implementation, I went with a quad tree, which seems to lend itself well to terrain. Although in 3d, terrain using quad trees seems to work well. In my implementation, I cut the world up into a grid (X/Z plane, Y is height, I did not cut it up vertically). The approach was to firstly to create a bounding box, divide this into 4 equal sized child boxes and bin the geometry based on the median of the triangles into each box they were contained within. I would then regenerate the bounding box for each node, I repeated this until I had an acceptable breakdown of geometry (this is subjective on the type of game you have, my view is a fixed point.).

Finally, I would then in game each frame, traverse the tree, testing the bounding box as each node against the camera Frustum, when eventually a node would be found outside the view I would then mark it as culled, and traverse the rest of the children and mark them as culled.

Of note:

* I selected a Quad tree implementation because of the game view. If had more vertical terrain, I may have leaned towards Oct trees.
* A tree implementation lends itself to assisting with culling of static assets also. I took advantage of the tree structure to add other attributes to the leaves.
* My implementation ignored some of the more advanced concepts, such as cutting geometry up where it crossed over planes.
* Of note, ensure that you aren't putting repeated assets into your mesh like trees or walls. Anything that you put in that occurs multiple times, I suggest you use instancing so that you gain the advantage of drawing these assets quickly. I attached the instancing flags to the leaf nodes, so when I culled the box, I culled all the instances of assets in that part of the scene.
* Finally, plan it. I wish I had done this more, I spent time refactoring my game engine over the past 3 years to add more functionality. No, you don't have to implement everything you desire, but leave it open enough.

Most of this is my experiences. But at the end of the day, yes, you will need to commit time to this pursuit. Good luck.

Note: I will post some screenshots later of the culling in my game to give you an idea of how my efforts panned out.

---
Tags: blender, assimp, 3d-modeling, frustum-culling, model-loader
---


# Question
Title: Are minecraft LANS and servers Filtering Enabled?
Non-filtering enabled means any given client can make changes and the server will replicate them. This is faster but opens doors for hackers and exploiters. Filtering enabled means the client provides user input, and the server decided what to do accordingly. This idea came from Roblox, but I wonder if Minecraft servers are filtering enabled?

In other words: Is Minecraft Filtering Enabled?

# Answer
> 0 votes
# Yes

This isn't even a thing Roblox came up with. It's a thing known in the industry as "the client is a lying, cheating, bastard" (or its technical name, "authoratative server").

Minecraft utilizes it, even in single player (using an integrated server, which runs on a separate thread, see: sides). LAN is just the single player integrated server opened up to additional connections.

It should also be noted that in *creative mode* the client becomes authoratative over several aspects normally controlled by the server, eg. inventory contents, but this is usually regarded as fine because it's creative mode.

---
Tags: minecraft-modding, roblox
---


# Question
Title: Way to Reset Varible After Collision Resolution
I have some code that, if a player is in contact with the wall, prevents the player from moving.

Is there any way with this code to reset the collide variable, and if not, what would be the simplest alternative.I have tried resting it at the start of the step but that did not work.

# Answer
> 0 votes
I would suggest doing a different approach to this question.

Assign a `place_meeting` with some X and Y distance so if your object gets close to the wall, its speeds are reduced to 0, but far from that place, its speed continues to work. Something like:

```
if (place_meeting(x-3,y,obj_wall)) {
   x +=0
}
else {
   speed (variable) = speed
}

```

Another suggestion for you to try like this:

```
if ((keyboard_check(vk_down)) AND
     NOT place_meeting (x,y+4(choose a good distance compared to the sprite), obj_wall))
{
   y +=4
}

```

The meaning: if you press the key and you are not close to the object it will move. It works in all directions.

---
Tags: collision-resolution, game-maker-dnd
---