# Question
Title: Legal to make and sell a game engine made with Unity3D?
does anyone know if it's legally sound to create a game engine within unity, build it as a standalone and sell it as a product? The engine would allow users to compile their own games through it.

It is a product made within Unity after all so I'd assume so. Tons of businesses also use Unity to create applications that are not games.

Thanks!

# Answer
> 4 votes
That would be a violation of the Unity Terms of Service section 2.6 (d).

> You may not \[...\] use the Unity Software for competitive analysis or to develop a competing product or service;

---
Tags: unity, legal, commercial
---


# Question
Title: Why real time lightning fails to show shadows on terrain in Unity?
I'm using the TerrainTools unity package to create a simple 500x500 terrain, and placing a simple character that moves around, however, by default, the lightning is at real time mode, and the shadows over the terrain flicker like this:

https://youtu.be/\_eFFDCRjObY

I know I can set the terrain as static and bake the lighting, however, doing that I lose my character shadow.

So my questions are, why this happens over real time lighting?, and, why I cannot see my shadow on a dynamic mesh over baked lightning?

Here you can see my lighting and directional light configs:

Lighting config:

Directional light config:

# Answer
> 3 votes
Flicking shadows on terrain can often be fixed by adjusting the "Bias" and "Normal bias" of the light source. However, adjusting those settings does have side effects, so you should pay attention to how the settings affect your shadows in different areas (especially on high-detail objects close to the camera). In the worst-case scenario, you might have to use tricks, like rendering nearby objects with one camera/directional light, and distant objects with a different camera/directional light, to get close and distant objects to both look right.

Other possible causes of flickering shadows:

* The camera's near clipping plane is set too low (it should usually be at least 0.3 and may need to be set higher if the far clipping plane is very large).
* The camera is very far away from the world center (more than 100,000 units if I remember correctly).

Baked lighting doesn't cast real-time shadows (e.g. character shadows) because it's baked. Baking your lighting essentially renders the shadows into a texture that is applied on top of the meshes. For traditional baked lighting, there's very little performance cost but it's completely static. However, you can combine real-time and baked lighting using mixed lighting.

Baked and real-time lighting are important concepts, so if you weren't already familiar with the differences between them, you should take some time to thoroughly read the Unity documentation on the different lighting modes.

---
Tags: unity, lighting
---


# Question
Title: How to detect if a 2D object overlaps any other 2D objects
I am programmatically placing 4 large dots on my 2D scene which already has some objects on it. If the new dot overlaps an existing object I want to destroy the existing object. All the objects have 2Dcolliders and all are on the same layer ("Action").

Since I only do this once during the initial setup of the game I don't want to use collision detection events, instead it would seem that Collider2D.OverlapCollider would be the way to do this but I can't get it to work. The following code is called from Start() after all the objects have been placed, and thinking it might be something to do with the colliders not being active until the first frames, I also called it from a mouse click with the same result (no overlaps).

```
    void EraseOverlapDots()
    {
        GameObject[] largeDots = GameObject.FindGameObjectsWithTag("LargeDot");
        foreach(GameObject ldot in largeDots)
        {
            Debug.Log("Object:" + ldot.tag + "(" + ldot.transform.position + ")");

            Collider2D collider = ldot.gameObject.GetComponent<Collider2D>();
            ContactFilter2D contactFilter2D = new ContactFilter2D();
            contactFilter2D.SetLayerMask(ldot.layer);
            contactFilter2D.useLayerMask = true;

            List<Collider2D> collisions = new List<Collider2D>();
            int colCount = collider.OverlapCollider(contactFilter2D, collisions);
            int i = 0;
            foreach (Collider2D col2d in collisions)
            {
                i++;
                Debug.Log("HIT"+i+":" + col2d.tag + "(" + col2d.transform.position + ")");
            }
        }
    }

```

In an attempt to debug this I purposely put 4 small dots in exactly the same position as the large dots to ensure they overlap. When I run the game they are visibly exactly on top of each other but the result is always zero overlaps.

# Answer
> 1 votes
I'm answering my own question because I did get this working. The problem was with the layermask.

Change this line:

```
contactFilter2D.SetLayerMask(ldot.layer);

```

to either:

```
contactFilter2D.SetLayerMask(Physics2D.GetLayerCollisionMask(ldot.layer));

```

or:

```
contactFilter2D.SetLayerMask(LayerMask.GetMask("Action"));

```

Both seem to work with the second version being easier to understand and more flexible since you can specify multiple layers if needed such as:

```
contactFilter2D.SetLayerMask(LayerMask.GetMask("Action", "Default"));

```

This solution was inspired by a comment at the bottom of this Unity Forum post: https://forum.unity.com/threads/solved-collider2d-overlapcollider-returns-0-and-no-overlaps-are-found.642409/

I have not yet found any detailed explanation or tutorials on ContactFilter2D.

---
Tags: unity, c#, 2d, collision-detection
---


title: Why would I add components in code?

text:
# Question
Title: Why would I add components in code?
Watching a Unreal Course, and the instructor is creating a default pawn c++ class. He is adding all the components with code, but this seems really inefficient to me. Why can't you add components in the engine like you can with blueprint classes? Also, I know you can convert c++ classes to Blueprint classes and still code using attached c++ components, is there a downside to doing this?

my main questions are these:

What is better about adding components in code?

What is the difference between creating a blueprint class and creating a c++ class but converting it into a blueprint?

What are the benefits of each? thnx.

# Answer
> 2 votes
For a bigger project, the C++ programmer is unlikely to be the level designer or artist responsible for the items in BP.

Adding items in code means that the non-programmers cannot remove components that are critical to the running of that code because they don't know why they're there.

You don't make a C++ class and convert it to BP. You create a Blueprint based on a C++ class which contains all the functions and variables which can be exposed to BP with UFUNCTION and UPROPERTY respectively.

C++ is faster than Blueprint since BP uses an emulator to call C++ code in the engine and is slower (tests have shown by up to 7x slower) and with C++, you can get hold of the parent C++ code and modify it as you need to.

C++ can be much simpler as well. In the original, now archived course, the next section is Testing Grounds and introduces behaviour trees and blackboards. In one of the modules, the Blueprint part is made up of 12+ nodes which, when converted to C++ is 3 lines long.

Blueprints, on the other hand are considerably easier to prototype with and will quickly tell a programmer whether something you're planning is achievable.

There are also scenarios where C++ is more work than you'll get benefits from; displaying UI is the biggest one of these.

---
Tags: c++, unreal-4, blueprints
---


# Question
Title: How to align the Polygon Collider 2D in Unity to match the position of Sprite?
How to align the Polygon Collider 2D in Unity to match the position of Sprite?

I have a game object. It has a Sprite Renderer with an image. Now I add a Polygon Collider 2D component to the game object, that generates a collider. The shape of the generated collider is correct as expected - i.e. it matches the image from the Sprite Renderer. But the position of the collider is wrong. Here you can see what I mean:

For sure I have a solution - I can manually configure the Offset of the Polygon Collider 2D. But that would take a significant amount of efforts and time (because I have a lot of such game objects, which need to have a sprite and collider). So, I am hoping to find a solution which would position the generated collider correctly. I.e. in such a way, so that the boundaries of the collider would match the boundaries of the sprite.

# Answer
> 1 votes
The issue most likely has to do with the skin & bone animation. The polygon collider will not update itself every frame while the sprite is animating.

Your best option would be to use a simple collider instead, but if you really need it to be very accurate, you'll need the colliders to be placed on the objects and updated as they rotate/move around.

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


# Question
Title: How can I play a YouTube video in Unity if given the YouTube URL link?
How can I play a YouTube video in Unity if given the YouTube URL link? I am using 2019.4.13

Is there a way to open webpages?

# Answer
Unity can't play youtube videos out of the box. Youtube generally doesn't support streaming of videos outside of YouTube itself (or an iframe with the YouTube player widget within another website).

There are tools that download youtube videos, however these violate YouTube's terms of service so I would not recommend using them.
> 2 votes

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


title: How to Make Saving System More Secure

text:
# Question
Title: How to Make Saving System More Secure
I've been working on an saving system for my 2D RPG game, and I recently encountered an issue: my saving system uses **PlayerPrefs**, which I heard is supposed to be used for things such as settings. I've also heard that it isn't very secure and that people can exploit it. I was wondering whether there was a way to make my saving system more secure. Here's my inventory script that also holds the save function:

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

public class ItemInformation : MonoBehaviour
{
    // These are the assets for the item to change
    public Text nameText;
    public Text descriptionText;
    public Text regenText;
    public Text amountText;

    // This is the identifier for each item
    public string identifier;

    // These are the variables that change with the different items
    public string itemName;
    public string itemDescription;
    public float itemRegeneration;
    public int itemAmount;

    // Starts on awake
    void Awake()
    {
        // Function to change the object's information and such
        nameText.text = itemName;
        descriptionText.text = itemDescription;
        regenText.text = "HEALS " + itemRegeneration + "HP";

        // Loads game data
        LoadDataIfNeeded();
    }

    // Function to save game data
    public void SaveData()
    {
        string jsonString = JsonUtility.ToJson(this);
        PlayerPrefs.SetString(identifier, jsonString);
        PlayerPrefs.Save();
    }

    // Loads data if needed
    public void LoadDataIfNeeded()
    {
        if (PlayerPrefs.HasKey(identifier))
        {
            string jsonInstance = PlayerPrefs.GetString(identifier);
            JsonUtility.FromJsonOverwrite(jsonInstance, this);
        }
        else
        {
            SaveData();
        }
    }

    // Updates on every frame
    void Update()
    {
        // Shows amount of item left
        amountText.text = "HAVE:" + itemAmount;
    }
}

```

# Answer
Since you wrote in a comment it is for an offline game, the short answer is: you can't.

If the player is the owner of the whole game (since it offline), any kind of mechnism can be prevented if he is dedicated enough to figure out how you obscured your data. You can only make it harder for him.

You need to prevent memory manipulation, else the player could either freeze his hitpoints, ammo, money, etc or increase it to his liking.

The second part is you need to protect the save file itself against manipulation. Since he can read it as well, you need to make it harder for him to read and change values. Binary files, custom formats and a hash of everything are doing the job. The draw back (if that is one for you) is, if he really tries to manipulate the file, he might create new run time errors when you try to read your own file since the format got broken (and the player will certainly blame it on you why all his items are gone)

There is the opinion that if the game is offline, you should let the player do what he wants. Maybe the game is too hard and he would otherwise stop playing. Maybe he is lacking time for farming. As long as he is the only player, all he can do is boost himself and has no effect on the play experience of other players.
> 3 votes

# Answer
First, I'd not recommend saving in `PlayerPrefs` for large saves, it would be better to save it in a file at `PersistentDataPath` instead.

As for preventing the player from modifying it, the simplest way would be to encrypt the file before saving it to the disk, and then decrypt it when loading. The encryption key would be hard-coded to your program so there wouldn't be any external file that the player can access in order to easily decode and modify your save file, but any decompiler can easily see your program's code and extract that key. It would require some more technical know-how, so most simple players would not be able to do that.

You can go even further by using a native plugin to hide your encryption key in, and add complex code that generates the key real-time (instead of simply entering a string which hackers can easily find).

All that said - if it's a single player game, there's no real reason to work so hard to prevent cheating. A simple encrypted save file will be very easy to implement and will do the trick nicely for most cases. Even that may be too much since if a player decided they want to cheat, why do you care, whatever makes the game more fun for them should be good for you.
> 0 votes

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


# Question
Title: How to Make GameObject move in Circular Motion
I've been trying to work an enemy that moves in a circular motion for my RPG game, but for some reason, whenever I press play the GameObject instantly goes hundreds of units in the X and Y coordinates. It also move back to -1 on the Z axis. Here's the script to my enemy's movement:

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

public class EnemyScript : MonoBehaviour
{

    private Rigidbody2D rb;

    [SerializeField]
    float rotationRadius = 2f, angularSpeed = 2f;
    float posX, posY, angle = 0f;

    // Start is called before the first frame update
    void Start()
    {
        // Gets the RigidBody2D component
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        Movement_1();
    }

    void Movement_1()
    {
        posX = rb.position.x + Mathf.Cos(angle) + rotationRadius;
        posY = rb.position.y + Mathf.Sin(angle) + rotationRadius;
        transform.position = new Vector2(posX, posY);
        angle = angle + Time.deltaTime * angularSpeed;

        if (angle >= 360f)
        {
            angle = 0f;
        }
    }
}

```

# Answer
You have a double-delta there. You have a delta on the position (you change the position relative to the current position, based on the angle), and you also have a delta on the angle (you change the angle relative to the previous angle). That is equivalent to having the position change every frame, but also having the velocity change every frame.

What you want to do is increase the angle every frame, but the position itself should be set using a formula based on the angle, but not based on the previous position. Only one element that changes relative to itself - the angle.

So something like this:

```
void Update() {
  angle += Time.deltaTime * angularSpeed; // update angle
  Vector3 direction = Quaternion.AngleAxis(angle, Vector3.forward) * Vector3.up; // calculate direction from center - rotate the up vector Angle degrees clockwise
  transform.position = center + direction * radius; // update position based on center, the direction, and the radius (which is a constant)
}

```

You could apply the same method and use the sin/cos if you prefer (find the position using sin/cos based on the angle, but don't use the previous position as an input). Personally I find the method above more intuitive.
> 1 votes

---
Tags: unity, c#, linear-algebra
---


# Question
Title: Persisting Player Prefs On Build in Android
Can I ask for help/guide where I can build 2d game on android device includes the players prefs that I defined already, for example I have an "int" PlayerPrefs (PlayerPrefs.Getint ("mysavenumber")),

the data "mysavenumber" has already a saved integer value in it. How ever upon building my game and installing it on my android device it seems does not hold any value.

How can I build my game with the Playerprefs data that I have defined upon building and installing it on an android device?

# Answer
PlayerPrefs are stored locally on the device, they are not part of your app so they will not be set when you install it.

You have two options:

1. Pass a default value to `PlayerPrefs.GetInt(string name, int defaultValue)`, that will be the value that you want to set when you install. Unity will automatically use that value if you haven't called `PlayerPrefs.SetInt()` for that value yet.
2. When you first run the game, go over all the values you wanted and set them to the pre-defined values that you want. This has the benefit of having all the default values in a single place instead of spread around the code whenever you call GetInt(). You can save another player pref called "default-set" and use it to make sure you only initialize the default values once, otherwise you will overwrite any changes that the player makes.
> 1 votes

# Answer
You can just create a game object and add a script to it and on the `Start()` method just call the `PlayerPrefs` and set the values you want. Now keep in mind that `PlayerPrefs` are only 1 megabyte of free local storage that you get. Thats why its called `PlayerPrefs`, its the preferences of the player, like sound settings, music settings, etc. Things that are usually small to store.

You can also just create a json file into the build with classes and the values you want to save and read and write to that json file the values you want. Or like the YouTuber Brackeys did with saving and loading game. Here is the video: https://www.youtube.com/watch?v=XOjd\_qU2Ido
> 0 votes

---
Tags: unity
---


title: libGDX imagebutton seeing double

text:
# Question
Title: libGDX imagebutton seeing double
If I leave my imagebuttons' width and height alone I get larger buttons than I'd like:

```
    radio.setX(wu*35);
    radio.setY(hu*20);

```

When I replace/add to the lines above with setbounds or setWidth/setHeight functions, I get this:

```
    radio.setBounds(wu * 35, hu*20, wu * 12, hu * 12);

```

It did get smaller, but now it appears to be two images. What is going on? I always run into this issue, across multiple screens and projects. My attempts to resolve it include scaling the native images to be closer to the size I want them to appear in-game, and using the other button methods that deal with sizing, such as setScaleX.

# Answer
> 0 votes
After running this problem by the libGDX forum, the prevailing wisdom is that widgets were meant to be used inside tables. While I like the built-in functions provided by the button class, such as swapping out the images used on mouseover, mousedown, disabled, etc. events, I think I can duplicate this feature with the right listener and an Image actor.

---
Tags: libgdx, gui
---


# Question
Title: Unity error: type "x" exist in both 'A' and 'B'
I just opened a project made in unity version 2018.1.1f into Unity version 2020.1.1f I know opening the older projects is not supported by Unity but it opened fine.

The only problem is that it is giving an error which looks like this-

What I tried:

1. checking the script `onetizationPlatform.cs` to ensure nothing is wrong in it
2. checked that there's no two files with same name `unitylifecyclemanager`
3. doing point 2 with `unityengine.advertisement.editor`
4. deleting `unityengine.advertisement.editor` which caused another error so I had to restore it back

# Answer
I fixed the problem by first removing unity advertisements from package manager and then deleting every single advertisement or monetization related file from my project

After that I reinstalled unity advertisement from package manager which first gave 2-3 errors which were clearable and then everything started working nicely.
> 1 votes

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


# Question
Title: Slicing irregular spritesheet (automatically?)
If found a cool sprite sheet on the internet but its irregular.

Is there any way besides manually cutting sprites to extract the separate pngs? I need to pack them then again into the Texture Atlas under proper names.

Maybe theres some smart online tool that uses deep learning or something like that?

# Answer
> 2 votes
There is the way, which is partially automated:

1. Open sprite sheet with Photoshop
2. Using the slice tool make one big slice that'll contain the entire image
3. Right-click it and split this slice into a grid (it's 32x32 pix I presume)
4. Join small slices into a bigger one (this have to be done by hand) where needed
5. Export every slice as a separate file using File -\> Export As...

There are also online editors which allow you to do the same, like Photopea, but I'm afraid it can't slice image automatically. However, you can go to Edit -\> Preferences... menu and make yourself a 32x32 pix guide-grid. Then you'll have to slice image manually, but it will be easier since each of slice rect borders will snap to grid lines.

# Answer
> 3 votes
Since you found the picture online, without any `json` file attached or any other information, its not possible to cut this into multiple sprites automatically. You'd have to do it by hand.

# Answer
> 2 votes
You can use Leshy's tools to split non uniform spritesheets: https://www.leshylabs.com/apps/sstool/

Your spritesheet is 32x32. I've used it before:

---
Tags: sprites, spritesheet, texture-atlas
---


# Question
Title: Best practice for giving properties to game objects
I'm not a noob in Unity although not the most experienced one, but during one of my project a noob question came to my mind! Strange but this never was an issue for me during my old projects... I became confused where should I initialize the basic properties of my agents.

Example: I have some workers (agents) in a strategy game and they can extract resources. For this I can create a script which executes the process; also I need a variable which define the maximum amount of collected resource the agent can carry. Normally I would create this property in the "Extracting" script which is fine, but should I really create different scripts for (almost) every property of an agent?

There's some properties which are very general like "HP" for example... the HP can be used in many scripts and has no proper script to define/initialize it, but there's ton of other examples...

My idea to organize this thing to create a 'Property' script where I would write all of the properties which need for the given agent type. But in this case I have to connect the script to other ones which would use any property of this agent (by `GetComponent<>`)

Under the hood a GameObject is a class right? There's any way to add some variable (for properties) to the specified GameObject and access these variables from any scripts of which is attached to that GameObject?

What is the proper way to do this?

# Answer
> 5 votes
For HP, I'd recommend creating a `Health` component, something like this...

```
public class Health : MonoBehaviour {

    public float maxHP = 100;

    public UnityEvent OnDeath;

    float _currentHP;

    void Start() {
        _currentHP = maxHP;
    }

    public void TakeDamage(float damage) {
        if (_currentHP <= 0f) return;

        _currentHP -= damage;
        if (_currentHP > 0f) return;

        _currentHP = 0f;
        if (OnDeath != null) OnDeath.Invoke();

        Destroy(gameObject);
    }
}

```

Now you can add a `Health` component to anything that needs to be able to take damage: characters, breakable objects, etc.

Any script that needs to interact with the Health component on itself or on a target it's damaging / healing can do so with `GetComponent<Health>()`

Now you don't need to re-invent the wheel for each one - you can share one common implementation of HP-tracking and death-invoking across everything that needs it, and make new damageable or invulnerable entities and variants as simply as adding or removing a `Health` component from them.

You can follow this pattern for each identifiable function your agents need. Some agents extract resources? Put the properties they need in a `ResourceExtractor` component. Some agents can attack? Put the properties they need in an `Attack` component. etc.

This is an approach called Composition Over Inheritance - instead of stacking all possible behaviours we might need on the parent GameObject, we import just the ones we care about for a given entity by attaching the right combination of components to it.

---

For properties that are the same for a large number of objects (like max HP or max carrying capacity, not current HP/current load which can vary for each instance), you can use the flyweight pattern or type object pattern to store them in a common object, something like...

```
[CreateAssetMenu(fileName = "newAgentProperties.asset", menuName = "Properties/Agent Properties")]
public class AgentProperties : ScriptableObject {

    public float movementSpeed;
    public float carryingCapacity;
    // ... etc.
}

```

Then your agent script can simply store a reference to these shared properties:

```
public class Agent : MonoBehaviour {

    public AgentProperties properties;

    // ... Add per-instance properties and actions here.
}

```

# Answer
> 0 votes
You could declare a public string, which will be the identifier, and make the specific workers have different roles, depending on the string’s value. For example, something like this:

```
public string Job;

void MineStone()
{
   if (Job == miner)
   {
       // mine function goes here
   }
}

```

# Answer
> 0 votes
No, you can't extend GameObject to add more variables to it (The Unreal Engine works like that, by the way, but Unity doesn't). Properties of a gameObject belong to the component (aka MonoBehaviour) where they make the most sense thematically and technically.

So a property like `HP` belongs into the Component which handles reacting to damage and destroying the object. You can then add that component to any object which is supposed to be destructible. When a script now needs to know if the object it is on is damaged, then it would do so by accessing the Health component via GetComponent.

When you develop a MonoBehavior which only works when a different component is also on the same gameObject, then you can declare that through the RequireComponent attribute. That way the Unity editor will automatically add required components for you and warn you when they go missing.

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


# Question
Title: What is the standard practice for animating motion -- move character or not move character?
I've downloaded a bunch of (free) 3d warriors with animations. I've noticed for about 25% of them, the 'run' animation *physically moves the character forward in the z direction*. For the other 75%, the animation just loops with the characters feet moving etc., but does so in place, without changing the character's physical location.

I could fix this by:
1.) Manually updating the transform in code for this 75%, to physically move the character
2.) Alter the animation by re-recording it, with a positive z value at the end (when I did this it caused the character to shift really far away the rest of the units, probably something to do with local space vs world space I haven't figured out yet).

But before I go too far down this rabbit hole, I wonder if there is any kind of standard? In the general case, are 'run' / 'walk' animations *supposed* to move the character themselves, or is it up to the coder to manually update the transform while the legs move and arms swing in place? Is one approach objectively better than the other, or maybe it depends on the use case? If so, what are the drawbacks of each? I know nothing about animation, so I don't want to break convention (if there is one).

# Answer
Animations in which the character translates away from the origin are said to contain **"Root Motion"** \- because the root bone moves.

This allows the animator to directly author subtle non-uniformities in the movement speed, in a "what you see is what you get" fashion. Say the character slows down slightly as their foot makes contact with the ground, then speeds back up as they push off again. Incorporating this via the movement script would be messy and error-prone.

By allowing this root motion to drive the movement of the game entity, we get a very close match between what the animator authored and what the player sees - minimizing mismatch errors like foot sliding.

But it can also make it more difficult to change and direct that motion at runtime. Your animations might cover a walk of 1.4 m/s and a run of 2.2 m/s, but if the player's input maps to a movement of 1.7 m/s the two might not blend cleanly to make this intermediate speed. Or if the only turning animations you have are 45 degree turns, then the player character ends up walking in a half-circle in order to turn around.

That makes root motion useful for naturalistic motion and performance capture, where you want all the little inconsistencies of a real creature's movements incorporated in the final result, and you're willing to sacrifice some amount of runtime control to make it happen. Cutscenes or special actions that happen with some fixed alignment (like interactions with cover) will often use this style extensively.

---

Animations where the character does not translate away are called **"In-Place"** \- because the character stays in one place, like walking on a treadmill.

This makes it easier to blend and transition the animation with other animations the character can do, because they're all aligned at the same position/orientation.

The way the character moves through the scene is entirely up to the movement scripts, giving the programmer and game designer a lot of freedom to control the movement, pivoting to just the right angle or dialing the speed up and down. This can also make it easier to layer the animation with procedural motions like a jump that snaps to a target point, a rail/ledge to follow, or a moving object to ride.

The downside is that the scripted motion layered on top can look mechanical, and disconnected from the movement of the character's limbs. Seeing feet that appear to slide or swim across the ground, rather than making stationary contact and convincingly propelling the character, is a common artifact of this approach.

Some of this can be ameliorated by using IK (Inverse Kinematics) to nudge limbs to match their intended contact points. Or it might not be a big deal at all if you're animating something non-naturalistic, like a stylized cartoon character or a hovering sci-fi object or otherworldly alien creature. Or if your viewpoint is far enough away that those little misalignments don't really show, like in a city builder/god game/RTS.

---

So both approaches have their benefits and drawbacks, and as a result they're both used - often even in the same game, for different actions or at different stages of production.

Fortunately, Unity gives you powerful tools to decide how you want to use root motion, allowing you to use it to drive a body's movement through the scene, or bake it out if you want to work with it as an in-place animation. So you can change your mind easily as you iterate on your project and find what works best for getting you the results you need, and the way your team likes to work.
> 46 votes

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


# Question
Title: How can I avoid coupling between units and their environment?
Currently in the process of making a game like Dwarf Fortress, so without graphics. I'm mostly thinking about how I want to implement everything. While writing code I keep stumbling on general game implementation problems that are really annoying me. Assume this:

We have a `Map` class which stores `Chunk` classes which stores `Tile` classes which stores `Player`s and `Enemy`s currently on this tile.

```
class Map {
    public:
        std::vector<std::vector<Chunk>> chunks;
};

class Chunk {
    public:
        std::vector<std::vector<Tile>> tiles;
        std::vector<Player*> player_need_update;
        std::vector<Enemy*> needs_update;
};

class Tile {
    public:
        std::vector<Player*> players;
        std::vector<Enemy*> enemies;
};

```

Now let's say I want to `move()` a player to a different `Tile`. For this I created a `needs_update` vector storing entities that need to be updated on the game `Map`. Every game tick we loop all chunks and loop all entities needing an update.

I think (thought) this is a logical way of doing this because we can have a tile that is independent of a chunk that is independent of a map. Same for entities. So let's say we want to move an `Entity`:

```
void Entity::move(uint16_t move_x, uint16_t move_y) {
    x += move_x;
    y += move_y;

    changed() // Notify chunk that something changed about us
}

```

This is already where it is going wrong. To be able to notify the chunk we have moved, we need to know ourselves in which chunk we are `Chunk *in_chunk;` in class `Entity`. And this breaks the structure I wanted to achieve (independence across classes).

Another example, suppose we want to attack an `Entity` on a different `Tile`. We would need to know there is an entity in the first place, but we would also need to know things about the enemy to then decide whether to attack it or not.

```
Player::attack(Enemy &enemy /* ?? */) {
    // Attack
}

```

I think it is wrong to move a player by calling a function in `Map`:

```
void Map::movePlayer(Player &player) {
    // Do stuff to move player
}

```

So, how do you implement basic game structures like this, keeping things logically structured but while still being able to ie. move a player across the map?

# Answer
The target implementation of your Map and entities is very much like a graph, or, more specifically, a tree:

Since the goal is to minimize references to parent nodes, **we will call update methods from parents, as well as have parents pass data to those children that is necessary for them to update.**

Since entities need to be able to move throughout the tree, it's inevitable that we will need some sort of function in the `Map` and `Chunk` to be able to move entities to different nodes. **However, we can separate updating the graph from updating the state of the entities, which will keep them from storing references to one another.**

## Updating the Map Graph

Since your `Entity::move` method adjusts fields for `x` and `y`, it seems that you already locally store the coordinates of your entities. Thus, you have enough information to know when to delete references to entities in your Chunks and Tiles; specifically, when their coordinates are no longer within the bounds of that Chunk or Tile.

For example, in your Tile class (I'm doing this in Javaish-pseudocode since I'm clueless with C++ and don't want to cause confusion):

```
for(Player player in players) {
    if(player.coordinates != this.coordinates) {
        player.needsMove = true;
        /*Remove reference to player from vector*/;
    }
}

```

Then, in your Chunk class:

```
for(Player player in player_need_update) {
    if(player.needsMove) {
        if(inThisChunk(player.coordinates)) {
            /*Add a reference to this player in the appropriate Tile in this Chunk*/;
            player.needsMove = false;
        }
    }
}

```

And you'd have to do the same in your Map class if entities can move between Chunks.

## Detection Among Entities

A similar approach could help the entities detect one another. For example, take the case of Players attacking Enemies. If a Player can only attack Enemies within the same Chunk, then we could do something like this in the Chunk class:

```
for(Player player in player_need_update) {
    for(Enemy enemy in enemies) {
        if(player.shouldAttack(enemy)) {
            player.attack(enemy);
        }
    }
}

```

From there, calls to `Player::attack()` can be passed references to enemies without storing them for long-term use.
> 1 votes

---
Tags: c++, tilemap, software-engineering
---


# Question
Title: How do I make night cycle like Dino Chrome?
I want to add a day/night system cycling to my runner game like the game Dino Chrome. The condition is when the score reaches `100` it will be `night` then when it reaches `100` again will be `day`.

I tried with this code but nothing changed in my game:

```
if (_GameManager.instance.score % 100 == 0)
{
     fadeToBlack = !fadeFromBlack;

     if (fadeToBlack)
     {
          cam.backgroundColor = new Color(Mathf.MoveTowards(cam.backgroundColor.r, 1f, fadeSpeed * Time.deltaTime),
                                          Mathf.MoveTowards(cam.backgroundColor.g, 1f, fadeSpeed * Time.deltaTime),
                                          Mathf.MoveTowards(cam.backgroundColor.b, 1f, fadeSpeed * Time.deltaTime),
                                          cam.backgroundColor.a);
     }

     if (fadeFromBlack)
     {
          cam.backgroundColor = new Color(Mathf.MoveTowards(cam.backgroundColor.r, 255f, fadeSpeed * Time.deltaTime),
                                          Mathf.MoveTowards(cam.backgroundColor.g, 255f, fadeSpeed * Time.deltaTime),
                                          Mathf.MoveTowards(cam.backgroundColor.b, 255f, fadeSpeed * Time.deltaTime),
                                          cam.backgroundColor.a);
     }
}

```

Eventually I want to change all game object colors via script with smooth, but for now I just want to apply a change to the camera background.

and this is my whole script

    public static _ObstacleManager instance;

    private void Awake()
    {
        instance = this;
    }

    public float maxTime;
    float timer;

    [Header("CommongObstacle")]
    public GameObject[] Obstacles;

    [Header("BirdObstacle")]
    public GameObject[] buwungObstacle;

    [Header("MeteorObstacle")]
    public GameObject Meteor;
    public Transform[] spawnpoint;

    int choosedSpawnMeteor;
    int choosedObstacle;

    [Header("NightCycle")]
    public float fadeSpeed = 2f;
    public bool fadeToBlack, fadeFromBlack;
    public Camera cam;

    // Start is called before the first frame update
    void Start()
    {
        cam = GetComponent<Camera>();
    }

    // Update is called once per frame
    void Update()
    {
        if (_GameManager.instance.isStarted)
        {
            timer += Time.deltaTime;

            if (timer >= maxTime)
            {
                GenerateObstacle();

                if (_GameManager.instance.score >= 400)
                {
                    GenerateBuwungObstacle();
                }

                timer = 0;
            }

            if (_GameManager.instance.score % 100 == 0 && activeFade == null)
            {
                fadeToBlack = !fadeToBlack;

                Color color = fadeToBlack ? Color.black : Color.white;

                activeFade = StartCoroutine(FadeTo(color));
            }
        }
    }

    //kelipatan 200
    public void GeneratedMeteorObs()
    {
        choosedSpawnMeteor = Random.Range(0, spawnpoint.Length);
        GameObject meteorGo = Instantiate(Meteor, spawnpoint[choosedSpawnMeteor].position, Quaternion.identity);
    }

    public void GenerateObstacle()
    {
        choosedObstacle = Random.Range(0, Obstacles.Length);
        GameObject obstacle = Instantiate(Obstacles[choosedObstacle]);
    }

    public void GenerateBuwungObstacle()
    {
        choosedObstacle = Random.Range(0, buwungObstacle.Length);
        GameObject obstacle = Instantiate(buwungObstacle[choosedObstacle]);
    }

    // Store the fade in progress (so we don't accidentally double-start it)
    Coroutine activeFade;

    // Perform a fade over time, then clear the activeFade variable when done.
    IEnumerator FadeTo(Color destination)
    {
        Color start = cam.backgroundColor;

        for (float t = 0; t < 1f; t += Time.deltaTime / fadeSpeed)
        {
            cam.backgroundColor = Color.Lerp(start, destination, t);
            yield return null;
        }

        cam.backgroundColor = destination;
        activeFade = null;
    }

```
</code></pre>

# Answer
There are a few mistakes in this code.

You've taken the code that *performs* the colour transition, and nested it inside the conditional block that *triggers* the colour transition.

That means each time you hit a multiple of 100, you update the background colour for one single frame, then leave it constant until the next multiple of 100. Then you update the background colour in the opposite direction for one single frame.

You might be under the mistaken impression that `Mathf.MoveTowards()` kicks off a tween that runs independently in the background. It can't do that, because it doesn't take and hold a reference to the variable you'd want the tween to update next frame. It's just a math function that takes some numbers and returns a number - assigning its output to your desired variable each frame is your job.

You can also make this code much simpler by using `Color.Lerp`. Here's a corrected version:

```
// Store the fade in progress (so we don't accidentally double-start it)
Coroutine activeFade;

// Perform a fade over time, then clear the activeFade variable when done.
IEnumerator FadeTo(Color destination) {
    Color start = cam.backgroundColor;

    for (float t = 0; t < 1f; t += Time.deltaTime / fadeDuration) {
        cam.backgroundColor = Color.Lerp(start, destination, t);
        yield return null;
    }

    cam.backgroundColor = destination;
    activeFade = null;
}

// Check for the trigger to start a new fade, and start it.
void Update() {
    if ((_GameManager.instance.score % 100) == 0 && activeFade == null) {
        fadeToBlack = !fadeToBlack;

        Color color = fadeToBlack ? Color.Black : Color.White;

        activeFade = StartCoroutine(FadeTo(color));
    }
}

```
> 2 votes

---
Tags: unity
---


# Question
Title: How to restrict movement of Leap Motion hand object
I have a "Hand" GameObject controlled by a Leap Motion Controller. The Hand despite having RigidBody and Box Collider just seemingly moves with no regards to physics (transform translate movement I suppose). So it clips through other Rigidbody objects.

I'm trying to pseudo-introduce physics to it. I created a second GameObject "HandClone" (with Rigidbody and Box Collider) that copies the first `Hand` position but moves with actual physics. HandClone script:

```
   private void FixedUpdate()
    {
        rb.MovePosition(targetTransform.position);
        rb.MoveRotation(targetTransform.rotation);
    }

```

Now HandClone goes where Hand goes, and HandClone is successfully bumping into other objects.

However, when HandClone gets stopped by something, `Hand` still keeps moving past HandClone and clips into the other objects, like before.

Now I am thinking that the way to solve this is to constrict `Hand`'s movements to the bounds of `HandClone` so that finally `Hand` will stop clipping through objects. But how can this be achieved, would that even work, and is there a better way? Will movement streamed from Leap Motion Controller even respond to scripts like that?

\__

Edit: I've now decided to hide Hand and place HandClone where Hand was.

But my script for HandClone to copy Hand's movements is making HandClone fly all over the place. Here's the script:

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

public class clone1 : MonoBehaviour
{
    private Rigidbody rb;
    public GameObject target;
    void Start()
    {
        rb = this.GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {

    }
    private void FixedUpdate()
    {
        Vector3 newRotation = new Vector3(target.transform.eulerAngles.x + 8.5f, target.transform.eulerAngles.y - 172.78f, target.transform.eulerAngles.z - 94.02f);
        rb.MoveRotation(Quaternion.Euler(newRotation));
    }
}

```

The reason why I am adding those float numbers is because when the game isn't playing, those numbers are what make HandClone sit in the correct position, so I thought it would help with alignment in playmode. But HandClone is just flying everywhere regardless. Any advice with making the HandClone stay attached to the avatar's wrist would help.

# Answer
> 0 votes
Constraining one gameobject within another is easy - add a collider to it. Or in your case if you have two hands, simply reset the position of the second original object to be the same as the second object - the one with the colliders.

However, your problem sounds a bit more related to Leap Motion and its design best practices, and not general unity. For that it seems that Leap Motion have a ready asset called RigidHand, which should deal with all the physics for you.

---
Tags: unity
---


# Question
Title: Why do Dynamic Bones disconnect natural flow if they have ANY child gameobjects?
I've been having an issue for months now where if I have a dynamic bone chain that splits off in any way (ie. any of the chain's bones have child gameobjects), then the flow of the dynamic bone chain becomes completely disconnected and seems to do something akin to ignoring weight painting. This is hard to explain through text, so I've linked images of before and after I added a child gameobject to one of the bones in a dynamic bone chain.

Behavior **without** gameobject interrupting Dynamic Bone Chain:

Behavior **WITH** gameobject under one bone in the Dynamic Bone Chain:

This is the block of settings I have available to edit with my existing Dynamic Bone script:

This model is intended to be imported as a functional "Hand Puppet" avatar into VRchat, therefore any major project-side changes to the Unity physics engine will not be carried over in-game. VRchat has blacklisted most scripts for their game with the exceptions of Rigidbodies/Fixed Joints, Constraints, Dynamic Bones, Audio Sources, and some limited functions of Final IK.

As a brief explanation, the reason there are two white lines signifying Dynamic Bone behavior in my screenshots is that I have applied Dynamic Bone roots to two bones on the model's skeleton so that their behavior compounds to create a more fluid and natural motion (at the cost of some performance). My posted concern occurs no matter how many/few dynamic bone components are applied as long as there is at least one component on the chain.

I'm using Unity 2018.4.20f1.

I have tried countless methods involving constraints, Blender work, revised armatures, updating dynamic bones, etc, but this issue persists no matter what.

How can I fix this problem?

# Answer
So I believe the problem here is an interesting form of the age old mass-ratio constraint problem. I’ll explain the high level.

**The why:**

So Unity’s default MLCP solver is commonly referred to as PGS for short. In this (and any) physics solver, a constraint between two objects uses the mass and inertia tensor (referred to as mass properties) of both objects as inputs to determine the impulse required to move both objects such that the constraint’s conditions are satisfied.

In the case of the constraints you’re using, the condition they are satisfying is a fixed distance between the two objects, meaning that the solver will apply corrective impulses every frame, on every constraint, for a set amount of iterations. The amount of iterations the solver uses to attempt to converge on a solution is just an estimate, which means that there can be situations in which the constraint will diverge, especially if a large mass is being carried by a series of smaller masses (i.e. wrecking ball on a chain). The constraints between the smaller masses have no knowledge of the larger mass way at the end of the chain, so they cannot adequately compensate for the effective mass of the large object on the end. I believe a similar situation is occurring here.

**TL;DR** I believe that the mass of your new child object is not accounted for by the constraints which bind the parent object to the rest of the body, making those constraints unable to converge on a solution. If that is the case, I think there are a few ways to fix this. First, being to disable physics on the child object while it is parented. If not that, you could try making the mass of the child extremely small and removing linear drag from the child as well. It may take a bit parameter tuning and testing to achieve an acceptable solution, and this is a very common practice.

That’s my best guess from the limited information in the question

**Edit**: Other tests/solutions could include parenting the child object to the leading object in this chain. If this fixes the problem, then I would consider my theory correct. Another route would be to try significantly raising the masses of every object in the chain such that the mass of the new child object is negligible in comparison to any segment, though, this may introduce other undesirable behavior as the entire object would have significantly more momentum.

Another similar (albeit far less likely) theory to explain your problem would be that the engine decided to recalculate the polyhedral mass properties when the child was parented to your object, including mass, center of mass and inertia tensor. That would effectively make that segment a compound collider. The shift in center of mass plus the mass ratio problem could explain the behavior. This would be a bit more difficult to fix and diagnose, though. If that was the case, you may need to manually modify those mass properties when parenting and unparenting so that it appears to the physics engine as if nothing has changed.
> 1 votes

---
Tags: unity, models, debugging
---


title: How to use a mask texture with Kobold2D

text:
# Question
Title: How to use a mask texture with Kobold2D
I am an iOS developer but I'm new to cocos2d. I'm working on new game, I use Kobold2D, have cocos2d installed too, and I want to make this effect:

I know how is done with Flash, but can't make it with Kobold2D. There's 2 images with the same size: one is a low-res image for the background and the second is a hi-res over the first one. When the "reticle" mask moves, it reveals the second image inside the circle and the background is visible outside only. I googled with no success, saw some Ray Wenderlich projects they weren't helpful.

# Answer
1. First draw the mask sprite, with the src color (the mask) set to GL\_ONE and the destination color (an empty buffer) to GL\_ZERO.
2. Draw the sprite, with the src color set to GL\_DST\_ALPHA.
3. Call the CCRenderTexture (renders the masked sprite)
4. Open up HelloWorldLayer.m and add the following method right above init:

```
- (CCSprite *)maskedSpriteWithSprite:(CCSprite *)textureSprite maskSprite:(CCSprite *)maskSprite {

    // 1
    CCRenderTexture * rt = [CCRenderTexture renderTextureWithWidth:maskSprite.contentSizeInPixels.width height:maskSprite.contentSizeInPixels.height];

    // 2
    maskSprite.position = ccp(maskSprite.contentSize.width/2, maskSprite.contentSize.height/2);
    textureSprite.position = ccp(textureSprite.contentSize.width/2, textureSprite.contentSize.height/2);

    // 3
    [maskSprite setBlendFunc:(ccBlendFunc){GL_ONE, GL_ZERO}];
    [textureSprite setBlendFunc:(ccBlendFunc){GL_DST_ALPHA, GL_ZERO}];

    // 4
    [rt begin];
    [maskSprite visit];
    [textureSprite visit];
    [rt end];

    // 5
    CCSprite *retval = [CCSprite spriteWithTexture:rt.sprite.texture];
    retval.flipY = YES;
    return retval;

}

```
5. Replace the area between BEGINTEMP and ENDTEMP with the following:

```
CCSprite * mask = [CCSprite spriteWithFile:@"SpriteToUse.png"];
CCSprite * maskedCal = [self maskedSpriteWithSprite:cal maskSprite:mask];
maskedCal.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:maskedCal];

```

I found these instructions from here: How to Mask a Sprite with Cocos2D
> 1 votes

---
Tags: rendering, cocos2d, masking
---


# Question
Title: Render only a cross-section of a 3D scene in Godot
I'm working on a 3D game where I sometimes want to display only a cross-section of the scene. Ideally I would like this to be just the intersections of the scene with a plane. But the only way I've been able to achieve this so far is by setting the near and far culling planes to be very close together. However, there are two problems with this approach:

1. The result isn't actually 2D, the cross-sections have the thickness the size of the gap between the culling planes (this isn't a huge deal, but would be nice to fix)
2. Most objects become quasi-outlines since their fronts and backs are now culled by the camera. I at least want this to be filled in (e.g. for a sphere I want a solid circle instead of just an outline).

Is there a way to make a very small gap between the near and far culling planes but filling in the interior of the objects, or is there another way to achieve this plane-intersection effect?

# Answer
> 1 votes
Yes, I think there are a few ways you could do this

To start, to address your depth problem, you’ll want to use an Isometric Projection matrix, instead of the typical Perspective Projection matrix (which creates that frustum). Pretty straight forward, for the most part. Makes a cube look like a square when looking directly at any face head-on. I recommend taking a peek at this wikipedia article to see what other options are out there.

As for the cross section, there are a few options. I’m not great with graphics, but I do know about the OpenGL discard statement which would allow you to simply check the depth before rendering the fragment, however you will incur a notable performance hit by calling discard. According to this question you could simply adjust the projection matrix far plane every time the fragment is above whatever depth you designate.

Apart from all that shader stuff, if you’re just looking for a way to slice all of your meshes with a plane, i would be remiss to not mention the Sutherland-Hodgman Clipping Algorithm. It achieves precisely what you described, and it is still used in certain contexts today because it’s quick, it preserves shapes and winding order, and it’s very simple to implement and understand. If you google it, there’s lots of examples and youtube videos.

---
Tags: 3d, godot, clipping
---


title: Keep the prefab connection with FBX

text:
# Question
Title: Keep the prefab connection with FBX
The steps I have gone through:

1. Added an **FBX** in UnityProject.
2. **FBX** added to scene hierarchy.
3. Made **Prefab** by dragging the **FBX** into my assets.

Note that now the model became a prefab in my hierarchy. Then I added a script to the **prefab** and assigned some objects and methods to such script.

My problem is that when I import the new FBX in the project my scene object doesn't update as it's linked to the **prefab** which doesn't *see* the updated **FBX**.

Is it possible to update my prefab with the latest FBX so I don't have to rebuild the prefab and reassign all scripts every time?

# Answer
The way I do it is outside Unity. I use the operating system's file explorer to overwrite the FBX file with the new version, then I go back to Unity, which should keep all prefabs that wrap the model intact. I find this to be the most consistent way.

Alternatively you can import the new FBX and edit your prefab to add it in there and get rid of the previous model but if this works or not depends on how you set things up in your prefab.
> 2 votes

# Answer
You can try this.

1. Drag the prefab into the scene hierarchy.
2. Update the prefab by adding the new FBX.
3. Apply the changes to your prefab from the inspector window.
> 1 votes

---
Tags: unity, fbx, import
---


title: How to delete Google Play Services?

text:
# Question
Title: How to delete Google Play Services?
I want to delete Google Play Services in the Google Play Developer Console, but I can't. Here is what I did:

1. I published my game to Google Play without Google Play Services.

2. I decided that I want Google Play Services in my game, so I integrated them in the source code.
3. After that I created Google Play Services for my game in the Google Play Developer Console.

4. But the created Google Play Services didn't work. The were Unpublished at that moment. I read that in order for them to work, you have to publish them. I published them, they still don't work and I can't delete them. In order to delete them I must unlink the game, but since the game is published I can't unlink it. I asked Google Support what to do, they told me to delete the project in the Google API Console and after 7 days the game will be unlinked. There has been 15 days since then and nothing happens. Please tell me what can I do.

# Answer
*Here are the instructions on how to delete a project:*

1. Sign in to your Google Play Developer Console.
2. Click Game Services.
3. Select the project.
4. At the bottom of the Game Details page, click the link to go to the **API Console Project.**
5. In the API Console Project, on the left menu, click **APIs & Auth \> Credentials**.
6. Under **"Client ID for Android application"**, click Delete.
7. On the left menu, click Projects.
8. Click Billing & settings.
9. Click Delete project.

To confirm that your project has been deleted, go back to your Google Play Developer Console and click Games services Game Services.

I found that from this link.
> 1 votes

---
Tags: android, google-play-services, google-play
---


title: Draw Edges in OpenGL

text:
# Question
Title: Draw Edges in OpenGL
I use blender game engine and blender uses OpenGL for graphics. How can I draw lines around all 3D objects? Would this be a job for a filter? Mainly, I want my end result to look drawn.

I found this:

```
uniform sampler2D bgl_RenderedTexture;
uniform sampler2D bgl_DepthTexture;

void main()
{
   float depth = texture2D( bgl_DepthTexture, gl_TexCoord[0].xy).r;
   float depth2 = texture2D( bgl_DepthTexture, gl_TexCoord[0].xy + vec2(0,0.002)).r;
   float depth3 = texture2D( bgl_DepthTexture, gl_TexCoord[0].xy + vec2(0.002,0)).r;

   float fac = abs(depth-depth2) + abs(depth-depth3);

   float intensity = 9050;

   vec4 sub = vec4(fac*intensity,fac*intensity,fac*intensity,0);

   gl_FragColor = texture2D( bgl_RenderedTexture, gl_TexCoord[0].xy ) - sub;
}

#change float intensity

```

here and that seems to work, but I need it to look more sketched. So I would like some noise influence. Maybe it's called sinus displacement? Is there a way to do that?

I draw and I want the style to look like this. Thanks.

*Disclaimer:* I do hang out on BSE and this is not a question they are prepared to answer or is it necessarily on-topic for them, since it is about OpenGL.

# Answer
> 0 votes
Here's some code that hopefully gives you the effect you are looking for. It works similar to your original code, but has some added code to help get a brighter pop.

```
uniform sampler2D bgl_RenderedTexture;
uniform sampler2D bgl_DepthTexture;
uniform vec2 bgl_TextureCoordinateOffset[9];

const float near = 0.1;
const float far = 100.0;

float depth(in vec2 coo)
{
 vec4 depth =  texture2D(bgl_DepthTexture, coo);
 return -near / (-1.0+float(depth) * ((far-near)/far));
}

void main(void)
{

    vec4 sample[9];
    vec4 border;
    vec4 texcol = texture2D(bgl_RenderedTexture, gl_TexCoord[0].st);

    for (int i = 0; i < 9; i++)
    {
        sample[i] = vec4(depth(gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]));
    }

    vec4 horizEdge = sample[2] + sample[5] + sample[8] -
                     (sample[0] + sample[3] + sample[6]);

    vec4 vertEdge = sample[0] + sample[1] + sample[2] -
                    (sample[6] + sample[7] + sample[8]);

    border.rgb = sqrt((horizEdge.rgb * horizEdge.rgb) +
                            (vertEdge.rgb * vertEdge.rgb));

       if (border.r > 0.8||border.g > 0.8||border.b > 0.8){
        gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
    }else{
  gl_FragColor.rgb = texcol.rgb;
        gl_FragColor.a = 1.0;
    }
}

```

---
Tags: opengl, shaders, blender-game-engine, filtering
---


# Question
Title: set model to transparent where texture is transparent
I finally got around to applying textures to my game, and I noticed that the areas that are transparent on the .png of the texture are not transparent on the actual model.It is illustrated in the image below.

I want the areas of the model that are supposed to be transparent to be transparent. The white areas are the areas that should be transparent. the white areas are transparent on the actual .png. Is there any way to do this using glfw? Is there some sort of transparency function GLFW has? I thought changing `RGB` to `RGBA` on the texture generator would fix it but it did not. `glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);` The data for the actual model is below (its formatted in json but still shows the vertices). The first 3 entries on each row are the coordinates, then 3 entries for the color, then the texture mapping.

```
{"vertices":[
0.00,0.00,0.0,0.0,0.0,0.0,0.0,0.0,
500.00,0.00,0.0,0.0,0.0,0.0,1.0,0.0,
500.00,500.00,0.0,0.0,0.0,0.0,1.0,1.0,
0.00,500.00,0.0,0.0,0.0,0.0,0.0,1.0

],
"indices":[
0,1,2,
0,3,2
],

"texturePath": "textures/planet1.png"}

```

Do I have to map the coordinates of the texture to a circular object rather than a square one like it is formatted now. I am hoping I don't, because that would make my life so much simpler.

# Answer
> 0 votes
I figured it out using this lovely tutorial.

I changed my fragment shader from this:

```
out vec4 FragColor;

in vec3 ourColor;
in vec2 TexCoord;

uniform sampler2D ourTexture;

void main()
{
    FragColor = texture(ourTexture, TexCoord);
}

```

to this:

```
out vec4 FragColor;

in vec3 ourColor;
in vec2 TexCoord;

uniform sampler2D ourTexture;

void main()
{
    vec4 texColor = texture(ourTexture, TexCoord);
    if(texColor.a < 0.1)
        discard;
    FragColor = texColor;
}

```

I never told the shader to ignore the transparent areas of the model in the first place.

---
Tags: opengl, textures, glfw
---


# Question
Title: Why is Cinemachine Virtual Camera locking my camera position to the Origin?
I want the camera to follow a character as he moves around. So I did the following:

* Position the camera behind and slightly above the character.
* Add a Cinemachine Brain component to the camera.
* Create a GameObject containing a Cinemachine Virtual Camera component. Set its LookAt and Follow properties to the character to be followed.
* Run the game.

I expect for the camera to follow the character, more or less maintaining the relative position and orientation I had set for it. (ie. more or less as if the camera object was parented to it, but smoother.)

If I use the Cinemachine Free Look camera, this is basically how it works, except that it only deals with following and I have to maintain the orientation manually with the mouse. But if I use Cinemachine Virtual Camera, because I don't want to deal with the free look part of it, for some bizarre reason it locks the position of the GameObject containing the camera to `(0, 0, 0)`! And I don't just mean it moves it there; it's stuck there! If I go into the Inspector and change the position at runtime, it instantly changes back to `(0, 0, 0)`.

What can cause Cinemachine Virtual Camera to do this? And how can I make it stop?

# Answer
> 1 votes
It is about the properties of the Virtual Camera. Tons of options are available when Virtual Camera is selected. You can check the documentation of it here

When you add a Virtual Camera on a scene, its Body property is set to Transposer and its Aim property is set to Composer. Body property determines how to follow the object in terms of world positions when you add a Transform to Follow variable and Aim property determines the rotation of the camera.

If you want a 3rd Person like follower camera for your object, you can use Virtual Camera and set Body property and Aim property to Transposer & Hard Look At, respectively. When these properties is set, your objects Transform has to be assigned to the Follow & Look At variables.

---
Tags: unity, cinemachine
---


# Question
Title: Rendering differences between ps_1_3 and ps_2_a
I am trying to update a shader from `ps_1_3` inline assembly to `ps_2_a` HLSL. However the HLSL shader causes things to render differently when using `ps_2_a`. When using my HLSL conversion with `ps_1_3` it works same way as with the inline assembly.

Original assembly

```
Sampler[0] = (DiffuseMapSampler);
pixelShader = asm
{
    ps_1_3
    tex t0
#ifdef _POINTLIGHT_
    add r0.rgb, v0, v0
    +mov r0.a, v0.a
    mul_x4 r0, t0, r0
#else
    mul_x4 r0, t0, v0
#endif
#if defined(OVERGROWTH) && HASALPHA2MASK
    mul_x2 r0.a, r0.a, t0.a
#endif
};

```

Sampler and VS\_OUTPUT

```
struct VS_OUTPUT
{
    float4 Pos  : POSITION0;
    float2 Tex0 : TEXCOORD0;
#if _HASSHADOW_
    float4 TexShadow    : TEXCOORD1;
#endif
    float4 Color  : COLOR0;
    float Fog   : FOG;
};

texture DiffuseMap;
sampler DiffuseMapSampler = sampler_state
{
    Texture = (DiffuseMap);
    MipFilter = LINEAR;
    MinFilter = LINEAR;
    MagFilter = LINEAR;
    AddressU  = WRAP;
    AddressV  = WRAP;
    MipMapLodBias = 0;
};

```

My HLSL translation

```
float4 basicPixelShaderNoShadow(VS_OUTPUT VsOut) : COLOR
{
    float4 diffuseMap = tex2D(DiffuseMapSampler, VsOut.Tex0);
    float4 outCol;
#ifdef _POINTLIGHT_
    outCol.rgb = VsOut.Color.rgb + VsOut.Color.rgb;
    outCol.a = VsOut.Color.a;
    outCol = (diffuseMap * outCol) * 4;
#else
    outCol = (diffuseMap * VsOut.Color) * 4;
#endif

#if defined(OVERGROWTH) && HASALPHA2MASK
    outCol.a = (outCol.a * diffuseMap.a) * 2;
#endif
    return outCol;
}

```

And this is the result in game  For some reason when using `ps_2_a` the colours are oversaturated.

Edit: HLSL that fixed the issue:

```
float4 vertexColor = float4(VsOut.Color.rgb, VsOut.Color.a*2);
float4 diffuseMap = tex2D(DiffuseMapSampler, VsOut.Tex0);

float4 outCol = diffuseMap * vertexColor * 2;

#if defined(OVERGROWTH) && HASALPHA2MASK
outCol.a *= 2 * diffuseMap.a;
#endif

return outCol;

```

dont quite understand why, but it works :)

# Answer
I haven't (yet) found definitive confirmation of this (and it's likely lost in the mists of time, in ancient documentation that no longer exists), but SM1.3 is clearly clamping intermediates to 1.0 whereas SM2 is not.

So, for example, where you have:

```
outCol.rgb = VsOut.Color.rgb + VsOut.Color.rgb;

```

And:

```
outCol = (diffuseMap * outCol) * 4;

```

If the result of any of these exceeds 1.0, SM1.3 is clearly clamping it. To replicate the SM1.3 behaviour in SM2 you could use e.g. the clamp or max intrinsics.
> 1 votes

---
Tags: hlsl, directx9
---


# Question
Title: how to ADD a NEW entity/item/effect to Minecraft Java
In Minecraft Java, I am creating many resource packs by myself (no studio or external resource) so, I want to ***ADD*** a new file/entity/element/items/etc. to the game to not replace an old item because EVERY item/effect/entity has SOME use in the game. In conclusion: how I can ADD \[not replace\] a file in the game and give it custom physical and mental properties?

# Answer
> 0 votes
1. Get a texture for the Minecraft mob (or make one yourself).
2. In MCreator, Click on "New Mod"
3. Next, click on "Mob" and name your mod. Names mustn't repeat. Make it something you understand, the end-user won't see this name.
4. Then, fill out all of the custom characteristics of your mob.
5. Finally, export your mod into your preferred version of Minecraft.

I found these instructions from here.

---
Tags: minecraft-modding
---


# Question
Title: Issues with referencing experimental light class
I am trying to reference a Light2D component on a GameObject but I get the following error:

```
'The type or namespace name 'Universal' does not exist in the namespace 'UnityEngine.Experimental.Rendering'.

```

I have confirmed that I have v10.2.2 of the Universal RP package in package manager. I have also attempted regenerating all csproj files as well as deleting the Library folder and reopening Unity. I also have the library reference to 'UnityEngine.Experimental.Rendering.Universal' in my script.

# Answer
> 2 votes
If you are using an assembly definition asset make sure you add references to the universal pipeline assets under the Assembly Definition References portion.

---
Tags: unity, lighting
---


# Question
Title: Frame Buffer Object (FBO) is not working. What is the right way to use?
I am trying to use FBO but i am living some problems. I will show you my steps but first i will show my running screen ,so we can compare them. Like before fbo after fbo.

My running screen and Draw() function code:

```
glClearColor(0.5,0.5,0.5,1.0);
glLoadIdentity();
glTranslatef(0.0,0.0,-3.0);
glRotatef(0,0.0,1.0,0.0);
glUniform3f(glGetUniformLocation(mainShader->getProgramId(),"lightPos"),0,1,2);
mainShader->useShader();
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    scene->draw(mainShader->getProgramId());
mainShader->delShader();

```

After I tried to add FBO :

Create FBO texture function:

```
unsigned int createTexture(int w,int h,bool isDepth=false)
{
    unsigned int textureId;
    glGenTextures(1,&textureId);
    glBindTexture(GL_TEXTURE_2D,textureId);
    glTexImage2D(GL_TEXTURE_2D,0,(!isDepth ? GL_RGBA8 : GL_DEPTH_COMPONENT),w,h,0,isDepth ? GL_DEPTH_COMPONENT : GL_RGBA,GL_FLOAT,NULL);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);

    int i;
    i=glGetError();
    if(i!=0)
    {
        std::cout << "Error happened while loading the texture: " << i << std::endl;
    }
    glBindTexture(GL_TEXTURE_2D,0);
    return textureId;
}

```

Init() function :

```
void init()
{
    glClearColor(0,0,0,1);
    glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluPerspective(50,640.0/480.0,1,1000);
    glMatrixMode(GL_MODELVIEW);
    glEnable(GL_DEPTH_TEST);
    mainShader=new shader("vertex.vs","fragment.frag");
    quadRenderShader=new shader("quadRender.vs","quadRender.frag");
    scene=new meshLoader("test.blend");

    renderTexture=createTexture(640,480);
    depthTexture=createTexture(640,480,true);
    glGenFramebuffers(1,&FBO);
    glBindFramebuffer(GL_FRAMEBUFFER,FBO);
    //GL_COLOR_ATTACHMENT0
    //GL_DEPTH_ATTACHMENT
    glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,renderTexture,0);

    glFramebufferTexture2D(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D,depthTexture,0);

    int i=glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if(i!=GL_FRAMEBUFFER_COMPLETE)
    {
        std::cout << "Framebuffer is not OK, status=" << i << std::endl;
    }
    glBindFramebuffer(GL_FRAMEBUFFER,0);

}

```

And Draw() function:

```
void display()
{
    //rendering to texture...
    glClearColor(0.5,0.5,0.5,1.0);
    glLoadIdentity();
    glTranslatef(0.0,0.0,-3.0);
    glRotatef(0,0.0,1.0,0.0);
    glUniform3f(glGetUniformLocation(mainShader->getProgramId(),"lightPos"),0,1,2);
    mainShader->useShader();
    glBindFramebuffer(GL_FRAMEBUFFER,FBO);
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
        scene->draw(mainShader->getProgramId());
    glBindFramebuffer(GL_FRAMEBUFFER,0);
    mainShader->delShader();

    glClearColor(0.0,0.0,0.0,1.0);
    //render texture to screen
    glLoadIdentity();
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    quadRenderShader->useShader();
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D,depthTexture);
    glUniform1i(glGetUniformLocation(quadRenderShader->getProgramId(),"texture"),0);
    quad->draw(quadRenderShader->getProgramId());
    quadRenderShader->delShader();

}

```

and Result only drawing last setup color (glClearColor) so black :

Result should be like in tutorial :

Note: I know tutorial monkey is purple but it is not problem.

# Answer
> 1 votes
I ran into this problem and fixed it by clearing BOTH the framebuffer quads contents which happens after it is bound, and since the quad is drawn to the screen, the screen needs to be cleared too:

```
while(!glfwWindowShouldClose(window))
{
    // clear quad from screen
    glClear(GL_COLOR_BUFFER_BIT);
    glClear(GL_DEPTH_BUFFER_BIT);
    glBindFramebuffer(GL_FRAMEBUFFER,FBO);
    // clear fbo contents
    glClear(GL_COLOR_BUFFER_BIT);
    glClear(GL_DEPTH_BUFFER_BIT);
    ...
    glBindFramebuffer(GL_FRAMEBUFFER,0);

}

```

# Answer
> 0 votes
What happens if you change your:

```
glBindFramebuffer(GL_FRAMEBUFFER,FBO);
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    scene->draw(mainShader->getProgramId());

```

to the first line of your display function? Try to compare your code to this of mine: https://github.com/felipunky/LearnOpenGL-master/tree/master/LearnOpenGL I use frameBuffers there the only difference is that I need to reference the shaders to themselves, so I have:

```
glBindTexture( GL_TEXTURE_2D, even ? textureColourBufferOne : textureColourBuffer );

```

You would just have something like:

```
glBindTexture( GL_TEXTURE_2D, textureColourBufferOne );

```

---
Tags: opengl, glsl
---


# Question
Title: How can users verify a game distributed peer-to-peer has not been modified maliciously?
I'm interested in p2p software distribution, and I'm also directly including a modding interface into my game, which is built on my own custom engine.

I was working with a folder inside of the Roaming folder to store the data (resource, saves... etc), and I quickly figured out a malicious programmer could easily modify my program and make or erase (at least) folders.

How would one prevent this kind of modification, without owning the whole distribution process?

Do you really have to trust the provider/source to trust the software? Or could you trust software on the client side using some hash or such?

The only solution I can think of would be having a website on which I put a hash of my game, and any user that gets an instance of my game can verify it was not modified by hashing it and comparing it with the one on my website. But it is definetely not user-friendly at all...

# Answer
> 0 votes
> The only solution I can think of would be having a website on which I put a hash of my game, and any user that gets an instance of my game can verify it was not modified by hashing it and comparing it with the one on my website. But it is definetely not user-friendly at all...

It sounds then like you have your answer: publish the expected hash of your game, and ask users to compare their hash to the published version.

Anything you do client-side to make this more user-friendly is subject to the same risk of tampering: the malicious distributor simply replaces the files responsible for your user-friendly verification flow with a modified version that reports "Everything's OK!" despite their tampering.

You can make your server-side version a little nicer, with simple instructions, and a field to paste a hash to compare and get clearly-explained results automatically, rather than making the user check character-by-character. But that's about it.

In publishing games over a network, we must always be conscious "the client is in the hands of the enemy" - so the server is the only side of the equation we can trust.

# Answer
> 0 votes
The truth is, you can't always prevent this kind of modification. No matter what you do, the player can ***always*** find a way to get past your security. But, if it's a singleplayer game, you can make it more difficult for the hacker by implementing a **Binary Formatter** or another formatter of some sort, which will make the process much more difficult. If it's a multiplayer game, you can prevent exploiting to some extent by trying to run as much of the game logic as you can on the server side. You can't really trust the data clients give to the server, since they can mess with that data, then pass it to the server.

---
Tags: security
---


# Question
Title: Player not moving camera to the other side of the screen when hitting the screen edge
I'm working on a game where I want the player to appear on the other side of the screen when they get to the edge of the screen, essentially mimicking the background moving. When the player gets to the edge of the map, they shouldn't be able to move anymore. I'm just trying to get the first part to work where the player appears on the other side of the screen after hitting the edge. My full code is below.

```
#Import the pygame module
import pygame

from pygame.locals import (
    K_w,
    K_s,
    K_a,
    K_d,
    K_ESCAPE,
    KEYDOWN,
    QUIT,

)

BLUE = (0,0,255)
PURPLE = (153,50,204)
GREEN = (0,128,0)

MAP = [[BLUE, GREEN, BLUE],
       [GREEN, PURPLE, GREEN],
       [PURPLE, GREEN, BLUE]]

class Map():
    def __init__(self,map):
        self.map = map

    def update_map(self):
        pass

# Define constants for the screen width and height
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SPEED = 8
# Setup the clock for a decent framerate
clock = pygame.time.Clock()

# Define a player object by extending pygame.sprite.Sprite

# The surface drawn on the screen is now an attribute of 'player'
worldMaxX = SCREEN_WIDTH*3
worldMaxY = SCREEN_HEIGHT*3

cameraX = SCREEN_WIDTH
cameraY = SCREEN_HEIGHT

class Camera():
    def __init__(self):
        self.worldX = 0
        self.worldY = 0
        self.cameraX = SCREEN_WIDTH
        self.cameraY = SCREEN_HEIGHT
    def worldCoordinates(self,screenX, screenY):
        worldX = self.cameraX + screenX
        worldY = self.cameraY + screenY
        return (worldX, worldY)

    def screenCoordinates(self,worldX, worldY):
        screenX = worldX - cameraX
        screenY = worldY - cameraY
        return (screenX,screenY)

class Player(Camera):
    def __init__(self):
        super(Player,self).__init__()
        self.player_surface = pygame.Surface((25, 25))
        self.player_surface.fill((255, 0, 255))
        self.rect = self.player_surface.get_rect(center = (25,25))

    def update(self, pressed_keys):
        # Move the sprite based on user keypresses
        if pressed_keys[K_w]:
            self.worldX,self.worldY = self.worldCoordinates(self.rect.x,self.rect.y)
            self.worldY -= SPEED

            self.rect.x,self.rect.y =  self.screenCoordinates(self.worldX,self.worldY)

        if pressed_keys[K_s]:
            self.worldX,self.worldY = self.worldCoordinates(self.rect.x,self.rect.y)
            self.worldY += SPEED

            self.rect.x,self.rect.y =  self.screenCoordinates(self.worldX,self.worldY)

        if pressed_keys[K_a]:
            self.worldX,self.worldY = self.worldCoordinates(self.rect.x,self.rect.y)
            self.worldX -= SPEED

            self.rect.x,self.rect.y =  self.screenCoordinates(self.worldX,self.worldY)

        if pressed_keys[K_d]:
            self.worldX,self.worldY = self.worldCoordinates(self.rect.x,self.rect.y)
            self.worldX += SPEED

            self.rect.x,self.rect.y =  self.screenCoordinates(self.worldX,self.worldY)

    def updateCamera(self):
    #Move camera
        if (self.rect.x < 0):
            self.rect.x = SCREEN_WIDTH
        if (self.rect.x >= SCREEN_WIDTH):
            self.rect.x = 0

        if (self.rect.y <= 0):
            self.rect.y = SCREEN_HEIGHT

        if (self.rect.y >= SCREEN_HEIGHT):
            self.rect.y = 0

    def render(self,position):
        screen.blit(self.player_surface, position)

# Initialize pygame
pygame.init()

# Create the screen object
# The size is determined by the constant SCREEN_WIDTH and SCREEN_HEIGHT
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

# Instantiate player. Right now, this is just a rectangle.
player = Player()

# Variable to keep the main loop running
running = True

# Main loop
while running:

    # for loop through the event queue

    for event in pygame.event.get():
        # Check for KEYDOWN event

        if event.type == KEYDOWN:
            # If the Esc key is pressed, then exit the main loop
            if event.key == K_ESCAPE:
                running = False
        # Check for QUIT event. If QUIT, then set running to false.
        elif event.type == QUIT:
            running = False

    # Get all the keys currently pressed
    pressed_keys = pygame.key.get_pressed()

    # Fill the screen with black
    screen.fill((0, 0, 0))

    player.update(pressed_keys)
    player.updateCamera()
    # Draw the player on the screen
    player.render(player.rect)

    # Update the display
    pygame.display.flip()

    clock.tick(60)

```

---

What happens though is that my player square doesn't appear on the other side of the screen when going left or up. But, I don't understand why. I thought the code below would work, which it does when moving right, and down, but not up or left. What am I doing wrong with the camera method updateCamera that this isn't happening the way I expect it too?

```
    def updateCamera(self):
    #Move camera
        if (self.rect.x < 0):
            self.rect.x = SCREEN_WIDTH
        if (self.rect.x >= SCREEN_WIDTH):
            self.rect.x = 0

        if (self.rect.y <= 0):
            self.rect.y = SCREEN_HEIGHT

        if (self.rect.y >= SCREEN_HEIGHT):
            self.rect.y = 0

```

# Answer
You need to use `elif` for your second conditional, not just `if`. If I role-play as your computer real quick with my `self.rect.x` value to something less than zero, this is what I say:

```
if (self.rect.x < 0):
            self.rect.x = SCREEN_WIDTH

```

Oh, OK! `self.rect.x` is less than zero, so I'll set it equal to `SCREEN_WIDTH`! Onward to the next line!

```
if (self.rect.x >= SCREEN_WIDTH):
            self.rect.x = 0

```

Oh, OK! `self.rect.x` is equal to `SCREEN_WIDTH`, so I'll set it right back to zero!

Hence, it works when going right and down (those are the second `if`s), but not left or up. This is the code that should work:

```
if (self.rect.x < 0):
    self.rect.x = SCREEN_WIDTH
elif (self.rect.x >= SCREEN_WIDTH):
    self.rect.x = 0

```
> 1 votes

---
Tags: camera, python, pygame
---


title: Window handle is invalid

text:
# Question
Title: Window handle is invalid
I'm trying to implement an input listener for FNA (modern version of XNA). Since FNA does not supply any sort of way to listen to native input this has to be done through the windows API and native calls. This is how I set this up:

```
public KeyboardListener(GameWindow window) {
    var procedurePointer = Marshal.GetFunctionPointerForDelegate<WindowProcedure>(Procedure);
    procedure = new IntPtr(SetWindowLongPtr(window.Handle, GWL_WNDPROC, procedurePointer.ToInt64()));
    if (procedure == IntPtr.Zero)
    {
        var error = GetLastError();
        throw error switch
        {
            ERROR_INVALID_WINDOW_HANDLE => new InvalidOperationException("Invalid window handle"),
            _ => new InvalidOperationException($"Unknown error message '0x{error:X4}'")
        };
    }
}

// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowlongptra#parameters
private const int GWL_WNDPROC = -4;

// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowlonga
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int SetWindowLongPtr(IntPtr hWnd, int nIndex, long dwNewLong);

[DllImport("Kernel32.dll", CharSet = CharSet.Unicode)]
private static extern uint GetLastError();

```

I construct the keyboard listener during the `Initialize` method of `Game`:

```
class MyGame : Game {
    protected override void Initialize() {
        new KeyboardListener(Window);
    }
}

```

This is the method call that reports the error: `SetWindowLongPtr(window.Handle, GWL_WNDPROC, procedurePointer.ToInt64())` and it throws `"Invalid window handle"`. It's worth noting that the example code I saw converted the pointers to `Int32` instead of `Int64`, but I am on a 64 bit machine so the pointers can not fit in 32 bits.

---

### What I've tried & figured out so far...

* Debugging tells me that both `window.Handle` and `procedurePointer` are non-null and at least point to *something*.
* I have tried to initialize it earlier or later, but that doesn't seem to make a difference.
* Other native methods such as `SDL2.SDL.SDL_MinimizeWindow(Window.Handle)` work perfectly fine and don't complain about the window handle.

# Answer
So after like 5 hours of debugging of course I solve it 3 minutes after I write up this answer (as always Stack Exchange is the best rubber duck).

The clue is that `SDL2.SDL.SDL_MinimizeWindow(Window.Handle)` and all other SDL calls work perfectly fine. Turns out FNA is slightly different from XNA in that `Window.Handle` points to an `SDL` window, not a Win32 window.

The fix for this is easy, fortunately:

```
// This is required, otherwise this procedure will be garbage collected. Note that this field must be static.
private static WindowPointer nonGcProcedure;

public KeyboardListener(GameWindow window) {
    nonGcProcedure ??= Procedure;

    // Convert the SDL handle to a win handle
    var info = new SDL.SDL_SysWMinfo();
    SDL.SDL_VERSION(out info.version); // This *might* not be required
    if (SDL.SDL_GetWindowWMInfo(window.Handle, ref info) == SDL.SDL_bool.SDL_FALSE)
        throw new InvalidOperationException();

    var winPointer = info.info.win.window;
    var procedurePointer = Marshal.GetFunctionPointerForDelegate(nonGcProcedure);
    procedure = new IntPtr(SetWindowLongPtr(winPointer, GWL_WNDPROC, procedurePointer.ToInt64()));
    if (procedure == IntPtr.Zero)
    {
        var error = GetLastError();
        throw error switch
        {
            ERROR_INVALID_WINDOW_HANDLE => new InvalidOperationException("Invalid window handle"),
            _ => new InvalidOperationException($"Unknown error message '0x{error:X4}'")
        };
    }
}

```
> 1 votes

---
Tags: c#, xna, windows, windows-forms, fna
---


# Question
Title: How do I let the player create a list, and make the game cycle through that list?
I'm creating a game where the player can put 4 objects in any combination, even 4 of itself. What would be the best method of going about this, and letting the game cycle through the list the player created based on a timer.

Example: The player has 4 weapons: Katana, Axe, Spear, Chakram. The player can set the order to Chakram, Chakram, Katana, Spear. The game will give the player the item based on the order of the list they set. The game will only give the player an item after a set amount of time.

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

public class Runner : MonoBehaviour
{
    private Touch _touch;
    private Rigidbody _rb;
    private Animator _anim;
    private UIManager _ui;

    [SerializeField] private HealthBar _healthBar;
    [SerializeField] private Bullet _bullet;

    [SerializeField] private float _moveSpeed = 0.25f;
    [SerializeField] private float _dashSpeed = 0.5f;
    [SerializeField] private int _health = 20;
    [SerializeField] private int _currentHealth;

    [SerializeField] private bool _hasZwei;
    [SerializeField] private bool _hasAxe;
    [SerializeField] private bool _hasDagger;
    [SerializeField] private bool _hasKatana;

    void Start()
    {

        _rb = GetComponent<Rigidbody>(); //Accessing the Rigidbody Component
        _anim = GetComponent<Animator>(); //Accessing the Animator Component
        _ui = GameObject.Find("UI Manager").GetComponent<UIManager>(); //Accessing the UI Manager Component

        _currentHealth = _health;
        _healthBar.SetMaxHealth(_health);

        _anim.SetBool("Running",true);
    }

    // Update is called once per frame
    void FixedUpdate()
    {
       Movement();
    }

    void Update()
    {
        Invoke("GainPowerUp", 5f);
    }

    void Movement()
    {
        if (Input.touchCount > 0)
        {
            _touch = Input.GetTouch(0);

            if (_touch.phase == TouchPhase.Moved)
            {
                _rb.MovePosition( new Vector3(
                transform.position.x + _touch.deltaPosition.x * _moveSpeed,
                transform.position.y,
                transform.position.z + _touch.deltaPosition.y * _moveSpeed));
                _rb.constraints = RigidbodyConstraints.FreezeRotation;
            }
        }

        if (Input.touchCount == 2)
        {
            _touch = Input.GetTouch(1);

            switch(_touch.phase)
            {
                case TouchPhase.Began:
                if (_hasAxe == false && _hasZwei == false && _hasKatana == false && _hasDagger == false)
                {
                    Debug.Log("Has no weapon.");
                }
                if(_hasZwei)
                {
                    Debug.Log("Player has attacked with Zweihander");
                    _hasZwei = false;
                    _anim.SetTrigger("NoWeapon");
                }
                if(_hasAxe)
                {
                    Debug.Log("Player has attacked with Axe");
                    _hasAxe = false;
                    _anim.SetTrigger("NoWeapon");
                }
                if(_hasDagger)
                {
                    Debug.Log("Player has attacked with Dagger");
                    _hasDagger = false;
                    _anim.SetTrigger("NoWeapon");
                }
                if(_hasKatana)
                {
                    Debug.Log("Player has attacked with Katana");
                    _hasKatana = false;
                   _anim.SetTrigger("NoWeapon");
                }
                break;
            }
        }
    }

    public void Damage(int damage)
    {
        _currentHealth -= damage;

        _healthBar.SetHealth(_currentHealth);

        if (_currentHealth == 0)
        {
            gameObject.SetActive(false);
        }
    }

    public void GainPowerUp(int _powerUp)
    {
        _powerUp = Random.Range(0,4);

        switch(_powerUp)
        {
            case 1:
                //Sword Powerup
                _hasZwei = true;
                _hasAxe = false;
                _hasDagger = false;
                _hasKatana = false;
                _anim.SetTrigger("SwordRun");
                break;

            case 2:
                //Axe Powerup
                _hasAxe = true;
                _hasZwei = false;
                _hasDagger = false;
                _hasKatana = false;
                _anim.SetTrigger("AxeRun");
                break;

            case 3:
                //Katana Powerup
                _hasKatana = true;
                _hasAxe = false;
                _hasDagger = false;
                _hasZwei = false;
                _anim.SetTrigger("KatanaRun");
                break;

            case 4:
                //Dagger Powerup
                _hasDagger = true;
                _hasAxe = false;
                _hasKatana = false;
                _hasZwei = false;
                _anim.SetTrigger("DaggerRun");
                break;
        }
    }
}

```

# Answer
If you want to call your powerUp on a fixed cycle, you should use InvokeRepeating instead of Invoke, which allows you as a third parameter the cycle when it is called.

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

Do not place it in Update but in Start, it just needs to be called once for calling itself for future calls. You can increase a counter inside your PowerUp that resets to 0 once you hit the size of your array that holds the elements you want to cycle through.
> 1 votes

---
Tags: c#
---


title: Procedurally Generating Locked Doors

text:
# Question
Title: Procedurally Generating Locked Doors
An upcoming goal of mine is to write a procedural generation algorithm for daggerfall-esque dungeons. However, I plan on including doors locked with specific keys and I would rather they be able to be accessed by the player, at least at some point. (Perhaps in a hypothetical situation. one or two keys are accessible at first and the rest are locked behind those doors)

How would I go about approaching this?

# Answer
> 2 votes
Doors and keys (or switches, or puzzles, or whatever is used to open them), have a very simple rule: The player must be able to reach the key without crossing the door.

Ergo, if you decide, at random, that at some point there will be a door. There must be a path from the start position to the position of they that does not crosses the door.

Furthermore, a locked door is - rarely - of much use for the design if you can simply bypass it. Thus, we expect that the door restrict access to some part of the graph (dungeon or maze). So, you know, don't put the key there.

---

However, I will suggest to generate the dungeon by expanding from the starting area. And I'm going to suggest to place the keys first. That way you know that the key will be reachable before the door. I'll also suggest to expand breath first, to increase the chance a key will be on a different path than the door it opens.

You may also want to avoid interconnecting path that require different sets of keys. A simple way to do that (assuming a single threaded generation) is marking every area with the number of keys you have placed, and only connect between existing areas that have the same number (or if you can make one way paths, make them from higher to lower number, so they are shortcuts for backtracking but not for sequence breaking - or if you want to support sequence breaking those paths need to be hidden or hard to execute). *Or don't connect at all, that is even easier. In which case the dungeon will be a tree.*

Thus, it is possible to generate the order of keys and doors, as long as the key for a door is before it. And then you place it in that order.

---

By the way, I said area, because they don't have to be rooms. You may generate areas, and then subdivide them into rooms and corridors with a secondary dungeon generation algorithm. If you do that at all, and what kind of algorithm, depends on what you are going for.

---

Going further:

For a zelda-like design, you want the dungeon to have states. There will be something that open some paths in exchange of closing others. We are not talking of a switch that opens a door. That would be a key. We are talking of a switch that opens some doors and closes others. *Or on a Metroidvania fashion, there will a second version of the map, and instead of a switch we have a room that allows to travel between them.*

To do that, when you generate a new area, add a new node for each state of the node. Do the interconnections of the area based on the state. *The node for the area 1 in state A, connects to the node for the are 2 also in state A.* On a switch area, all the states gets connected. To account for the operation of the switch, some paths will be blocked on one graph, but not on the other.

For example, let us say our map in state A looks like this:

```
    8   5 - 4
    |
    1 - 2 - 3

        6 - 7

```

And in state B looks like this:

```
    8   5 - 4
        |   |
    1 - 2   3
        |
        6 - 7

```

Where area 3 is a switch area.

If we made our graph as follows:

```
    8   5 - 4
    |   |   |
    1 - 2 - 3
        |
        6 - 7

```

It would appear that I can put a key in 5 that opens the path from 2 to 3. But that won't work, because we need to go from 2 to 3 to activate the switch before we can reach 5.

Instead the graph must be like this:

```
    8   5 - 4
    |
    1 - 2 - 3-+
              |
        6 - 7 |
              |
              |
    8   5 - 4 |
        |   | |
    1 - 2   3-+
        |
        6 - 7

```

And that is why a node per area per state is created. In this case with two states, each area has two nodes.

*We also see, for example, it is valid to put a key in 5 that opens 8, but using it requires to switch back.*

---

By the way, a door does not have to be a literal door. It can be some kind of obstacle that can only be removed if you a certain something which we call a key. For example, you could have rocks blocking a path, and you need a bomb to open it. The rocks are the door, the bombs are the key. You put that in your dungeon generation system, et voilà.

---
Tags: unity, c#, procedural-generation
---


# Question
Title: Disable and re-enable image tracking ARKit
Is there a way to disable and re-enable tracking for images in ARKit? From the older versions, this was the solution. But the newer versions have removed the `UnityARSessionNativeInterface` script.

```
void Start ()
{
    m_session = UnityARSessionNativeInterface.GetARSessionNativeInterface();
}

void AddImageAnchor(ARImageAnchor arImageAnchor)
{
    //at the bottom of this function
    StartCoroutine(RemoveAnchorCoroutine(arImageAnchor));
}

IEnumerator RemoveAnchorCoroutine(ARImageAnchor anchor)
{
    yield return new WaitForSeconds(3.0f);
    //doesn't have to be in a coroutine, but for my uses it is
    m_session.RemoveUserAnchor(anchor.identifier);
}

```

# Answer
See this answer on stack overflow; I'm copying it here in case it gets removed from SO.

---

The current ARKit API doesn't have a method to disable or enable it in Unity, during run-time at this point.

With than being said, Unity has its own function to enable and disable VR, AR or XR plugins. If ARKit is built correctly, this method should work. So, you might be able to disable/enable ARKit by setting `XRSettings.enabled` to `false` and enable it by setting it to `true`.

It's also a good idea to call `XRSettings.LoadDeviceByName` with an empty string, wait for frame, before setting `XRSettings.enabled` to `false` to disable it:

```
IEnumerator DisableAR()
{
    XRSettings.LoadDeviceByName("");
    yield return null;
    XRSettings.enabled = false;
}

```

then call to disable:

```
StartCoroutine(DisableAR());

```
> 0 votes

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