# Question
Title: How Client send info to Host in Unity Multiplayer
I want to send player name and other details from client to host device. I have setup game for maximum two players connection.

Here is the code that I have tried multiple times with different changes:

```
    void Start ()
{
    spriteRenderer = GetComponent<SpriteRenderer> ();
    circleCollder = GetComponent<CircleCollider2D> ();
    //      StartCoroutine (ColorSwitcher ());
    InitialTasks ();
}

private void InitialTasks ()
{
    isAlive = true;
    GameManager.Instance.IsPlayerWin = false;
    int selectedTheme = Random.Range (0, ballSprites.Length);
    spriteRenderer.sprite = ballSprites [selectedTheme];
    trailRenderer.material = trailMaterials [selectedTheme];
    destroyParticleObj.GetComponent<ParticleSystemRenderer> ().material = trailMaterials [selectedTheme];

    hidePlayerName += OnTouchHidePlayerName;

    if (!isLocalPlayer) {
        // remote player
        gameObject.tag = GameConstants.TAG_REMOTE_PLAYER;
    } else {
        // local player
        Debug.Log ("locally set player name: " + DataCollection.localPlayer.PlayerName);
        playerNameText.text = DataCollection.localPlayer.PlayerName;
//      StartCoroutine (SomeDelayForSendingPlayerDetails ());
    }

//  if (isServer)
//      RpcSetRemotePlayerName (DataCollection.localPlayer.PlayerName);
//  else
//      CmdSetRemotePlayerName (DataCollection.localPlayer.PlayerName);
}

public override void OnStartLocalPlayer ()
{
    base.OnStartLocalPlayer ();
    CmdSetRemotePlayerName (DataCollection.localPlayer.PlayerName);
}

[ClientRpc]
private void RpcSetRemotePlayerName (string remotePlayerName)
{
    playerNameText.text = remotePlayerName;
    Debug.Log ("rpc remote player name: " + remotePlayerName);
}

[Command]
private void CmdSetRemotePlayerName (string remotePlayerName)
{
    RpcSetRemotePlayerName (remotePlayerName);
    Debug.Log ("cmd remote player name: " + remotePlayerName);
}

```

Basically I want to interchange names of both players in 2 players multiplayer game. So please give me some advice into this.

# Answer
> 0 votes
Looks like your setup should work. Make sure you have a network identity and you are a local player.

Add a debug log in InitialTasks and if it does not return the playerNameText properly then make sure that PlayerNameText element is active when you set it.

```
else {
    // local player
       playerNameText.text = DataCollection.localPlayer.PlayerName;
       Debug.Log (playerNameText.text);
     }

```

If the element is inactive you wont set it properly so possibly set it then hide it and see if that works.

Another way to sync up variables is to use a syncvar.

In this example the variable is syncing the name on start as the value changes.

```
[SyncVar(hook = "SyncName")]
public string clientName="";

private void Start()
{   //as I change the name it will sync
    clientName = "Justincredible";
}

void SyncName(string name)
{
    playerNameText.text = name;
}

```

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


# Question
Title: When when pressing on the G key one of parts is scaling slower then the other?
Each Prefab is built with canvas and two panels childs of the canvas. I'm scaling the two panels. The automatic mode part is working fine.

The problem is with the G key. When I press once on G it's scaling both panels up to maxSize then when pressing on G once again it's scaling the panels back down to minSize.

But when I press on G quick in the middle while it's scaling them it should turn the scaling side in the middle. For example if I press G and both panels start scaling to maxSize if in the middle I press on G again it should scale them both to minSize without getting first to the maxSize. But in this case one of panels is keep scaling to maxSize a bit and then move back to minSize.

But they both should turn side in the middle at once. It seems like one of them have a lag he turn sides a bit after the first one.

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

public class Scaling : MonoBehaviour
{
    public GameObject Prefab;
    public int numberOf = 1;
    public float duration = 1f;
    public Vector3 minSize;
    public Vector3 maxSize;
    public bool scaleUp = false;
    public Coroutine scaleCoroutine;
    public bool automatic = false;
    public bool coroutineIsRunning = false;

    private List<GameObject> parts = new List<GameObject>();

    private void Start()
    {
        for (int i = 0; i < numberOf; i++)
        {
            GameObject objecttest = Instantiate(Prefab);
            foreach (Transform child in objecttest.transform)
            {
                parts.Add(child.gameObject);
            }
        }
    }

    private void Update()
    {
        if (automatic)
        {
            if (!coroutineIsRunning)
            {
                Scale();
            }
        }
        else
        {
            if (Input.GetKeyDown(KeyCode.G))
            {
                Scale();
            }
        }
    }

    private void Scale()
    {
        scaleUp = !scaleUp;

        if (scaleCoroutine != null)
            StopCoroutine(scaleCoroutine);

        for (int i = 0; i < parts.Count; i++)
        {
            if (scaleUp)
            {
                scaleCoroutine = StartCoroutine(ScaleOverTime(parts[i], maxSize, duration));
            }
            else
            {
                scaleCoroutine = StartCoroutine(ScaleOverTime(parts[i], minSize, duration));
            }
        }
    }

    private IEnumerator ScaleOverTime(GameObject targetObj, Vector3 toScale, float duration)
    {
        float counter = 0;
        Vector3 startScaleSize = targetObj.transform.localScale;

        coroutineIsRunning = true;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            targetObj.transform.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);

            if (counter > duration)
                coroutineIsRunning = false;

            yield return null;
        }
    }
}

```

# Answer
> 1 votes
In your scale method, you loop through all objects and start a coroutine for each. You save the coroutine object to cancel it later, but you are overwriting the last one started with each iteration through the loop. So when you start the next time, you are only canceling one of the coroutines that you started.

Either keep track of each coroutine separately in an array, or just use `StopAllCoroutines()`.

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


# Question
Title: What is the meaning of component is Dirty?
I was reading a blog from Unity about UI it has a term like **component is dirty**, what does that mean **component is dirty** ?

Unity UI Fundamentals tutorial

# Answer
Sean gave a great answer for general usage of the term. Specifically with regards to Unity UI, a canvas (component) is marked as dirty whenever there is a change to one of its constituent meshes.

Here's the official, more detailed explanation:

> A *Canvas* is a native-code Unity component that is used by Unity’s rendering system to provide layered geometry that will be drawn in, or on top of, a game’s world-space.
>
> Canvases are responsible for combining their constituent geometry into batches, generating the appropriate render commands and sending these to Unity’s Graphics system. All of this is done in native C++ code, and is called a *rebatch* or a *batch build*. When a Canvas has been marked as containing geometry that requires rebatching, the Canvas is considered *dirty*.

Additional details about how this affects the rendering process can be found in the Fundamentals of Unity UI best practices tutorial.
> 8 votes

# Answer
Without context it's hard to say for sure, but "dirty" in programming generally means that an object has been modified, but those changes have not yet been propagated out to related data structures or systems.

This is generally an optimization technique. By using dirty checks, a system can avoid repeatedly processing redundant state changes (e.g., making sure only the most recent change is processed each frame for objects that may be updated many times during the frame). There's some additional performance benefits and pitfalls with dirty flags as well.

For something like a UI component, I would imagine this has to do with UI rendering. The UI renderer may not want to recalculate text width or redraw overlay textures if nothing has changed, so it instead checks to see if any observed UI components are "dirty" before doing its more expensive updates.
> 8 votes

---
Tags: unity, terminology
---


# Question
Title: The cube does not rotate with Vuforia virtual button in Unity3d
I added the cube on the image target of Vuforia. I also added the Vuforia virtual button on the image target. Now I want to rotate the cube by pressing virtual button. For this purpose I implemented the following script.

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

public class rotate : MonoBehaviour, IVirtualButtonEventHandler {

    public GameObject vbtn;
    public GameObject cube;
    public Renderer rend;

    // Use this for initialization
    void Start () {

        vbtn = GameObject.Find ("virtualbtn5");
        vbtn.GetComponent<VirtualButtonBehaviour> ().RegisterEventHandler (this);
        cube = GameObject.Find ("Cube");
        rend = cube.GetComponent<Renderer>();
    }

    public void OnButtonPressed(VirtualButtonBehaviour vb){

        Debug.Log ("Button pressed");
        cube.transform.Rotate (new Vector3(0,Time.deltaTime*1000,0));
        rend.material.color = Color.blue;

    }

    public void OnButtonReleased(VirtualButtonBehaviour vb){

        Debug.Log ("Button released");
        rend.material.color = Color.red;
    }

}

```

The button seems to be working because the `Debug.Log ("Button pressed");` and `rend.material.color = Color.blue;` statements in `onButtonPressed` function are working fine. But `cube.transform.Rotate (new Vector3(0,Time.deltaTime*1000,0));` for rotating cube does not work.

Simple is that the button can change the color of the cube but it does not rotate the cube.

# Answer
> 0 votes
The button is behaving just as a normal button would. It is only clicking once so you probably do have a very small change to the y rotation but it is not continuing to rotate over time.

Two ways you can fix. you can use a bool to trigger the method in a update. Something like bool beginRotate.

```
bool beginRotate = false;

 public void OnButtonPressed(VirtualButtonBehaviour vb){

    Debug.Log ("Button pressed");
    beginRotate = true;
}

void Update(){

if(beginRotate)
cube.transform.Rotate (new Vector3(0,Time.deltaTime*1000,0));

```

}

Or another way would be to call a COroutine on button press.

```
 public void OnButtonPressed(VirtualButtonBehaviour vb){

 Debug.Log ("Button pressed");
 StartCoroutine(RotateCube());
}

IEnumerator RotateCube()
{
    cube.transform.Rotate(new Vector3(0, Time.deltaTime * 1000, 0));
    yield return new WaitForSeconds(0.01f);
}

```

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


# Question
Title: How to get error line when debugging APK from Logcat
I made android game by Unity and built APK. When I got error from this game, I can see the error message:

```
07-06 00:35:38.905: I/Unity(31609): (Filename: ./Runtime/Export/Debug.bindings.h Line: 43)
07-06 00:35:38.906: E/Unity(31609): NullReferenceException: Object reference not set to an instance of an object
07-06 00:35:38.906: E/Unity(31609):   at GameManager.OnRealTimeMessageReceived (Boolean isReliable, System.String senderId, System.Byte[] data) [0x00000] in <filename unknown>:0
07-06 00:35:38.906: E/Unity(31609):   at GooglePlayGames.Native.NativeRealtimeMultiplayerClient+OnGameThreadForwardingListener+<RealTimeMessageReceived>c__AnonStorey4.<>m__0 () [0x00000] in <filename unknown>:0
07-06 00:35:38.906: E/Unity(31609):   at GooglePlayGames.OurUtils.PlayGamesHelperObject.Update () [0x00000] in <filename unknown>:0
07-06 00:35:38.906: E/Unity(31609):
07-06 00:35:38.906: E/Unity(31609): (Filename:  Line: -1)

```

However file name and error line is wrong, so I can't check where exactly error came from.

I checked my logic almost 2 hours also the object references too, but there is no logic to access undefined object code.

It could be, but I can't see where it is. I must run this app because it uses Google Play Games Service, so it requires completed built APK without developlemt option checked.

Using Application.RegisterLogCallback not much help, it has exactly same result.

How do I get exact error line in this case?

# Answer
> 2 votes
It looks like you’re using IL2CPP. If it’s possible, you might want to try targeting Mono instead, at least temporarily, which will do a better job of showing line numbers.

Also, you can still run a build in debug mode and access GPGS if you sign the APK with your release key. If you are using the internal build system, as opposed to Gradle, it should do this automatically. However, if you are using Gradle, you’ll either need to make a modification to the Gradle template, or just re-sign the apk after it’s built, using command line tools.

If all else fails, just add a bunch of `Debug.Log` calls (every other line, if necessary) with simple messages like “a”, “b”, “c”, etc. Look through the logcat to see the last successfully logged message before the error.

---
Tags: unity, android, mobile, debugging, google-play-services
---


title: Develop Isometric Games

text:
# Question
Title: Develop Isometric Games
could someone explain me about isometric games ? i'm unity beginner and want to know about game development.

1. i read that its 2.5 d , that all the objects is actually 2d sprites, is that true ?
2. can we combine it (i use isometric camera, pan only, no rotation) ? ,i mean can we use 2d (for buildings) and 3d (characters) ?
3. i recently play android games (Fun Hospital Tycoon), anyone know the game ? are they using full 2d or combined ?

thank you.

# Answer
> i read that its 2.5 d , that all the objects is actually 2d sprites, is that true ?

You can use 2D spirtes, 3D models, or a combination of boths.

2.5D means different things depending on the context. For example, an otherwise 2D labyrithn with overhead passes or teleportation points is 2.5D. An scenario where the movement only happens on a plane but has 3D graphics is 2.5D. An of course, a fractal whose dimentionality is 2.5, is 2.5D.

Is any of that true for an isometric game? Perhaps. You can make a fully 2D isometric game, you can make it 3D with movement contrained to the horizontal plane and with a particular camara projection to get the isometric look, or you may not constraint the movement to the plane at all... at that point, is is not 3D?

Who cares, don't pay to much attention to "2.5D".

> can we combine it (i use isometric camera, pan only, no rotation) ? ,i mean can we use 2d (for buildings) and 3d (characters) ?

Yes, you can do that. Both your buildings and characters can be either 3D models, or 2D sprites using billboarding planes. Use what you need. If you lock the angle of the camera and use orthogonal projection, it can work.

Using 3D would allow better effects, for instance, it can give you more realistic light effects. However, being the game isometric, you are already taking your artistic license on the presentation.

> i recently play android games (Fun Hospital Tycoon), anyone know the game ? are they using full 2d or combined ?

How you can do the same effect? I would suggest to use full pixel art. Looking at screen shots of the game, I have no reason to believe that they need 3D models in runtime. In fact, doing it all 3D would probably have a performance hit on the average android device.
> 2 votes

---
Tags: isometric
---


title: Camera rotate at target?

text:
# Question
Title: Camera rotate at target?
I have free camera that move and rotate around the level. In this script if tb = true, I want my camera to rotate at target. Camera will show my character not rotate at character direction. image

```
public Transform avatar1; // character
public Camera cam;
public bool tb;

void Start()
{
    tb = false;
}

void Update()
{

    if (tb == true)
    {
        StartCoroutine(bu1());
    }

}

IEnumerator bu1()
{
    cam.transform.position = Vector3.Lerp(cam.transform.position, new Vector3(avatar1.transform.position.x + 6, 10, avatar1.transform.position.z + 7), 0.1f);
    cam.transform.rotation = Quaternion.Lerp(cam.transform.rotation, avatar1.transform.rotation, 0.4f); // here is my problem
    yield return new WaitForSeconds(2);
    tb = false;

}

```

# Answer
> 1 votes
You are lerping the camera's rotation to the target's rotation, you want the camera to rotate towards the player, you need a direction vector that points towards that target, to do that:

> **direction = target - observer** (all are vectors)

After getting the direction, you need to convert that vector to a quaternion, since that is how rotation works, for that, there is already a function that makes that conversion (Quaternion.Euler).

Example:

```
public Transform avatar1; // character
public Camera cam;
public bool tb;
public float duration = 2f; /// Lerping duration.

void Start()
{
    tb = false;
}

void Update()
{

    if (tb == true)
    {
        StartCoroutine(bu1());
    }

}

IEnumerator bu1()
{
    float n = 0.0f; /// Normalized time reference.
    Vector3 direction = avatar1.position - cam.transform.position;
    Quaternion originalRotation = cam.transform.rotation;
    Quaternion newRotation = Quaternion.Euler(direction);

    cam.transform.position = Vector3.Lerp(cam.transform.position, new Vector3(avatar1.position.x + 6, 10, avatar1.position.z + 7), 0.1f);

    while(n < 1.0f)
    {
         cam.transform.rotation = Quaternion.Lerp(cam.transform.rotation, newRotation, n);
         n += (Time.deltaTime / duration);
         yield return null;
    }

    tb = false;
}

/// You can also use Quaternion.LookRotation(newRotation);

```

As a side note, your avatar is already a Transform, so it is not necessary to call "avatar1.transform.position", instead you can just call "avatar1.position".

Hope it helps.

# Answer
> 0 votes
Here is the solution part.

```
IEnumerator bu1()
{

    cam.transform.position = Vector3.Lerp(cam.transform.position, new Vector3(avatar1.transform.position.x + 6, 10, avatar1.transform.position.z + 7), 0.1f);
   var CamRot = Quaternion.LookRotation(avatar1.transform.position - cam.transform.position);
    cam.transform.rotation = Quaternion.Slerp(cam.transform.rotation , CamRot, 4 * Time.deltaTime);
    yield return new WaitForSeconds(2);
    tb = false;

}

```

---
Tags: unity
---


# Question
Title: Should players be required to find story clues to advance in the current playthrough (if they have already played the game)?
I am making a fairly simple game. I would like to know if players should be required to find story clues to advance in the current playthrough (if they have already played the game).

For example, let's say someone needs to find a password late in the game to unlock a door that has been visible since the beginning of the game, allowing them entry into one of the final areas of the game. If someone has already played the game and already knows the password, should they be able to skip the majority of the game by quickly entering the password in the beginning, or should they be required to work their way through the game and find the password before the door can be accessed?

For major games, which approach is more common?

Also, I would like this game to be able to be speedrun-able. Would a speedrun be boring if the fame used the first approach of being able to skip most of it by using the password?

# Answer
> 2 votes
I’ve seen games do it both ways, but only in the context of gaining access to small areas with loot or what have you. I am sure there are games that do include intentional large game skips that I don’t know about, but the best implementation I’ve seen is one where the password/code/answer changes each play through. This has the benefits of giving an actual reason to find the answer, rather than just making it an unnecessary fetch quest, and making walkthroughs not be able to just give away all the answers.

# Answer
> 1 votes
Talking strictly about speed-running, I'd say your example wouldn't matter that much, as the time optimization techniques generally involve clever playing/exploitation of the game. However, if such a door would lead to almost finishing the game with little room for any time optimization, then it really doesn't sound so interesting.

Leaving speed-running aside, in Chrono Trigger's new game+ you had the option of skipping the whole game basically and straight up face the final boss in the very beginning of the game. You'd get one of the many endings, and I particularly found that quite fun to do. I still played the game again (many many times) to explore other things.

I believe if you cleverly use any of the two approaches, it can lead to very satisfying playing experiences.

---
Tags: game-design
---


title: Speed limit for Newtonian spaceships?

text:
# Question
Title: Speed limit for Newtonian spaceships?
I am working on a game based around Newtonian physics. Therefore there is no drag and therefore a ship will keep accelerating indefinitely if there is no counter-force acting on it. This is being built within Unreal Engine and it is entirely based on physics thrusters (i.e. *"Add Force at Location"*).

For gameplay purposes I'd like to implement a "speed limit". Consider a simple *seek* steering behaviour. `Ship A` is pursuing `Ship B`. `Ship A` reaches the "speed limit" at time `t0`. `Ship B` changes direction at time `t1`.

If I calculate the new direction at `t1`, and then "cap" the speed at time `t1 + 1 frame`, `Ship A` will continue on its original direction, because accelerating towards another direction would make its total linear velocity greater than the speed limit.

If instead of calculating the "global" instantaneous velocity I only calculate the projection of the velocity vector along its forward axis, then it works.

However, there are some fringe cases. For example if the new direction is almost orthogonal to the velocity vector, then that means that its projection on the forward axis will be very small in magnitude. The ship will thus reach speeds well above the limit, only to have a "hard brake" when the velocity projection reaches the limit on its forward axis.

Which other methods could I use to limit speed? I thought about removing a software-based limit altogether and just make sure that the ship is braking whenever it is close to the limit. While more realistic, I'm afraid it might look less interesting.

# Answer
Myself, I like to use an AccelerateTowards method that takes a target velocity and a maximum acceleration (though the same thing can be done with forces by incorporating mass):

```
targetVelocity = inputVector * maxSpeed

// If inputVector has length <= 1
// then this obeys our speed limit by construction.

// Compute the change needed to reach the target.
deltaV = targetVelocity - currentVelocity
accel = deltaV/dT

// Clamp to what our engines can do.
// maxAcceleration = maxForce / mass
if (accel.length > maxAcceleration)
    accel = Normalize(accel) * maxAcceleration

force = accel * mass
ApplyForce(force)

```

This will let you put your full allowed force into changing direction even if you're already travelling at the speed limit, and will enforce the speed limit throughout the turn (so you don't travel faster diagonally in-between)
> 1 votes

# Answer
Depending on how 'arcady' your game should be, this might be difficult.

In real life, if you have high velocities, the energy needed to accelerate further is increasing by the square. So doubling your velocity would mean quadruple the energy needed. A realistic approach to that problem could be, that your engines cant provide enough thrust to accelerate much further. So your acceleration flattens out, while you still get faster and faster, as your acceleration never reaches zero.

Now you could 'science-babble' your way out of it:

* Your engines need a certain acceleration, cause of plasma fields, so limiting speed to a certain point where acceleration would still be enough.
* Stuctural integrity: as a safety measure your speed is capped. If you would accelerate further, every slight deviation from your flight vector would damage and/or destroy your ship/engine/pilot. (And a perfect linear acceleration vector is impossible)
* Galactic Rulings: Flying with higher speeds may disrupt the subspace the engines are using to accelerate (power them or as something to push from).

The second point would in my oppinion fit best with your orthogonal example. If a pilot tries something like accelerating orthogonal to its original vector, damage the ship SLIGHTLY. A player could use it as a risk/reward mechanic, doing sick maneuvers at cost of health or hull.

If you want to make it feel more arcady, just cap it and say thats the limit because reasons. Noone will ask for a reasons and it will fit right in. Just always reduce the maximal velocity to the cap while keeping the new vectors direction
> 0 votes

---
Tags: physics, unreal-4
---


title: c++ text rpg loading rooms/mobs

text:
# Question
Title: c++ text rpg loading rooms/mobs
So for practice and as a learning exercise i foolishly decided to make a text based rpg on my phone using the c4droid ide. ive done well and have learned a lot.

So far you can create a new character or load the previous one. and you can walk around in the rooms ive made. currently the rooms load from a file when you enter it, and then it loads again every time you do anything except leave,which loads the next room instead. ill be tweaking my gameloop so it doesnt reload the room everytime soon.

My next step is the addition of mobs. and here ive run into a problem i cant find the answer to with google. My plan was/is to make a class for mobs and instantiate it when there was a mob present and load data from a file. But then i was trying to figure out how to code which room to load them in. First answer was to have the room file dictate which mobs, if any to load. great. except that i want the mobs to stay dead, not reapawn everytime the room reloads. so now im wondering if i should be loading the rooms from file all at the same time before the game loop. Potentially too memory intensive down the line when the game has more rooms and mobs? and what to load them to? i havent used arrays in c++ yet, though i have used map which seems similar. Im not even sure what a vector is. i expect ill be needing to read up on those very soon.

so the basic question is this: leave loading the rooms the eay it is, load them all at the beginning of the game, or something else?

all help is appreciated

# Answer
> 1 votes
To add to other answers, we don't really know how many rooms you have (or plan to), so loading every room in the beginning might work, but not in all cases.

As a text-based game however, you can still keep track of all spawned enemies, something like this:

* Move to a new room, load it
* Enemy is in the room (based on the room file), check if that enemy has already spawned (exists) in the "enemy array"
* if not, spawn a new enemy, and add its instance to the enemy array.
* if yes, do not load that enemy again, as its most likely wondering around the map.

Now every time you visit a new room, keep in memory the previous room (that the enemy is in) so that it can navigate through the room to find you. If you move too many rooms away, maybe you can despawn the enemy (unload and remove from enemy array) or you can keep all previous rooms in memory, until the enemy navigates past them. It all depends on how you want enemies to behave.

Since you are using C++, the best choice is a `std::vector`, as mentioned in the comments as well.

The details really are up to you to decide, as its implementation will slightly change the enemy's behaviour (if you want it to respawn, or chase you indefinitely etc etc). Also, I'm not sure what's the size of the "map" that contains all the rooms, but if you have divined your game in stages, or something that can make you "progress" to another set of rooms (like ascending, descending floor), you can load all rooms of that stage in the memory, and spawn all enemies the moment you appear there. Assuming that your gave mimics the appearance of rogue-like games, it shouldn't be intensive at all memory-wise.

# Answer
> 0 votes
You didn't post any numbers regarding the RAM usage of your game, but reading between the lines I get the impression that your game is still far too simple to require so much memory that you can't load all the rooms at game startup and then keep their state in memory while the game is running.

But if you want to keep your architecture where you load every room from the filesystem when you enter it and unload it when you leave it, then you could add a second "change file" for each room. This file represents the state of any changing properties of the room (like the status of any mobs in it). After you loaded the room file, check if there is a change file for that room and when you have one, load it and apply the changes to the room data you just loaded. When these properties change, write a change file for that room with those changes.

And by the way, you now have a working savegame system.

I'm looking forward to playing your game.

---
Tags: c++, rpg, text
---


# Question
Title: Should tiles be referenced statically when making a map or some other way?
I'm trying to think of a way to manage tiles in my game, so far I have a `Tile` class that has characteristics about the tile in question, a `TileDictionary` class to keep a list of tiles to use, and the map is simply just a `Tile[,]` array.

```
class Tile
{
    public Texture2D graphic;
    string name;
    bool walkable;

    public Tile()
    {
        name = "Dirt";
        graphic = null;
        walkable = true;
    }

    public Tile(string _name, Texture2D _graphic, Boolean _walkable)
    {
        name = _name;
        graphic = _graphic;
        walkable = _walkable;
    }

static class TileDictionary
{
    public static Tile DIRT_TILE = new Tile("Dirt",null,true);
    public static Tile STONE_TILE = new Tile("Stone", null, true);
    public static Tile CLAY_TILE = new Tile("Clay", null, true);

    public static void LoadTileGraphics(ContentManager content)
    {
        DIRT_TILE.setGraphic(content.Load<Texture2D>("tiles/dirt"));
        STONE_TILE.setGraphic(content.Load<Texture2D>("tiles/stone"));
        CLAY_TILE.setGraphic(content.Load<Texture2D>("tiles/clay"));
    }

```

Is this a good method? I see games like Minecraft using static `Block` instances to reference their blocks, but knowing that it was previously all magic numbers, I feel like this system was just a band-aid over the old system. Obviously all tiles would be loaded via the `TileDictionary`, but I am confused on how using this method would handle implementing and using more complex blocks that have functions tied to them or anything.

# Answer
As long as your tiles have no actual state or unique information, this is going to work just fine.

When you do add *a little* state, like a door which can be open or closed, you can implement this with two different tile types (`TileDictionary.DOOR_OPEN_TILE` and `TileDictionary.DOOR_CLOSED_TILE`).

But when it gets more complex, like if you have destructible tiles with individual hitpoint cost or signs with unique texts the player-character can read, then this won't be sufficient anymore.

You could then still use your architecture by putting some objects into your `Tile[,]` array which are not actually static members of `TileDictionary` but ad-hoc instantiated objects form classes which extend your `Tile` class.

However, this means that you might have to add some methods to `Tile` which are implemented as a no-op in `Tile` and only serve to be overridden by the more complex `Tile` subclasses. This might turn out to be a minor performance hook, because it means that this methods will now be called for every tile, even if it doesn't actually do anything most of the time.

It might be better to implement such objects not as tiles but as mobile game objects, just like the enemies and the player.

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

# Answer
I believe the Flyweight pattern is what you need.

> Flyweight, like its name implies, comes into play when you have objects that need to be more lightweight, generally because you have too many of them.

A simple implementation is listed at the page.
> 0 votes

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


# Question
Title: How to test for BoxCollider2D intersection in Unity?
I have a Player object with a `BoxCollider2D` component and a Ladder object also with a `BoxCollider2D` component. Each object has a script, and in each script, I set up references to the box colliders in the normal way.

```
public BoxCollider2D box_collider;

void Start ()
{
    box_collider = GetComponent<BoxCollider2D>();
}

```

My player script is called "PlayerController", so that's the class defined in the script.

In my Ladder's script I have the following:

```
void Update ()
{
    GameObject player = GameObject.Find("Player");
    PlayerController player_controller = player.GetComponent<PlayerController>();
    if (player_controller.box_collider.bounds.Intersects (box_collider.bounds))
        Debug.Log ("collision");
    else
        Debug.Log ("no collision");

}

```

This script invariably returns "no collision" and I'm not sure why.

**Any ideas?**

# Answer
> 2 votes
I believe what you want to achieve is to set a ladder to be a trigger on the box collider and set up a method on the ladder `OnTriggerEnter2D`. When player will collide/trigger entering into ladder, the ladder will be informed about that.

> https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html

```
void OnTriggerEnter2D(Collider2D col)
{
     // check tag of col and process
}

```

Of course you can also check collison of objects, there are few other methods that might help (remmember to turn of isTrigger on collider in this case):

> OnCollisionEnter2D - Sent when an incoming collider makes contact with this object's collider (2D physics only).

# Answer
> 1 votes
Another way, aside from using Ontrigger or OnCollision to find a intersection like ground, water, enemies ect.. Is to use layers and cast a check to see if you contacted one.

`Physics2D.OverlapCircle(playerPosition, collisionRadius, ladderLayer)`

here is a example of a bool returning true if I am touching the layer

```
[SerializeField]
private LayerMask groundLayer;
private float collisionRadius = .23f;
Transform playerFeet
public bool grounded = false;

```

groundLayer

```
 public bool GroundCheck()
{
    return grounded = Physics2D.OverlapCircle(playerFeet.position, collisionRadius, groundLayer);
}

```

---
Tags: unity, c#, 2d, bounding-boxes
---


# Question
Title: Client should send one big packet or multiple smaller ones per frame?
The client can do several actions per frame, for instance, requesting a movement, shooting etc. Should i send a packet to the server for each action the client performed during the frame, or should i stack them in an unique packet and send it at the end of the frame?

EDIT: i'm using *Jmonkeyengine* and the provided network API *SpiderMonkey*.

# Answer
> 5 votes
It shouldn't be a problem to send many packets in one frame. Every packet has some overhead, but you won't feel the difference.

However, if you decide to send a packet every frame, even if there was no user action (or the action is holding a key), while your client will work just fine, and your local testing server will do the job as well, real server will be easily flooded if multiply clients send multiply packets, multiply times (30, 60 or even more) a second. This is same if you want to update mouse cursor position on server every time a user moves the mouse.

# Answer
> 1 votes
Well,

(if I refer to data as ,,packet", I mean a group of data you want to send. Not a packet in ISO OSI)

let's consider players, bullets and zombies. Sending one big data packet is possible, but not good, because as game gets bigger, you will send more and more data. You will also discover that sometimes, you send position data but not weapon data (because weapon did not change, so why...) and etc. Therefore that will result in checking: Is the data packet containing this? and this?

That is feasible for small projects, but not for a perspective game. Considering that you send one big data packet, sockets divide it anyway to small frames / iso osi packets (depends on iso osi layer you consider).

**Sending small chunks**

Lets say, that you send one small chunk C1. But it is too small, that socket will not send it. Instead, it waits for more data. That is possible, but depends on technology you use, and how the networking is implemented there. Definitelly I can imagine, that the system might wait a bit to see if more chuks are about to be send, that then sends it all together.

So when you send one big data chunk

1. You will in fact be sending small chunks over network anyway
2. Code will be big and difficult to read, having huge packet class
3. You will have to check on client side: Is there weapon data? If so, call this function to draw that...is there zombie animation state...? etc.

Therefore, I vote for individual packets, consider zombie game as example

* send packet for weapon - sent to individual players
* packet containing user, zombie, bullet positions - sent to all players
* packet containing user information - health

Lastly, I will add here something I have learned...

**Never care about performance in first place**

Now alot of people will say: well that is bad attitude. But, if you write a game, which is very difficult task, and it will ALWAYS be complex, get the code done. No matter how memory or gpu is wasted. You can optimize when the code is done. (I am talking about code chunks, developing iterations, like every week try to optimize something....not all at the very end)

Why? It happened to me many times. I overthink: Well, how this can be efficient? Do this and this, and it results in such a complex task that you will not make it work.

Therefore: write simple code towards functionality, but keep some space for futurer optimalizations

example: Develop a game, where you send position every frame to all. Then, modify it to send position to all only when it changes. Then, modify it to send position to selective players, if needed. Then, you can compress the sent data...etc.

---
Tags: networking
---


# Question
Title: Programmatically created instance does not execute any code
I've created a new instance, positioned it, and added it to the scene like this:

```
const Player = preload("res://player.tscn")

func _physics_process(delta):
    if <outside display>:
        var newplayer = Player.instance()
        newplayer.position.x = 200
        get_tree().get_root().add_child(newplayer)
        queue_free()

```

This works to the extent that the player is created in the right position and starts falling down with gravity. But the new player does not respond to any input, nor does it do anything if I `print` things in the `_ready` function or the `_physics_process` function. It seems its script is just never executed at all.

I've tried not `queue_free()`'ing the old one, in case removing it is like removing its parent, but that doesn't help.

I've tried calling the `._ready()` function on it manually, but that doesn't work either.

I've tried calling `request_ready()` on the new player, but that doesn't run the `_ready()` function either.

In tutorials, this is usually all they do to get a new instance into the world, so I'm not sure what I'm missing here.

# Answer
After browsing the autocomplete options some more, I found `set_script()`. It is apparently to be used like this:

```
newplayer.set_script(script_object)

```

I'm not sure how to find an arbitrary script object, but in case you want to attach the same script as is currently running, you can do this:

```
newplayer.set_script(get_script())

```

This needs to be done *before* adding it to the scene.

The full code is:

```
const Player = preload("res://player.tscn")

func _physics_process(delta):
    if <outside display>:
        var newplayer = Player.instance()
        newplayer.position.x = 200
        newplayer.set_script(get_script())
        get_tree().get_root().add_child(newplayer)
        queue_free()

```
> 1 votes

---
Tags: instancing, godot
---


# Question
Title: Why does my Window take a few clicks to actually close even though the event fires?
I am pretty new to game dev (and libgdx + scene2d specifically), I am creating a dialog system for an rpg game and obviously a dialog window has a close button to close a dialog but for some reason it takes few clicks to close it (see video).

I have added `System.out.println(Actor.class)` to where the listener executes:

As you can see the events fired as planned!

Here is my listener code:

```
closeButton.addListener(new ChangeListener() {

  @Override
  public void changed(ChangeEvent event, Actor actor) {
    System.out.println(Actor.class);
    event.getListenerActor().getParent().addAction(Actions.hide());
  }
});

```

Please send help, thank you

# Answer
Guys who recommended checking whether stage.act() is firing properly were correct!

This is my original code in Hud.java(the class that renders the hud layer where I try to display dialogs):

```
  public void render(float delta) {
        stage.act(delta);
        stage.draw();
    }

```

And this is the code that fixed it:

```
public void render(float delta) {
    stage.draw();
    stage.act(delta);
}

```

It was a simple mistake, my bad, it is only logical to draw your things and then update them.

Thanks everyone for the imput
> 1 votes

# Answer
I think you should use ClickListener:

```
    closeButton.addListener(new ClickListener() {

    @Override
    public void clicked(InputEvent event, float x, float y) {
        System.out.println(Actor.class);
        event.getListenerActor().getParent().addAction(Actions.hide());
    }

});

```

Also, check if you call method stage.act() in render. Without that action will not work. Eventually you can use setVisible(false) on actor.
> 0 votes

---
Tags: java, libgdx, events
---


# Question
Title: SDL2 reporting 24-bit pixel format on a 32-bit desktop setup
I'm trying to figure out why calling SDL\_GetWindowPixelFormat is returning SDL\_PIXELFORMAT\_RGB888, even though I'm creating the window with the flag "SDL\_WINDOW\_FULLSCREEN\_DESKTOP", and my desktop uses 32-bit color.

Perhaps I'm misunderstanding what this flag means. I'm running my program on a Windows 7 machine, and I checked the display color-depth using Control Panel -\> Display -\> Adjust Resolution -\> Advanced Settings -\> Monitor (which displays "50 Hz, True Color 32-bit".)

I'm coding using SDL2 (version 2.0.6). I was expecting this call to return SDL\_PIXELFORMAT\_RGB8888 or some other 32-bit format. Any help appreciated on clarifying this. My code is below.

```
#include "SDL2/SDL.h"
#include <stdio.h>

SDL_Window* window;

int main(int argc, char* args[]) {

    SDL_Init(SDL_INIT_VIDEO);

    window = SDL_CreateWindow("TUTOR",
            SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
            0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);

    Uint32 global_pixel_format = SDL_GetWindowPixelFormat(window);
    const char* temp = SDL_GetPixelFormatName(global_pixel_format);
    printf(" SDL_Window created with pixel format %s\n", temp);

    SDL_Quit();

    return 0;
}

```

# Answer
Pixel format isn't specified by your desktop, it's just the format that SDL2 uses for pixels.

As @Maximus Minimus said, the 8 bits are unused, with 24 bits being 8 red, 8 green, 8 blue. This is 32 bits in total.

Look at: https://wiki.libsdl.org/SDL\_PixelFormat and https://wiki.libsdl.org/SDL\_PixelFormatEnum for more information.

Hope this helps.
> 1 votes

---
Tags: sdl2
---


# Question
Title: How to create button prompts for interactable objects in Unity?
I have a class of objects tagged as `interactables` that my player can interact with when within range.

When my player is near them, I want to display a button prompt at the bottom of the screen, along with a description of the type of interaction possible (for example, "inspect", "use", etc.).

I want to account for the possibility that the player might be within range of two or more of them at once, and thus allow him to toggle through them, displaying their button prompts in turn.

If my player interacts with something which generates a text box or other modal, I want the button prompt to disappear, but to return when the text box or modal is closed.

**Any advice on how to go about achieving this?**

I've done it in the past in different engines, but I have always been unhappy with how convoluted my method was. I'd like to hear how others might tackle this. Given how common this kind of thing is in games, I'm surprised I haven't found a good tutorial on it yet.

You can be as general or as specific as you'd like in your answer.

# Answer
> 2 votes
I'd divide this problem into three parts: the Interactable, the Interactor, and your InteractionUI.

Your Interactable objects all have:

* A script that exposes public methods to get the interactable state (eg. enabled/disabled), appropriate interaction prompt description(s), and to trigger the action of the object.

This could all be one shared script (exposing an OnInteract Unity event you can wire up in the inspector), subtypes of a common base Interactive, or unrelated components implementing an IInteractive interface if you need very divergent behaviours
* A trigger collider marking the interaction range (so it can be differently sized/shaped/positioned for each interaction, as appropriate).

Put this collider in an Interactables physics layer so it's easy to filter to where you need it.

Your Interactor script within your player character object maintains a list of Interactables in range, and an index or reference to the one currently selected/prioritized.

* Inside OnTriggerEnter/Exit2D methods, it adds and removes interactables to maintain this list. If the list goes from empty to non-empty, it can fire an InteractionAvailable event.

If the selected interaction goes out of range, it can fire an InteractionUnavailable event, or cycle to the next Interactable and send an InteractionChanged event.
* Each frame, you can check that the selected Interactable is still in a usable state, and optionally rank its range/priority/centeredness in view against the others in the list to decide whether to swap which interaction is presented, firing InteractionChanged events as needed.

If auto-selecting between interactables, ensure you give a bias toward the currently selected one — this adds some hysteresis so that your selection doesn't flicker unpredictably.

Lastly, your InteractionUI subscribes to events from the Interactor, and uses that information to show, update, or hide the interaction prompt. It can also communicate with your other UI to hide the prompt when appropriate.

* When you're in a UI state that allows interacting with the prompt, the InteractionUI can forward the interaction button input to the Interactor's currently selected Interactable.

You can cache the previous selection on InteractionChanged to make it available a fraction of a second longer while the visible UI prompt transitions, if you find it's too easy to accidentally trigger the wrong one during a swap.
* When more than one interaction is available, the UI can display prompts and forward inputs to the Interactor to cycle between them.

Above I haven't strictly separated the view & controller roles of the UI layer, but you can if it suits your approach to UI and input. The main point is separating out the model role into the Interactor component, which helps keep your interaction management logic from getting too entangled with UI presentation or input control state, and makes it easier if you ever want to introduce multiplayer or switching between multiple characters.

So, summarizing:

* you have an object that knows how it wants to be interacted with
* you have an Interactor that manages the set of interactions currently available to a given actor in the scene
* you have a UI controller that handles navigating and acting on the available interactions for the player's (current) actor

---
Tags: unity, 2d, gui
---


title: Unity Gameobject turned grayed

text:
# Question
Title: Unity Gameobject turned grayed
I accidently pressed some key combination which turned all the gameobjects in Unity engine gray and now I cannot restore them to the original form. Any suggestions? Below is the link of what I am talking about: https://ibb.co/izAVRo

# Answer
> 1 votes
Remove that `f` from the search bar.

It's trying to find gameobjects containing `f` letter, but none of them contains f in their name so all of them became gray.

---
Tags: unity
---


title: Camera Pitch, Yaw from View Matrix

text:
# Question
Title: Camera Pitch, Yaw from View Matrix
I have a camera that works with Pitch and Yaw (no roll) and compute the look at matrix as following :

```
glm::vec3 direction;
direction.x = cos(glm::radians(pitch)) * cos(glm::radians(yaw));
direction.y = sin(glm::radians(pitch));
direction.z = cos(glm::radians(pitch)) * sin(glm::radians(yaw));
direction   = glm::normalize(direction);
this->view =
  glm::lookAt(position, position + direction, glm::vec3(0, 1, 0));

```

Now I want to initialize these Pitch and Yaw from another View Matrix and used this method but without success:

```
  /* previousCamera->view as a glm::mat4 */
  position = glm::vec3(previousCamera->view[3]);
  const glm::vec3 direction = glm::vec3(previousCamera->view[2]);
  yaw   = glm::degrees(glm::atan(direction.x, direction.z));
  pitch = glm::degrees(glm::asin(direction.y));

```

Do you spot any mistake in my code?

---

Edit:

In addition to the answer from @DMGregory, my position and direction were not correctly extracted from the ViewMatrix:

```
  const glm::mat4 inverted = glm::inverse(previousCamera->view);
  position = glm::vec3(inverted[3]);
  const glm::vec3 direction = - glm::vec3(inverted[2]);
  yaw   = glm::degrees(glm::atan(direction.z, direction.x));
  pitch = glm::degrees(glm::asin(direction.y));

```

# Answer
> 2 votes
First, let's look at `y` because it's simplest.

* to encode pitch into your direction vector's y, you convert the pitch value to radians, then take its sine.
* to decode pitch from your direction vector's y, you take its arcsine and then convert it to degrees.

So you're correctly reversing each operation, and the value should round-trip correctly up to floating point accuracy.

yaw / x and z get a bit more complicated, so let's try running a few sample values through (with zero pitch, for simplicity):

* at yaw = 0, x = cos(0) = 1 and z = sin(0) = 0

+ at (x, z) = (1, 0), yaw = degrees(atan(1, 0)) = 90 degrees
* at yaw = 90 degrees, x = cos(radians(90)) = 0 and z = sin(radians(90)) = 1

+ at (x, z) = (0, 1), yaw = degrees(atan(0, 1)) = 0 degrees

So it looks like you've simply flipped your x and z arguments to atan.

If you think of the two-argument arctangent as finding an angle from positive x-axis on the unit circle in the xy plane, the arguments go in the order (y, x) rather than (x, y)

---
Tags: opengl, glm
---


# Question
Title: Subtracting magnitude from 2D circle contact
I'm trying to create an agar.io clone. In agar.io, each player can have multiple cells that "chase" the mouse pointer. The cells can also have multiple masses and the velocity is tied to the mass. The bigger the cell, the slower it moves. The first picture in this question is a good representation of how this plays out

The cells can't overlap (mostly), so I've already implemented

1. check to see if they are touching
2. calculate how much they overlap -\> distance between circle centers, minus both circle's radius
3. calculate a push vector -\> subtract the two centers, normalize the resulting vector, and multiply by overlap value

The above code mostly works, but in the regular game if you have a smaller/faster blob moving behind a larger/slower blob, the faster blob will start to slide around the larger blob. I'm not sure how to implement that.

I think you should be able to calculate the normal to the point where the circles touch, and remove the magnitude of the "chase the mouse" velocity in the direction of the normal? I'm not sure how to do that. Math is not my strong suit.

I took the idea for the circle collision from this link and I think my question of how to remove the velocity from the circle normal is in this link which talks about how to calculate the reflection off of a circle, but I haven't been able to translate that to code.

I'm using C++, not that that matters.

There's also the open source agar.io clones, Ogar and Agar.io-clone, but I haven't found much digging through the code with how they handle that.

# Answer
If both circles are headed to the same destination, but not in exactly the same line, then your logic for pushing them apart will actually already route the smaller circle around the larger one, slowly.

Here you can see three iterations of advancing the circles along their velocities, computing penetrations, and adding separating offsets. In the process, the smaller circle climbs from about the 10:00 position on the larger circle's clock face up toward the 12:00 position, even though we never "told" it to.

So, that might be why you're having trouble finding code in Ogar or Agar.io-clone that handles this routing-around behaviour: they might not code that behaviour explicitly. It can arise as an emergent result of applying offsets along the line separating the circles.

That said, you might find this effect is a bit too gradual on its own - especially when the circles are travelling directly in line with one another. There, pushing the small circle back along the line between the circles just reduces its net velocity along the same line, rather than displacing it above or below the obstacle. (You can think of it like all the little one's effort is going into pushing against the big circle, with no component sliding along the surface)

So we can give the small circle a little extra nudge to help it in these situations. I do something similar in this answer, though there the obstacles are stationary so we can plan the movement of the ball around them without order-of-update considerations. For many co-navigating balls, we'll want some type of iterative solution instead.

I don't know exactly what you have in mind with the proposal to 'remove the magnitude of the "chase the mouse" velocity in the direction of the normal', but here's how you can do that after you've resolved the collision between two circles:

```
toTarget = targetPosition - centerPosition

collisionNormal = normalize(centerPosition - obstacle.centerPosition)

// This is the component of the toTarget vector pointing into the obstacle.
// The min(, 0) discards cases where our toTarget actually points out of the collision.
intoCollision = min(dot(toTarget, normal), 0)

toTargetNonColliding = toTarget - normal * intoCollision

```

A few cautionary notes about doing this type of adjustment:

* This subtraction can produce a zero vector when the collision normal is pointing exactly opposite the direction we want to go. In such a situation, you can fall back on a perpendicular to the collision normal `(-normal.y, normal.x)` to avoid a deadlock.
* A circle might find itself wedged between two or more obstacles, in which case considering only one normal might not tell you enough about the nearby constraints, and considering all normals might leave you with nowhere to move at all. You'll need to decide what kind of behaviour you want in that scenario.
* You may want to apply this type of adjustment a little at a time, as a nudge or persistent spring force over a range of nearby distances, rather than an all-or-nothing instantaneous velocity change.

If you completely eliminate movement into collision on frames with collision, you'll tend to not encounter a collision in the next frame (if you're dealing with just the one obstacle), falling back on your default behaviour, which sends the velocity back into a colliding direction. This can make your following object appear to stutter or zig-zag on alternating frames as it switches between collision-avoiding and normal velocity calculations.
> 1 votes

---
Tags: 2d, collision-resolution
---


title: UE4 opens C++ project the second time

text:
# Question
Title: UE4 opens C++ project the second time
When I create new C++ Project (Base Code), UE4 opens only code editor (MS VSCode). Then when I close code editor and I open this project, UE4 opens its editor. Why?

# Answer
> 1 votes
When set as a C++ project UE is set to assume you want to code. So it opens visual studio. Seems reasonable.

See this : https://answers.unrealengine.com/questions/319140/how-to-deactivate-visual-studio-launching-3.html

You can disable it by setting it in the ini file:

`[/Script/SourceCodeAccess.SourceCodeAccessSettings]
 PreferredAccessor=NullSourceCodeAccessor`

---
Tags: unreal-4, unreal
---


# Question
Title: How do I scale room transition surfaces to fit mobile display?
I followed a tutorial on how to add a left swipe room transition, which works very well. My problem is that it won't scale to my Android display. I know that it's being drawn to the GUI layer and I've tried resizing the GUI to the display width and height but I didn't see any changes. It's a really nice effect that I want to get working for my game.

Create Event:

```
currentframe = 0
maxframes = 45

persistent = true; // when changing room keep this object alive

// copy the old room so we can display it on the second room
sur_oldroom = surface_create(room_width,room_height);
surface_copy(sur_oldroom,0,0,application_surface);

// We have recorded what the old room looks like so we can instantly go to the next room.
room_goto(rm_game);

```

Destroy Event:

```
surface_free(sur_newroom)
surface_free(sur_oldroom)

```

Step Event:

```
currentframe++

if (currentframe > maxframes) {
    instance_destroy() // The transition has finished so destroy it
}

// We are now on the second room so record that room.
if (currentframe == 2) {
    sur_newroom = surface_create(room_width,room_height);
    surface_copy(sur_newroom,0,0,application_surface);
}

```

Draw GUI Event:

```
if (currentframe > 1) {

    // convert the number of frames that have passed into a number between 0 and the room width
    var slideamount = EaseOutQuad(currentframe,0,room_width,maxframes)

    if (surface_exists(sur_oldroom)) {
        draw_surface(sur_oldroom,-slideamount,0)
    }

    if (surface_exists(sur_newroom)) {
        draw_surface(sur_newroom,room_width-slideamount,0)
    }
}

/// I do this to hide the flicker where the next room pops up for 1 frame
if (currentframe == 1) {
    if (surface_exists(sur_oldroom)) {
        draw_surface(sur_oldroom,0,0)
    }
}

```

I'm using Game Maker Studio 1.4.

# Answer
> 0 votes
I feel like the boy crying wolf, so sorry for that. Next time I encounter a problem, I'll just post it as how to fix that problem. Anyways in my screen manager object related to this post here: Can't scale properly to android device in Game Maker Studio 1.4, My solution was `display_set_gui_size(ideal_width,ideal_height);` after the line `surface_resize(application_surface,ideal_width , ideal_height);`

---
Tags: android, game-maker, graphic-effects
---


# Question
Title: Unity dynamic light isn't casting shadows
I am using the Lightweight Scriptable Render Pipeline 1.1.11-preview and I have two lights in the scene. One is a Sun light and another is an uplight. The Sun light is set to cast dynamic shadows, as are the particle effect clouds and the models. I am expecting the clouds and the cloudship (the floating thing in the middle of the picture) to cast shadows.

The sand is procedurally generated: a flat prefab is loaded at run time and the `y` points are set by Perlinn noise. I recalculate the normals using Unity's method.

Here is the scene:

The properties of the Sun light:

The prefab for the sand (which I am expecting to have shadows):

Here is the lighting properties.

The setting window for the Lightweight Pipeline:

The settings for the mesh that should be casting the shadow:

Is there anything I'm missing? Thanks in advance.

# Answer
In Lightweight Render Pipeline asset, my distance was set to 50. As my objects are large and set outdoors, this was not far enough to cast shadows. Below, I have set it to 6000 units, which is roughly the render distance of my scene.
> 1 votes

---
Tags: unity
---


# Question
Title: What are perimeter and aspect ratio, in the context of 3D mesh approximate convex decomposition?
I'm trying to understand the logic behind Mamou and Ghorbel's algorithm in their paper A Simple And Efficient Approach For 3D Mesh Approximate Convex Decomposition.

I cannot understand what is the aspect ratio of a surface as defined by the author. It includes the perimeter of two vertices v and w. These two vertices represent two triangles in the original mesh as they come from the dual graph as the authors define it. So I'm guessing they are talking about the perimeter of the two triangles these vertices correspond to. What is the perimeter of two triangles? Do they mean the sum?

The algorithm proceeds like this:

1. Create a dual graph of the mesh, where each vertex corresponds to a triangle of the original mesh, and two vertices are connected by an edge iff their corresponding triangles share an edge.
2. Iteratively choose and collapse an edge, so that two vertices are merged into one. We keep track of the "ancestors" of each vertex, A(v) that have been merged into it in this way.

Here's where I get confused:

> The decimation process described in the previous section is guided by a cost function describing the concavity and the aspect ratio \[5\] of the surface \\$S(v, w)\\$ resulting from the unification of the vertices \\$v\\$ and \\$w\\$ and their ancestors:
>
> $$S(v, w) = A(v) ∪ A(w) ∪ {w, v}. (2)$$
>
> As in \[5\], we define the aspect ratio \\$E\_{shape}(v, w)\\$ of the surface S(v, w) as follows:
>
> $$E\_{shape}(v, w) = \frac{ρ2(S(v, w))}{4π × σ(S(v, w))}, (3)$$
>
> where \\$ρ(S(v, w))\\$ and \\$σ(S(v, w))\\$ are respectively the perimeter and the area of \\$S(v, w)\\$.

# Answer
> 0 votes
I wasn't able to find a free version of AK Jain's book "Fundamentals of digital image processing" referenced as \[5\], so this is a little bit of speculation on my part.

Since \\$S(v, w)\\$ is a subset of dual graph, formed from vertices v, w, and all of their ancestors from previous edge collapse operations, it corresponds to a contiguous subset of triangles in the original mesh.

* We can sum the area of each triangle that has been merged with v or w (including v & w's own corresponding triangles) to form the area of this 2D surface
* We can take all uncollapsed edges incident to v or w (but not both), and sum the lengths of their corresponding triangle edges in the original mesh to find the perimeter of this surface.

(Note that after several edge collapse operations, you may have multiple edges joining a pair of vertices - representing multiple triangle edges forming the border between two clusters. If your collapse method simplifies these to a single edge, then you'll want to sum their lengths as you go or keep track of edge ancestors so you can find the total length along the border)

This construction will allow the aspect ratio to drop below 1 if the surface is curved (eg, if it's shaped like a fishbowl, with a large surface bounded by a narrow hoop). It could even drop to zero if v & w are the last two clusters in an island of the graph, so their union corresponds to a closed surface with no loose edges.

---
Tags: 3d-meshes, computational-geometry
---


# Question
Title: Is there a way to check if an object is currently colliding with anything?
I need to test from another Script on a different GameObject, whether a particular GameObject is colliding with anything (in particular using trigger).

So, for my purpose, I don't need OnCollisionEnter/OnTriggerEnter events, but I need something like this:

```
if ( myObject.isOnCollision )
   do something

```

How can I do this?

# Answer
> 3 votes
If you need a trigger collider to keep track of whether *anything* is touching it, you can attach a script to it like so:

```
public class Sensor : MonoBehaviour {
    int _overlaps;

    public bool isOverlapping {
        get {
            return _overlaps > 0;
        }
    }

    // Count how many colliders are overlapping this trigger.
    // If desired, you can filter here by tag, attached components, etc.
    // so that only certain collisions count. Physics layers help too.
    void OnTriggerEnter(Collider other) {
        _overlaps++;
    }

    void OnTriggerExit(Collider other) {
        _overlaps--;
    }
}

```

Now another script with a reference to `public Sensor mySensor;` can query `if(sensor.isOverlapping) {...}` to change behaviour when something is inside this sensor trigger.

Or you can use the various Physics.OverlapBox/OverlapSphere/etc. methods to query a shape of space for collisions.

# Answer
> 0 votes
You could use tags or layers I guess to make sure it is the right object that is colliding. So I believe (if I understood correctly your problem) that you need in fact OnCollisionEnter/OnTriggerEnter.

```
private void OnTriggerEnter(Collider collision){
    if (collision.gameObject.tag == "TheOtherObjectTag"){
      Debug.Log("Collision using tag");
    }
    if (collision.gameObject.layer == 1 << LayerMask.NameToLayer("TheOtherObjectLayer")){
      Debug.Log("Collision using layer");
    }
    if (GameObject.ReferenceEquals(collision.gameObject,myOtherGameObject)){
      Debug.Log("Collision using an object reference");
    }
}

```

I didn't try the code but I think the syntax is OK. Tell me if this is not what you need, and please explain further if it is not.

# Answer
> -1 votes
I am sure about my code it works and using it.

first you need a void OnTriggerEnter (Collider other) unity builtin function to use enter collider or for exit collider functions create a tag and use exact name

```
 private void OnTriggerEnter(Collider other)
{
    if (other.gameObject.tag == "Mytag")
    {
        GameObject explosion = Instantiate(Resources.Load("FlareMobile", typeof(GameObject))) as GameObject;
        explosion.transform.position = transform.position;
        Destroy(explosion, 2);
        explosionAud.Play();
        boxend();

        Debug.Log("fireeeee");
        //   Destroy(gameObject);
        Destroy(gameObject, 5);
    }
}

```

---
Tags: unity, collision-detection
---


# Question
Title: Additive, Alpha Blended, Unlit, Lit differences?
Short question, what's the difference between the shaders used for particle, and how they affect the visual.

Additive
Alpha Blended
Unlit
Lit

# Answer
"Lit" shaders are affected by lighting in your scene. So your smoke plume may be bright where it wafts through the cone of a street lamp, and dark where it passes into shadow.

Lighting calculations considerably increase the complexity of drawing the particles, so for many effects we'll prefer to use "Unlit" shaders, to skip the expensive lighting calculations and just draw the same particle appearance regardless of surrounding light and shadow. This works well for ethereal, magic, or explosive particle effects that aren't visibly affected by light sources, or for effects that are only ever shown in a single lighting environment so we can tune the parameters to match that one context.

"Additive" blending means that we compute the colour of the particle over the colour of the background scene behind it by adding the two colours. So a red particle over a green background becomes yellow. This is suitable for glowing effects like fire or sparks or magic energy, since the result is always as bright as the background or brighter. A black particle won't change the background at all (x + 0 = x). Against very bright backgrounds though, these effects can get washed out, since there's not much headroom to add more brightness. An advantage of additive blending is that it's order-independent. The results of a stack of additive blended effects will be the same without sorting, and you won't see popping as the order changes.

"Alpha Blended" means that the colour of the particle over the colour of the background scene behind it is computed by taking a weighted average (or "lerp" linear interpolation) of the two colours, using the opacity alpha value of the particle. This is often called "standard" or "layer" blending, and it can represent solid or dark materials. Unlike additive blending, this one is order-dependent, meaning that you need to sort the particles to get a consistent appearance, and you can sometimes see popping if the order changes.
> 8 votes

---
Tags: unity, shaders, particles
---


title: Simulating an aging population

text:
# Question
Title: Simulating an aging population
**Introduction:**

The main idea is to "classify population as they age". Let me further explain it with an example:

**Example:**

There are 50k population (we are not going to care about if male or female for now). Inside these number there are kids \[0 - 16\], fertile\[16 - 40\], non-fertile \[40 - 100\].

**Question**

Which would be a nice implementation to represent an evolving population data that is better or at least not too resource intensive as my example below?

**My Idea**

(Pseudo code)

```
Population[] // Array
   Age [0 -> 5] //Array
       a pop obj that stores data
   Age [5 -> 10]
       pop obj
   .
   .
   .
   Age[95 - 100]
      pop obj

```

This would be the structure and each tick happens this calculation:

```
FertilePop.count * fertility rate * (some other stuff) = numberOfBirths

```

where `numberOfBirths` are added to the `Age[0-5].obj.count`

and the rest of `Age[rang]` are subtracted a number and added onto the next `Age[rang]` until `Age[95 - 100]` where they "die of old age".

**Notes:**

This is purely background data and i am asking for a better solution/implementation that could be less complex, more dynamic and learn from it.

I expect to be able to do a graph plot so the user sees the pop evolution.

I took my interest in the matter from this link here to a population simulator.

https://niko.roorda.nu/computer-programs/popsim-population-simulation/

Thanks for your interest in this question.

# Answer
Myself, I'd be tempted just to make an array with 100+ entries, one for each year of age. (Assuming your game mostly runs in a granularity of years. You could boil it down to seasons or months if needed)

It may seem overkill, but an array with a few hundred entries (particularly if they're simple structs) is really nothing for modern processors to chew through. They *love* working on big swaths of contiguous data like that.

And this way we don't have to worry about variation inside a multi-year age bucket, which can lead to some complicated situations.

For example, let's say we have 5-year buckets. To simulate aging we could assume that each year, 20% of the people in one bucket graduate to the next one. So our aging formulas might look something like:

```
Age_0_to_4_new = Age_0_to_4_old * 0.8 + birthrate;
Age_5_to_9_new = Age_5_to_9_old * 0.8 + Age_0_to_4_old * 0.2;
...

```

Now imagine a calamity sterilizes the population, so `birthrate` goes to zero. In five years' time we should have emptied the `Age_0_to_4` bucket, and no more people should graduate into the `Age_5_to_9` bucket, but instead...

```
  Years After Calamity     Population in Age_0_to_4
  -------------------------------------------------

          0                     10 000
          1                      8 000
          2                      6 400
          3                      5 120
          4                      4 096
          5                      3 277
          6                      2 621
          7                      2 097
          8                      1 677
          9                      1 342
         10                      1 074

```

The lack of a within-age-group distribution model means we've still got babies well after they all should have grown up to the next age group! This creeps in more subtly even without sudden calamities, where any change to your population's circumstances gets smeared out, with the previous conditions lingering on longer than they should and biasing the results.

If we instead just store one record per year, we don't even need fancy a formula to graduate the population to the next bucket each year: we can simply treat the array as a ring buffer and move our start point back by one, while all the data stays where it is. Then all that remains is a mortality pass to diminish numbers in-place, and a birthrate pass to initialize the new starting entry.

When you want to query totals over an age range, you just iterate over the years in question. Again, modern processors are optimized for exactly this kind of consecutive number crunching, so even if it seems wastefully inefficient, the simple repeated adding is likely to be faster in practice than more sophisticated chunked models that treat the population more abstractly.
> 2 votes

# Answer
I wonder if you really need to have a pop object. What speaks against using a matrix type of structure to store demographic values (e.g. amount of fertile) and model how those evolve over time?

*Adding from the discussion below*

Ok, so two possibilities come to my mind. First, you keep it the way you have right now. Depending on what you want to model, memory or performance should not be a big issue and you could always iterate over the objects to get a cross sectional snapshot of your population. The second possibility is that you do not use individual data structures at all, but a set of equation modeling population evolution. In this scenario, your population distribution (i.e. how many of which age, from what gender, background, etc) at time point t would be mathematically calculated from time point t-1. An example of such modeling: https://www.inf.ethz.ch/personal/cellier/Pubs/BG/springer\_chap10.pdf
> 1 votes

---
Tags: unity, c#, data-structure, simulations
---


# Question
Title: Use IPointerEnterHandler with bool function?
Im trying to use mouse pointer to detect any UI element on my canvas. when pointer enter any UI element, UI\_active set true, else UI\_active set false. Here is my script:

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;// Required when using Event data.

public class UI_AVATAR : MonoBehaviour, IPointerEnterHandler {

public bool  UI_active;

public void OnPointerEnter(PointerEventData eventData)
{
    Debug.Log("The cursor entered the selectable UI element.");
    print(eventData.currentInputModule.name);
    print(eventData.pointerCurrentRaycast.gameObject.name);

}

}

```

# Answer
> 1 votes
If you really only care about whether the pointer is over *any* button, not whether it's over a specific button, then I think the method you want is:

```
EventSystem.current.IsPointerOverGameObject();

```

IsPointerOverGameObject returns true if (the given) mouse cursor / finger is over any event system object in your UI, serving the role of your `UI_active` variable.

---
Tags: unity, gui
---


# Question
Title: How can I change a variable value in specific time duration according to animation clip time length?
I will change my question with more details to make it more clear:

1. In the Assets I created Animator Controller and Animation: Named them both FPSController. FPSController is the object I want to animate it's rotation on the Z from 50 to 0:

2. Then I opened the Animator window and dragged the Animation into the Animator window:

3. Then I opened the Animation window and recorded the clip: The rotation on Z is going from 50 to 0 in 7 seconds. I'm rotating the FPSController on the Z from 50 to 0:

This is the Animation part and this is working fine. The FPSController(player) is starting when the Z rotation value is at 50 and slowly move to 0.

Now The game is start when the whole camera is blurry. For this I'm using Post Processing. Next step was to create a profile of the Post Processing called it CC and this profile I dragged in the Hierarchy to the FPSCamera:

In the FPSCamera I dragged to it a script name Post Processing Behaviour and then dragged to the script in the Inspector the CC profile: This way the Post Processing effects affecting the camera view:

So to make it clear: I'm rotating on the Z the FPSController by animation. And on the FPSCamera I'm using the Post Processing for making effects.

This is how the game start. This is the game view screenshot. The game start when everything is blurry and the FPSController(player) is rotating to the right by 50 degrees:

Now the part of the animation of rotating the FPSController by 50 is working fine. While it's rotating the FPSController I want slowly by the same time in this case 7 seconds to change the blurry effect and make the picture clear once the animation end. The property of the Post Processing CC profile I need to change is the focalLength. By default I start it with the value of 300. And I need in 7 seconds to change it from 300 to 0.

This is the script I ended with so far: The script is attached to the FPSCamera:

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

public class DOFControl : MonoBehaviour
{
    public PostProcessingProfile postProcProf;

    public Animator anim;
    private float clipLength;

    private void Start()
    {
        AnimationClip[] clips = anim.runtimeAnimatorController.animationClips;
        foreach (AnimationClip clip in clips)
        {
            clipLength = clip.length;
        }

        InvokeRepeating("incrementSpeed", 300, 0.1f);
    }

    void incrementSpeed()
    {
        var dof = postProcProf.depthOfField.settings;
        dof.focalLength -= 1f;
        postProcProf.depthOfField.settings = dof;
    }
}

```

I'm getting the animation clip time length 7 seconds. But the part with the InvokeRepeating is not working. I want to incrementSpeed the focalLength down from 300 to 0 by 7 seconds. Not sure if using InvokeRepeating is the right way at all.

# Answer
you can grab the cliptime with something like this then check against that all within the ienumerator if you wanted

```
    Animator anim;
    var animationClips = anim.runtimeAnimatorController.animationClips;
    for (int i = 0; i < animationClips.Length; i++)
    {
        if(animationClips[i].name == "AnimationName")
        {
            var clipTime = animationClips[i].length;
            if (clipTime == myEventTime)
            {
                focalLength = 0;
            }
        }
    }

```

Ok reading through the update. I would use a coroutine to decrease the focalLength over time.

```
 public FloatParameter focalLength;
 private float increment;
 private void Start()
 {
    focalLength = postProcProf.GetSetting<DepthOfField>().focalLength;
    increment = focalLength.value / clipTime;
    StartCoroutine(DecreaseFocalLength());
 }
 IEnumerator DecreaseFocalLength()
{
    while (Time.time< clipTime)
    {   //so if the focal starts @300 and the clipLength is 7 it will divide 42.8571428ect.. / second then stop
        focalLength.value -= increment;
        if (focalLength.value <= 0) focalLength.value = 1;
        yield return new WaitForSeconds(1);
    }
}

```
> 1 votes

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


# Question
Title: How to decide how many textures to break an object into?
So I am making a couple spacecraft in my game. And I want them to look sharp and as photorealistic as possible.

How can I decide if a certain craft should be broken into multiple meshes to each have its own texture based on its size?

Is there a rule? Like if you are using 4096 size textures. Obviously a bicycle could be a single mesh with 1 texture.

But what about a small sports car? An SUV? A dumptruck?

# Answer
Think about the texel density you want: how many unique texels of texture per meter of surface?

You can work out a minimum texel density by taking a typical view of your object in your game, and measuring its pixel size on your target display, divided by the in-world size of the (part of the) object you're looking at.

Multiply that density by the total size of the object to get a ballpark of how many texels you need to texture the whole thing uniquely at that density.

If you have areas that can re-use the same parts of the texture, you can exclude them from the calculation.

Now that you have a rough idea of how many texels you need, check whether it fits into a common texture size like 2048 or 4096. If you need larger than that, you'll likely want to break it up into multiple textures (or multiple entries in an array texture), since some devices don't support larger textures.

If the number of textures looks too high for your application, then you can look into alternatives to uniquely texturing your whole object at that texel density, like layering in fine detail or tiling detail maps over lower-res textures for the broader strokes.
> 3 votes

---
Tags: opengl
---


# Question
Title: GL_INVALID_OPERATION on glBindVertexArray Despite glGenVertexArrays()
so I've been trying to create a simpler way to draw polygons and and have come across the following issue:

When I call `glBindVertexArray(m_VAO);` it throws a `GL_INVALID_OPERATION` even though I have previously called these functions:

```
glGenVertexArrays(1, &m_VAO);
glBindVertexArray(m_VAO);

```

Why does this happen? The only description for this error officially is that I failed to call the lines above.

Here is the source with any relevant parts. Please note that I have the error pop up the line after this one, but it might be because of this current error.

```
Polygon::Polygon(const std::vector<GLfloat>& vertexArray,
         const char* vertShaderPath,
         const char* fragShaderPath)
    :m_vertexArray(vertexArray)
{
    // Created and linked shaders here...
    // ...
    // ...

    // Generate and bind vertex array object.
    glGenVertexArrays(1, &m_VAO);
    glBindVertexArray(m_VAO);

    // Generate and bind vertex buffer object.
    glGenBuffers(1, &m_VBO);
    glBindBuffer(GL_ARRAY_BUFFER, m_VBO);

    //Send verticies to buffer's memory.
    glBufferData(GL_ARRAY_BUFFER,
         m_vertexArray.size() * sizeof(GLfloat),
         &m_vertexArray[0],
         GL_STATIC_DRAW);

    // Set up vertex attributes.
    glVertexAttribPointer(0,
              3,
              GL_FLOAT,
              GL_FALSE,
              3 * sizeof(GLfloat),
              (GLvoid*)0);

    // Enable the attributes at layout position 0.
    glEnableVertexAttribArray(0);

    //Unbind VBO and VAO.
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);
};

// Destructor
Polygon::~Polygon()
{
    // De-allocated resources
    glDeleteVertexArrays(1, &m_VAO);
    glDeleteBuffers(1, &m_VBO);
}

void Polygon::draw()
{
    glUseProgram(m_shaderProgram);
    check_gl_error();
    glBindVertexArray(m_VAO); // GL_INVALID_OPERATION here
    check_gl_error();
    glDrawArrays(GL_TRIANGLES, 0, m_vertexArray.size()); // GL_INVALID_OPERATION here
    check_gl_error();
    glBindVertexArray(0);
    check_gl_error();
}

```

Let me know if you need any more info. Thanks!

# Answer
Since `m_VAO` is valid in constructor but not in `draw()`, it seems that the destructor was called before `draw()`, perhaps by copying an instance of the `Polygon` class.

P.S. Errors like these could be prevented by following the Rule of three.
> 5 votes

# Answer
There is another way this can happen (I just ran into this one myself); VAOs are like FBOs; they aren't shared between shared OpenGL contexts. That if, if you call glGenVertexArrays() from one shared context, you can't use those VAOs from other shared contexts. Unlike texture objects, VBOs, and a bunch of other OpenGL data, you need to create VAOs within the context that will be binding them.

(Of course, people generally advise against using shared contexts in the first place. But if you're using them anyway, this is something that can bite you!)
> 5 votes

---
Tags: opengl, c++, vertex-arrays, vao
---


# Question
Title: How to rotate an object to a specific transform?
I am working on a car racing game and there are some times when the car rotates and ends up on its roof. On those situations I want the car to respawn on the same location. What can I do to rotate it so the car ends up on its wheels?

# Answer
> 1 votes
you can check if roof hit with ground then respawn it.

attach this code to your car's roof:

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

public class RoofCheck : MonoBehaviour {

//if roof hit with ground
void OnCollisionStay(Collision other)
{
   if(other.gameObject.tag == "Ground"){
   Respawn();
   }
}

void Respawn(){
    //Reset to same position
    var respawnPos = transform.position;
    respawnPos.y += 5;
    transform.position = respawnPos;

    //Reset rotation
    transform.rotation = Quaternion.LookRotation(transform.forward);

}
}

```

use the direction to the next waypoint on the track:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class RoofCheck : MonoBehaviour {
    public List<Transform> wayPoint = new List<Transform>();

//if roof hit with ground
void OnCollisionStay(Collision other)
{
   if(other.gameObject.tag == "Ground"){
   Respawn();
   }
}

void Respawn(){
    //Reset to same position
    var respawnPos = transform.position;
    respawnPos.y += 5;
    transform.position = respawnPos;

    Vector3 closestPoint = FindClosestTarget(wayPoint).position;
    transform.rotation = Quaternion.LookRotation(new Vector3(0,0,-closestPoint.z));

}

Transform FindClosestTarget(List<Transform> list)
{
    Vector3 position = transform.position;
    return wayPoint.OrderBy(o => (o.transform.position - position).sqrMagnitude).FirstOrDefault();
}
}

```

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


# Question
Title: How do I provide incentive to a player to choose a specific option in a choice driven narrative
I am making a game where the choices you make are very real and have consequences that change the way the game plays. The game is styled after Chrono Trigger or Final Fantasy, in the way it plays and the style of art.

I am writing the flow-chart for the choices and the inciting event happens when the player chooses a specific choice. I want the game to stay open and I don't want to force the player into any choice by only presenting one option.

The inciting event occurs when the player goes out to get food for his dog (or cat, depending on what pet the player chose when he was creating his character) How do I provide enough incentive to cause the player to go out and get food for his pet?

# Answer
> 3 votes
You say you don't want to force the player to make a choice by presenting only one option, but there is only one option which leads to your game's story to start.

Do you see the problem?

If you want to provide (the illusion of) choice from the get go, give the player multiple options of what to do, but have all of them somehow lead up to the inciting incident (or an alternative inciting incident which also kicks off the main plot, but from a different direction).

But you might want to reconsider if this is really the best approach.

Even if you want your game to be an open world sandbox, you might want to consider to railroad your player a bit during the first few minutes of the game. If you look at some of the best-selling open world games, you will notice that almost all of them do this. A linear start ensures that the player received a basic tutorial and the minimum of information they need to understand the basic premise of your game's narrative. When you don't ensure this before you set them free in your open world, you risk that they don't understand what's going on (both mechanically and narratively) and get lost.

But this railroading doesn't actually need to be that obvious. You can do it quite subtly if you are creative.

If you just want the player out of their home to explore, then there isn't much you need to do. Exploring their environment is the basic instinct of every player. When you put a player into a building with an exit, they will leave it, because there is nothing else they could be doing.

Now where are they after they left their house? I would assume in some kind of town. When you don't want the player to leave their home-town before *inciting incident* happened, find some plausible reason why they can't leave (yet). Or place the trigger area which causes the *inciting incident* event to happen on the only path which leads out of the town, so they stumble upon it automatically while exploring. To increase the illusion of choice, provide lots of small optional things the player can do before they trigger the *inciting incident*:

* Small details of the town to interact with
* Shops to browse in.
* NPCs to talk to with branching dialog options which allow the player to express their character's personality.
* Maybe even a short sidequest or two with multiple outcomes.

I'm looking forward to playing your game.

---
Tags: 2d, game-design, open-world
---


# Question
Title: Maya: after bake into control rig, IK will auto reset when I change another IK
Arter setting one IK on my control rig, when I start to set the next IK, the previous one resets to its prior state.

Here's an example of my problem:

How can I keep the previous IK from resetting?

# Answer
> 1 votes
update 18-7-11 finally I find the best way is use maya "Auto Key"

update 18-7-11 I find my old solution is not good, it cause I cannot select time slider, so I should use following way to instead:

I should following way to fix it:

```
scripJob -attributeChange

```

when attributeChange, auto save key

update 18-7-10 following is my code to fix this bug, invoke my code `fix` meth in maya script editor \> python

```
import maya.cmds as mc
from kernel import *
def fix():
    mc.scriptJob(event=["timeChanged", reselect_character])

last_key_frame = None

def reselect_character():
    """
    I cannot find maya python get cur character func, so I default use ro_character character set
    :return:
    """
    global last_key_frame
    cur_key_frame = mc.currentTime(query=True)
    if cur_key_frame == last_key_frame:
        last_key_frame = cur_key_frame
        return
    character_set_name = "ro_character"

    if (not mc.objExists(character_set_name)):
        mel("character -name " + character_set_name + " -excludeVisibility -excludeScale;")
    mel("setCurrentCharacters( { \"" + character_set_name + "\" } );")

```

update 18-7-9 I find this bug occurs when time slider click(time change)

when i create character set, and reselect current same character set("No Character Set" doesn't work), the ik will not be reset, the bug wil fix

how to:

make maya script

update -timeChange cannot when click time slider, use scriptJob \> timeChanged Cond; maya mel: scriptJob -timeChange, it can detect time slider change,

when time slider change, reselect current character set

if not character set, create character set in maya script

**following soluiton doesn't work, see above solution**

I guess it's bug in maya 2017, when i preferences \> settings \> time slider \> key ticks \> select "channel box" and click save

it fixed, and then i select "key ticks" \> "active", it still fixed

I guess maybe my prefs interrupt and when i click Preferences \> "save", the prefs will return to normal

---
Tags: maya
---