title: Multiple viewport resizing

text:
# Question
Title: Multiple viewport resizing
I wonder how multiple viewports are handled in engines in terms of render targets buffers. Especially in the case of their resizing (for example changing the size of windows/viewports in Editor dock systems).

We apparently need separate color and depth buffers for each, and the sizes of these buffers should be equal to the sizes of viewports.

So does it means, that we have to recreate those buffers each time we resize viewports?

# Answer
> 0 votes
After a little digging found out that it can be enough to have only one main color (backbuffer) and depth buffer.
For proper rendering and clearing buffers between different viewports we can just use scissors test setting scissors equal to each viewport we about to draw.
So theres no need to additional handle "virtual" viewports changes and resize buffers, just set new values for scissors rect

Metal API case:
You can't simply set scissors and only after that clean the render target in metal api. It's should be in vice versa.
So I managed it by creating additional pass that only draws clear color on provided viewport size. It runs before any other passes each time we meet new viewport during frame rendering.

---
Tags: rendering, viewport, rendertexture, rendertargets
---


# Question
Title: Playing animation on button press with a condition
I want to do menu animation. In the animator, its contain 2 animations. One is opening animation, the other is closing animation. I set the opening animation as default state and added condition between of them. The condition contains one parameter, it is a bool type parameter. I drag the script which controls they behaviours on gameobject and animator component, but when the opening animation plays and player clicks the play button the parameter turns into true but it doesn't play.

```
 Animator canvasAnim;

 public Button lvlSelector;
 Button lvlSelector_A;

 // Use this for initialization
 void Start () {
     canvasAnim = GetComponent<Animator>();

     lvlSelector_A = lvlSelector.GetComponent<Button>();
     lvlSelector_A.onClick.AddListener(LevelSelector);

 }
 IEnumerator SlideLevelSelectMenu()
 {

     yield return new WaitForSeconds(1f);
     SceneManager.LoadScene("LevelSelectMenu");
 }

 void LevelSelector()
 {
     canvasAnim.SetBool("clickedclose", true);
     StartCoroutine(SlideLevelSelectMenu());
 }

```

# Answer
> 0 votes
Maybe you should add your `onClick` method as an AnimationEvent after the MainMenuClosing animation finishes. Animation Events allow you to add data to an imported clip which determines when certain actions should occur in time with the animation.

(Sorry couldn't post this as a comment)

# Answer
> -1 votes
Its a better idea not to use unity's animation system for UI animation. For the purpose of UI Animation use a Tween Library. I use DOTween for UI related animation. Its really easy to use as well.

For example if I had to make a simple scale animation on button click I can do something like this

```
void OnClick()
{
   button.transform.DoScale(0.8f,1f);
}

```

You can also add sequence of Animations for complex effects. This video from GameDevGuide explains it better: https://www.youtube.com/watch?v=Ll3yujn9GVQ

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


# Question
Title: Modelling Two Way Relationship in Unity for Scriptable Objects
How does one model two-way relationships for scriptable objects?

Let's say we have a number of items in-game, and each item can be obtained by different conditions. Some may require you to complete a certain mission, some may be purchasable from an NPC, some may be dropped from an enemy, and some may require you to purchase a DLC...

Given an item, we would like to know what are the ways that it could be obtained; and given a mission/npc/enemy/dlc, we would like to know what items it grants.

How can I model two way relationships like this?

For items alone, it may be easy to handle... but as you can imagine, there are a lot more two-way relationships in games, between missions and NPC, missions and missions, DLC and NPC... and so on.

# Answer
> 1 votes
I think this problem calls for another layer of abstraction. So i think it’s not a two-way relationship, but rather two one-way relationships.

Let’s take the example of a sword. This could be Dropped from monsters, Sold in a shop, etc etc.

So a sword could implement IDroppable, ISellable interfaces.

A store would have a list of ISellables and a monster would have a list of IDroppables.

This concept is called composition. You compose an object with properties that give it some functionality.

My example above uses interfaces. Another common way, is instead of the class Sword implementing the interface, the sword would have a set of components. Like Sellable Droppable etc. Whichever way you choose has pros and cons but the idea is similar. For scriptable objects, I suspect the component approach is better since Unity doesn’t play too nice with interfaces. So In my projects I would have something like

`List<CollectionSource>` where IDroppable and ISellable are both Collectionsources. And then do (pseudo code) `if list.contains(any IDroppable )` then we know it’s droppable.

To find out which monsters drop your sword, you could now write an editor window that scans your project for any store scriptable objects. And then scan each of their inventories to see if they contain the sword. If so, add them to the list in the window.

To find out how the sword can be obtained you need only look at which components/interfaces it has. A legendary weapon might only have a IUnlockable component and no ISellable, meaning stores can’t possibly have it. It can only be provided by situations that can provide Unlockables.

So we’ve changed the 2 way relationship into:

* **How is it collected?** Does it have IDroppable?
* **What monsters drop it?** Does sword have IDroppable? Search all monsters for having sword (as an IDroppable) in their drop list

Aside: Creating a list of IDroppables that is unity-inspector-friendly is not easy. For example a monster’s drop list. The easiest way I’ve found is to use abstract classes as a base for your component. But then you lose the full power and polymorphism of interfaces or full components. Other ways might be to have the list be of type Item, but then use the OnValidate function to weed out anything that isn’t an IDroppable. I tend to use both depending on the situation and the exact way I want to scale things up.

# Answer
> 0 votes
Have two scriptable objects references each other, but it's error prone. So we will need to have some validation logic, or an editor script that updates relationship automatically when one was changed. Also it would be time-consuming to write scripts for all the different relationships that needs to be accessed two ways.

Perhaps a third scriptable object can be used to store the relationship, and custom tooling can be made to automatically update the value on the two scriptable objects.

# Answer
> 0 votes
Make one-way reference only, and have the two-way relationships initialized at runtime.

But what if we want to have the relationship displayed in the Unity Editor two-way? A possible solution is to write a script that iterates through all scriptable objects and build a relationship graph between scriptable objects, but it would also be very time-consuming.

So a solution could be to abstract the scriptable objects and create a base class/interface for all relational scriptable objects. Then, let each class reports their relationship (and sub-relationship) through an abstract property, and iterate from the root object to build the relationship graph for both edit and play mode.

# Answer
> 0 votes
Use an actual relational database like SQLlite to store the relationship, and perhaps an id/guid reference to the actual scriptable object for easy editing within the Unity Editor. Or maybe, just ditch scriptable object completely.

There also seem to be some relational databases specifically made for Unity, with Unity data types support, and it may work for your case.

# Answer
> 0 votes
If this is only used for developer reference in the Unity Editor, and you only need to check one item at a time, you can do something like this (searching through each relevant asset in the game to find references):

```
public class NPC : ScriptableObject {
    [SerializeField] private List<Item> dropOnDeath;
    public IReadOnlyList<Item> DropOnDeath => dropOnDeath;
}

public struct ItemQuantity {
    public Item item;
    public int quantity;
}

public class Shop : ScriptableObject {
    [SerializeField] private List<ItemQuantity> inventory;
    public IReadOnlyList<ItemQuantity> Inventory => inventory;
}

public class Quest : ScriptableObject {
    [SerializeField] private List<Item> itemRewards;
    public IReadOnlyList<Item> ItemRewards => itemRewards;
}

[CustomEditor(typeof(Item))]
public class ItemEditor : Editor<Item> {
    private List<UnityEngine.Object> sources = new List<UnityEngine.Object>();

    override void OnInspectorGUI() {
        var item = (Item)target;

        if (GUILayout.Button("Find references")) {
            sources.Clear();
            //search each asset that can contain a reference to an item
            List<NPC> npcs = GetAssetsOfType<NPC>();
            foreach (var npc in npcs) {
                if (npc.DropOnDeath.Contains(item)) sources.Add(npc);
            }
            List<Shop> shops = GetAssetsOfType<Shop>();
            foreach (var shop in shops) {
                foreach (var itemQuantity in shop.Inventory) {
                    if (itemQuantity.item == item) {
                        sources.Add(shop);
                        break;
                    }
                }
            }
            List<Quest> quests = GetAssetsOfType<Quest>();
            foreach (var quest in quests) {
                if (quest.ItemRewards.Contains(item)) sources.Add(quest);
            }
        }

        EditorGUILayout.LabelField("Item Sources:");
        foreach (var source in sources) {
            EditorGUILayout.LabelField($"\t{source.Name}");
        }
    }

    List<T> GetAssetsOfType<T>() where T : UnityEngine.Object {
        string filter = $"t:{typeof(T).Name}";
        var guids = AssetDatabase.FindAssets(filter);
        List<T> assets = new List<T>(guids.Length);
        foreach (var guid in guids) {
            string path = AssetDatabase.GUIDToAssetPath(guid);
            T asset = AssetDatabase.LoadAssetAtPath<T>(path);
            assets.Add(asset);
        }
        return assets;
    }
}

```

(Note that I have not tested this and it may contain typos).

How well this scales depends on the scope of your game.

# Answer
> 0 votes
If this is only for developer reference in the Editor, and you only need to check one item at a time, another tool you can use is the free package Asset Usage Detector from the Unity Asset Store.

It can find references to an asset in scenes, prefabs, and Scriptable Objects. I'm guessing that it works by scanning the files for the asset's GUID, though I've never dug through the code to find out. It's a little awkward to use sometimes, but may be easier than creating your own process for mapping the relationships between assets.

---
Tags: unity, architecture, software-engineering, databases, scriptable-object
---


# Question
Title: What do you call the base class for a weapon?
This is a style question.

I have a 3D game (think Quake) and the OOP design at a very high level has 3 main base classes:

1. "World"
2. "Entity" - like "Player", "Grunt", "Barrel", "Door"
3. "Weapon" - like "Shotgun", "Nailgun"

The question is I want players to carry more than just weapons in this game. For example, World of Warcraft you can carry many things besides weapons like shields, armor, clothing, amulets, rings, etc. So, I need a base class for Weapon that is more generic.

I have thought of "Item", "Gear", "Equipment", "Kit" as the base class. But I am assuming there must be a standard term for this out. What do other game engines use for this type of base class?

# Answer
> 1 votes
As others have commented, there's no single strategy for this. Personally, I prefer the term "equipment" for items that the player can equip (such as armor and weapons), not for consumables (such as potions). However, you should take your in-game terminology into consideration. It's generally a good idea to make developer terminology reasonably consistent with in-game terminology so that your team members don't get confused.

Here's an example of a frustrating scenario: you have a base class `Item`, and several child classes such as `Weapon`, `Armor`, `Consumable`, `Key`, `Ammo`. Then your boss/client/UX team decides that within the game UI, "Equipment" will be a term for weapons and armor, and "Item" will be a blanket term for all other things that can go into your inventory, such as consumables, keys, and ammo. Now, whenever someone talks about an "item", you have to ask for clarification - are they referring to the `Item` class or the "Item" category in the game?

Another way you can avoid confusion is to use developer terminology that would never appear in an actual game. For example, in the Unity engine, any object that can be placed in the world is a `GameObject`. If I recall correctly, in the Source engine, any object that can be placed in the world is an `Entity`. In some engines and frameworks, any type of character is an `Actor`. Because these terms are never used in actual games, they help to avoid ambiguity in developer conversations.

With that in mind, you could consider base class names like `Equipable`, `Holdable`, `PlayerItem` that would definitely never appear as in-game terminology.

It's not always practical, but when possible you should try to work out all of your terminology early on and try to make it consistent between the code and in-game UI to avoid confusion/ambiguity.

---
Tags: terminology
---


# Question
Title: Is it legit to use Custom Controller Buttons for PC Games in Unity?
Not sure if this is off topic, but I have a problem. I'm making buttons for my own controller in my Game. For example, the attached images will appear to indicate the player to press the A or B Buttons. The image resembles Xbox Controller Buttons. So, is it legit to use them as Buttons of my own Custom Controller?

# Answer
There are official Xbox 360 button and controller images available under the Microsoft Permissive License. They were originally released for use by *XNA Game Studio* titles, but you are free to use them by the license without *XNA Game Studio*.

You can find the original downloads still available from a XNA Game Studio archive site:

Xbox Common Controller Images

Xbox Common Controller Button images

> I have the button artwork arranged in a sprite sheet you can use as well from here under the MIT license--Microsoft legal recommends we release content under MIT instead of MS-PL these days.

> At the moment, there's no Xbox One generation controller artwork available under a public license.
> 3 votes

# Answer
Apart from legal issues, the colors you chose are just plain confusing. On a first party controller (which most people use) A is green, B is red, X is blue and Y is yellow. These make sense based on the most common uses for these. A is generally used for confirming actions, B is for "back" or "no", etc.

Making the button colors differ from what's in front of you is the same as if I put basic quiz questions in front of you. What's the color of the text on this image?
> 1 votes

---
Tags: controllers, xbox-controller
---


# Question
Title: Name & explain shimmering patterns seen when looking at a grid of objects from a distance
If you place a large number of identical elements in a regular pattern, then look at them from a distance, they will make strange warped grid patters that shift as you move your viewpoint, as shown in this video. This is found not only in Minecraft, but also in any program.

I'm wondering if this effect has a name and how it can be explained.

# Answer
It's a moiré pattern caused by aliasing. In your examples, the Moiré patterns occur when a repetitive pattern of high spatial frequency is sampled at low resolution.

Consider the Wikipedia example reference image:

The bricks form a repetitive pattern. Because there's many bricks, the resulting texture has a high spatial frequency. Here's the same image with a reduced resolution:

Lowering the resolution has lowered our sample rate to the point that an obvious moiré pattern occurs. Because there are fewer pixels, information has been lost. And because the brick texture isn't perfectly aligned to the pixel grid, the information isn't lost evenly - some bricks lose more red brick pixels than their neighbors & the similarly for the white mortar pixels. This puts the periodic spatial signal of the brickwork out of phase. The threshold for this problem is determined by the Nyquist–Shannon sampling theorem.

Mipmapping can be used to reduce the artifacts on moiré prone textures. But in your Minecraft example, the 'texture' is effectively made across multiple blocks, so it can't be mitigated by mipmaps. Spatial anti-aliasing could help, but only to a point as we are limited by the finite nature of the screen. Generally speaking, the goal is to get something that's good enough through some combination of graphics techniques (to reduces the artifacts), art / texture choices (to avoid error prone visuals) and game design (to make occurrences brief &/or less impactful).
> 40 votes

---
Tags: graphic-effects, terminology
---


title: In ECS, how to decrease health?

text:
# Question
Title: In ECS, how to decrease health?
I spent a good amount of time trying to get my head around ECS but the "S" is still obscure to me - the farthest I went is that I know a System is where the magic happens; it's where behaviors get implemented, mostly.

However, most references I read about ECS were quite broad in their examples and didn't go much beyond the "Movement" and "Physics" Systems.

That said, **what does a system that a decreases health look like?** *My domain is TypeScript, but examples/snippets in any language work just fine.*

I think the above is hard for me to visualize mostly because my current understanding of ECS is quite as follows:

* An `Entity` is a unique ID that represents a thing,
* Each `Entity` has a "collection" of components, that describes what the `Entity` is composed of and are nothing but data,
* All spawned entities are cached in memory, usually through a "World" object,
* An `Entity` is given a `Health` component through a `world.addComponent(entity, health)` function call,
* Then, to decrease the `Health` of this `Entity` I just spawned, I'd have to...? *This is where things get blurry and dark for me - without the imperative thinking `health.decreaseBy(10)`, the System just does not "click".*

# Answer
> 7 votes
You're on the right track: systems are where the logic resides and where behaviors are implemented. Systems are basically functions where the arguments are components. So if you wanted to create a damage system you need:

* A health component which will be decremented
* A damage component which defines the amount to decrement

Then your system iterates through all entities that have both a damage and health component and decrements the health accordingly.

Once you've done that you'll most likely need some kind of death system. You can implement that either with a system that iterates through all entities that have health and checks if they are at 0 or below, or else by adding a `dead` component to entities with 0 health in your damage system and have your death system iterate all entities with a `dead` component.

Now there's lot's of ways you can implement a damage/death system in ECS, but the takeaways are that when working in ECS:

* If you want something to happen you need to do it with a system.
* Data exists in components, so when your systems need to do something they will get their parameters from some component (e.g. if you want a damage system that applies different damage amounts you need a damage component to store that data)
* You want to keep systems minimal and focused on very narrow behaviors. To expand on @Philipp's comment, if you have a game that has a variety of mechanics around health (e.g. poison, elemental, healing, etc.) you should resist the urge to make one health system that handles all those cases and break those up into a variety of systems (e.g. a poison system, an elemental damage system, etc.).

NOTE: There are exceptions to the rules above but they are uncommon.

## Why Make Systems Small?

@Vaillancourt asked what the rationale is for keeping "systems minimal and focused on very narrow behaviors", so here goes...

At a high level we're all idiosyncratic humans and we should use whatever suits our particular brains best, so if you find lots of files confusing, go ahead and centralize things in larger systems. At the end of the day the point is to build games with a minimum of pain and suffering.

That said ECS architecture is very aggressively tilted towards composition. It's designed with the intent that everything is broken into tiny modules that can be easily plugged together and rearranged, and that philosophy extends to systems as well as components. When first starting out with it I would advise someone to go with the grain of ECS and then start figuring out their own sweet spot for composition.

So as an example imagine we're making an RPG and I code up a health system that handles all the types of damage, healing and death - basically anything that affects health or is derived from it.

The first problem I might run into is performance: there's lots of components associated with this system and most of them won't be present on an entity at any given time (i.e. most entities won't have a heal component, or a damage component on any given frame). Many ECS implementations are optimized for concrete sets of components (e.g. anything with health AND damage) over more abstract queries (e.g anything with health AND/OR damage AND/OR heal, etc.) and there's going to be a lot of conditionals in your system to handle all the cases.

However, you shrug this off - your game simulates small parties fighting not massive battles, so the performance issues are negligible, and you keep plugging along with your full-fat health system.

However, designers being designers you start getting curve balls. First they want to add a spell that prevents damage from poison. Then they add another spell that gives your neighbors a speed boost when you take damage. Then they get weird and decide that whenever the Oneiromancer class takes damage it creates a nightmare token in their inventory. At this point your choice is either to fold half of your game into your health system - which would be madness - or just break it up into tiny little chunks. That way when a designer modifies a mechanic that intersects with health, you can either modify or add a small system, rather than going spelunking through a huge one.

I know that's an extreme example, but in my experience when I bundle up a bunch of stuff into something closed (e.g. a large function or class) I usually have to break it up into it's constituent parts further down the line.

---
Tags: entity-component-system
---


title: Clamping angle between two ranges

text:
# Question
Title: Clamping angle between two ranges
I try to "limit" the amount of angular movement my character is able to "show". I'm using Unity.

I have 3 components in my player entity as below:

The "Player" contains a `Rigidbody2D` responsible for the movement. The "Body" is an animated sprite that (up to now) moves alongside the Player entity. So it is able to move the sprite around the "full circle".

My main problem is, that once it crosses the y-Axis (z-Axis rotation \> `Abs(90)`), the "Body" is upside down which is really looking weird. Furthermore, it the "style" of my game does not really support the player "visually" going directly upward or downward the y-Axis. That's why I want to do 2 things:

1. "Flip" the "body" (mirror on the y-Axis) once the z-Axis rotation is above/below 90.
2. Limit the visual (just the visual) representation of the player's facing direction - see image below red area - so the player is never shown going directly up or down (the Rigidbody2D still can move in this direction, it's just not visualized that way).

My current rotation logic is quite simple:

```
var angle = Mathf.Atan2(velocity.y, velocity.x) * Mathf.Rad2Deg;
var angular = Mathf.LerpAngle(transform.rotation.eulerAngles.z, angle, this._behaviorBase.MaxAngularAcceleration * Time.deltaTime);
angular = (angular + DEG_IN_2PI) % DEG_IN_2PI;
var angularDirection = Quaternion.Euler(0f, 0f, angular);
this._body.SetRotation(angularDirection);

```

This just rotates the player's Rigidbody2D into the movement direction. I'm also able to "counter-rotate" the "Body" component inside the "Player" component so that it always looks in the same direction (unaffected by the Rigidbody movement) with this:

```
var angle = Mathf.Atan2(velocity.y, velocity.x) * Mathf.Rad2Deg;
var angular = Mathf.LerpAngle(transform.rotation.eulerAngles.z, angle,
this._behaviorBase.MaxAngularAcceleration * Time.deltaTime);
angular = (angular + DEG_IN_2PI) % DEG_IN_2PI;
var angularDirection = Quaternion.Euler(0f, 0f, angular);
this._body.SetRotation(angularDirection);
// new code for counter rotation
var counterDirection = Quaternion.Euler(0f, 0f, this._body.transform.rotation.z * 1f);
this._bodyTransform.rotation = counterDirection;

```

But whatever I try to flip the Body at the y-Axis, does not work and only rotated by 90 degrees instead of the full 180. Furthermore, I have quite some problems figuring out how to correctly "clamp" the rotation between `-45 < rotation < 45` and `135 < rotation < 225` because the rotation could be either in the positive or negative rotation representation.

Any tips on how to solve this would be highly appreciated.

**EDIT 1:**

@Kevin: This is the player:

I want to make sure that it can never look like this

The "visible rotation" should never exceed z-Axis angles of +-45 degree (but the Rigidbody should be able to rotate further)

Also, in case the rotation is in the other direction it should be flipped like this

In all cases, the rotation along the z-Axis should be between -45/+45 degrees.

# Answer
I was able to resolve the problem. I introduced a reference for the "Body" (`Transform`) in the controller and basically did 3 steps:

1. Counter rotate the Body element in relation to the Rigidbody
2. Flipped the Body using negative scaling of the direction (left or right looking of the body) changed
3. Clamped to angle according to the direction and applied it to the Body element.

I also introduced an additional flag to prevent strange "jittering" behavior if the movement rotation (Rigidbody) is close to vertical.

```
    var counterAngular = (int) this._body.rotation;
    counterAngular = (counterAngular + (int) DEG_IN_2PI) % (int) DEG_IN_2PI;
    var direction = counterAngular <= 90f || counterAngular >= 270f;
    var stall = Mathf.Abs(counterAngular - 90) <= 1 || Mathf.Abs(counterAngular - 270) <= 1;
    if (!stall && this._lastDirection != direction)
    {
        this._bodyTransform.transform.localScale = new Vector3(-this._bodyTransform.transform.localScale.x, this._bodyTransform.transform.localScale.y, this._bodyTransform.transform.localScale.z);
        this._lastDirection = direction;
    }

    var clamped = RotationUtils.ClampAngle(counterAngular, direction, this._lastRotation);
    var clampedAngular = Mathf.LerpAngle(this._bodyTransform.rotation.eulerAngles.z, clamped, this._behaviorBase.MaxAngularAcceleration * Time.deltaTime);
    var counterDirection = Quaternion.Euler(0f, 0f, clampedAngular);
    this._bodyTransform.rotation = counterDirection;
    this._lastRotation = clamped;

```

This is not the "elegant" solution I was looking for initially but it does the cut and maybe it will help others as well.

If there are better solutions out there, I'd be interested.
> 1 votes

---
Tags: unity, rotation
---


# Question
Title: How can I publish a Python game on itch.io as html?
I'm making a game with Python, using Pygame. I want to publish my game on itch.io so that it's playable in the browser.

Is there a way to do this? If so, how?

# Answer
Since mid-2022, pygame has partial support for WebAssembly as upcoming python3.11 and allows for running the same pygame code on desktops and mobile/web.

To publish your game on itch.io as some people have already done ( as can be seen on https://itch.io/c/2563651/pygame-wasm )

use pygbag from https://pypi.org/project/pygbag , some documentation is available from pygame-web.github.io

read documentation to adjust your main loop for async, and then use `python3 -m pygbag game_folder_with_all_extra_modules_and_assets/main.py`
> 2 votes

# Answer
A game made with Pygame is not playable in the browser. Games made with that tool can be put on itch, but only as a downloadable desktop package, not as a web game.

For completeness, I should mention there are a few projects that aim to get Python/Pygame working in a browser, but I would not call any of these a great option. The most prominent of these projects is Skulpt, and here are some examples of using it with Pygame.

Refer to this existing closely related question.
> 2 votes

---
Tags: javascript, python, pygame, html
---


# Question
Title: Is there a way to make a game that uses Python/pygame that will work through a web browser?
Is there any framework or method that will allow to use browser to run a 2D game made in python with pygame graphical library?

# Answer
> 1 votes
Since mid-2022, pygame has partial support for WebAssembly as upcoming python3.11 and allows for running the same pygame code on desktops and mobile/web.

You can publish your game on itch.io or github pages as some people have already done.

use pygbag from https://pypi.org/project/pygbag , some documentation is available from pygame-web.github.io

read documentation to adjust your main loop for async, and then use `python3 -m pygbag game_folder_with_all_extra_modules_and_assets/main.py`

# Answer
> -1 votes
use replit https://replit.com/~. if you want to make your own website with your game iframe a replit in html

---
Tags: python, pygame, browser-based-games
---


# Question
Title: Why when setting the duration to 0 and then back to 1 or any value above 0 the fading is not continue?
I'm implementing a fading effect for my game. I can change the duration to `0.1` (or `1`, `5`, or `10`). But if I change the duration to `0` and the fading stops, then when I change back the duration to any value above `0` the fading does not resume. I tried it on the automatic mode when `isAutomatic` is `true`. I can't figure out why after setting it to `0` and back to `1`, the fading is not continuing.

Here's my current implementation:

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

public class Fader : MonoBehaviour
{
    public GameObject objectToScale;
    public float duration = 1f;
    public Vector3 minSize;
    public Vector3 maxSize;
    public bool scaleUp = false;
    public Coroutine scaleCoroutine;
    public bool isAutomatic = false;

    private bool automatic = true;

    private void Start()
    {
        objectToScale.transform.localScale = minSize;
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.G))
        {
            Fade();
        }

        if (isAutomatic && automatic)
        {
            Fade();

            automatic = false;
        }
    }

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

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

            yield return null;
        }

        automatic = true;
    }

    private void Fade()
    {
        scaleUp = !scaleUp;

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

        if (scaleUp)
        {
            scaleCoroutine = StartCoroutine(ScaleOverTime(objectToScale, maxSize, duration));
        }

        else
        {
            scaleCoroutine = StartCoroutine(ScaleOverTime(objectToScale, minSize, duration));
        }
    }
}

```

# Answer
> 0 votes
For first situation, setting your `duration = 0` will not enter this loop:

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

            yield return null;
        }

```

Hence, object not fading.

Second situation, as for you changing your `duration` from 0 to 1 in runtime, the line `scaleUp = !scaleUp;` is setting `scaleUp = true` at 0, even though the object didn't scale up, now when you increase the duration from 0 to t seconds ( assuming t \> 0) , it will again call the  `scaleUp = !scaleUp;` that in return turns `scaleUp = false`, hence the code executing this line

```
scaleCoroutine = StartCoroutine(ScaleOverTime(objectToScale, minSize, duration));

```

i.e. going from `objectToScale.transform.localScale` to `minSize` which is the same as `objectToScale.transform.localScale` as set in the `Start()` function.

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


# Question
Title: How to determine whether multiple crafting requirements are met?
I'm currently working on a crafting system - this systems works fine when the desired item has only one requirement. If there is more then one requirement the system brakes.

Here's a short description of how the system should work:

* Every object has a monobehaviour-script which holds an scriptable object.
* This scriptable object contains all the statistics and has a list of required items.
* The warehouse has a monobehaviour-script and this has a list of content items.
* To craft a new item it should compare the content with the requirements.
* Based on the output the object will spawn.

The my problem is getting the right output.

**Item Class:**

```
[System.Serializable]
public class Item
{
    public ScripableTradegood scripableTradegood;
    public int amount;
}

```

**Warehouse**:

```
[Header("Warehouse Content")]
public List<Item> warehouseContent;

```

**Scriptable Object:**

```
[Header("Requirements")]
public List<Item> tradegoodRequirements;

```

**Here the problem:**

```
// Loop through the requirements
    foreach (Item requirement in tradegoodRequirements)
    {
        // For each requirement check content in warehouse
        foreach (Item content in warehouse.warehouseContent)
        {
            // When content is not requirement skip the check
            if (content.scripableTradegood != requirement.scripableTradegood) continue;

            // When right content was found
            if (content.scripableTradegood == requirement.scripableTradegood)
            {

                // If required content amount isnt present return
                if (content.amount < requirement.amount) return;

                /*
                 * When the tradegood has only one requirement - I could just substract the requirements and exit out of the function.
                 * But when if I have more then one requirement - how can I check if all requirements a present before substracting them?
                 * Logically I would have to leave the second loop and continue to check the requirements from the first loop - But how can I achieve that?
                 * */
            }
        }
    }

```

Where is my mistake? Is there something wrong with my approach?

# Answer
The problem is that you did not distinguish whether the inner loop terminated with or without finding the item type you were looking for. You could fix that by introducing a new variable `bool requirementFound` which you set to false before that loop, and then set to true when finding the resource.

Then, after that loop, you can check if `requirementFound` is still false. When it is, then the loop didn't find any of that item type, which means the recipe can't be crafted. When it is true, that resource is available, so we can proceed with the next.

```
foreach (Item requirement in tradegoodRequirements)
{
    foreach (Item content in warehouse.warehouseContent)
    {
        var requirementFound = false;
        if (content.scripableTradegood != requirement.scripableTradegood) continue;

        // When right content was found
        if (content.scripableTradegood == requirement.scripableTradegood)
        {
            // If required content amount isnt present return
            if (content.amount < requirement.amount) return;
        } else {
           requirementFound = true;
           break;
        }

        if(requirementFound == false) {
             //resource is unvailable
             return;
        }
    }
}

```

However, there is a more concise way of writing this if you want to use Linq. If you add the `using System.Linq` directive to your script, then `List`s (and all other collections) gain a whole bunch of useful new methods. Among them is the method `.Contains(predicateFunction)`. Which in plain English tells you "Does this collection contain anything where this function returns true?". So instead of the whole inner loop you can do this:

```
if (warehouse.warehouseContents.Contains(
   (content) => {
       content.scripableTradegood == requirement.scripableTradegood
       && content.amount >= requirement.amount ;
   })
) {
    // This item is available in sufficient quantity
} else {
    // this item is not available in sufficient quantity
}

```

And then there is another useful method `.All` which tells you "Does this function return true for everything in this collection?". So you can substitute that whole code with this:

```
if(
    tradegoodRequirements.All(
       (requirement) => {
           warehouse.warehouseContents.Contains(
               (content) => {
                  content.scripableTradegood == requirement.scripableTradegood
                   && content.amount >= requirement.amount;
               }
           );
        }
    )
) {
      // recipe is craftable
}

```

---

By the way: I assume you do ensure that the content of a warehouse can not contain multiple stacks of the same item type, right? Because if you allow that, then you can not just `return;` after you found a stack with an insufficient amount. There might be a second stack which is large enough. Or perhaps all the stacks together are large enough. That would complicate things a lot.
> 1 votes

# Answer
I wanted to share the new crafting system I came up with.

The user have to add tradegoods to a workbench. This workbench has 3 slots and contains a list of recepies. Those recepies are scriptable tradegoods because every tradegood has list of requirements inside.

Every time a user adds an item to a workbench slot I call this function and compare two strings:

```
public void CheckRecepies()
{
    // Resets the string every time a player adds something to the workbench
    workbenchContent = string.Empty;

    // Check the workbench content a create the string
    foreach (Item content in workbenchSlots)
    {
        // If current slot is not empty then add
        if (content.scriptableTradegood != null)
        {
            // Setup the workbench content string
            workbenchContent += content.scriptableTradegood.name + content.amount;
        }
    }

    // IF THE STRING IS FILLED CHECK REQUIREMENTS

    // Loop through the tradegoods and get the requirements
    foreach (ScriptableTradegood tradegood in recepies)
    {
        // Reset the recepie string for every new tradegood
        recepieContent = string.Empty;

        // Get requirements from tradegood
        foreach (Item recepie in tradegood.tradegoodRequirements)
        {
            // Setup the recepie content string
            recepieContent += recepie.scriptableTradegood.name + recepie.amount;
        }

        // COMPARE TWO STRINGS IF STRINGS ARE EQUAL WORKBENCH FULLFILLES REQUIREMENTS
        if (workbenchContent == recepieContent)
        {
            // Produce
            Debug.Log(recepieContent);
        }
    }
}

```

So far the system is working great for my purposes.
> 0 votes

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


title: 3D Scene in 2D Project in Unity

text:
# Question
Title: 3D Scene in 2D Project in Unity
Okay, found another question that didn't have any answers and couldn't find anything else by Google Searching, YouTube searching, etc. So here comes the inevitable dumb question I ask every time I load up Unity (:

**How do I create/set up a 3D Scene in a 2D project?** When creating my game project, I was anticipating using 2D to create the levels/UI. However, I've been looking into 3D lighting and other effects that would work better with 3D.

I need to either implement the lighting system crap into the Scene somehow or migrate the game into another 3D project and keep the 2D menu. I also would like to keep the animations/scripts (obviously) that I had before in the 2D scene that I'm trying to "convert".

And yes, I have tried creating 3D objects in the 2D scene, and yes, I have tried messing with the camera's rotation. I'm a lighting/shading/rendering noob when it comes to Game Dev, so please explain everything in detail... (:

Of course, as I'm sure you have found out already, I am not aware of any tutorials on this or other questions. If you have any pointers, I'm okay with that too. Thanks for any help in advance!

be nice I know im bad at Game dev ):

# Answer
> 5 votes
There is no fundamental difference between 2D and 3D scenes in Unity.

The 2D vs 3D project setting (which you can change at any time under Edit -\> Project Settings) just configures some convenient defaults for you:

* In 2D mode, new image files found in your Assets folder will be imported as Sprite (2D and UI) type by default. In 3D mode, they'll be imported as Default type instead. You can change this for individual assets by clicking on them in the Project tab and modifying the type drop-down at the top of the Inspector.
* In 2D mode, new scenes will contain...

+ An orthographic camera, which clears to a solid colour before rendering.

While in 3D mode, new scenes will contain...

+ A perspective camera, which clears to a default skybox set in the scene's lighting settings.
    + A directional light

You can change the camera type by clicking on it in the hierarchy and changing its type/clear settings in the Inspector. You can add or delete directional lights as you like.
* In 2D mode, the Scene View will default to 2D (orthographic projection along the z+ axis), while in 3D mode, the Scene View will default to a perspective projection. You can toggle between these views by clicking the 2D button at the top of the Scene View tab.

That's it. So there's nothing to impede you from making 3D content when your project is configured for 2D or vice versa.

If you encounter any difficulty accomplishing a specific 3D task/effect, try editing your question to describe in detail what you're trying to achieve and where you're running into trouble.

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


# Question
Title: DirectX11 creating input layout throws error on input signature not matching shader (instancing)
The input layout

```
D3D11_INPUT_ELEMENT_DESC layout[] = {
            {"Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
            {"Normal", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
            {"Transform", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 0, D3D11_INPUT_PER_INSTANCE_DATA, 1},
            {"Transform", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 16, D3D11_INPUT_PER_INSTANCE_DATA, 1},
            {"Transform", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 32, D3D11_INPUT_PER_INSTANCE_DATA, 1},
            {"Transform", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 48, D3D11_INPUT_PER_INSTANCE_DATA, 1},
            {"Color", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 64, D3D11_INPUT_PER_INSTANCE_DATA, 1},
};

```

The vertex shader

```
cbuffer CBuf
{
    matrix model;
    matrix modelViewProj;
};
struct VSIn
{
    float3 pos : Position;
    float3 n : Normal;
    row_major float4x4 transform : Transform;
    float4 color : Color;
};
struct VSOut
{
    float3 worldPos : Position;
    float3 normal : Normal;
    float4 pos : SV_Position;
    float4 color : Color;
};
VSOut main(VSIn input)
{
    VSOut vso;
    vso.worldPos = (float3) mul(float4(input.pos, 1.0f), input.transform);
    vso.normal = mul(input.n, (float3x3) input.transform);
    vso.pos = mul(float4(input.pos, 1.0f), modelViewProj);
    vso.color = input.color;
    return vso;
}

```

The error

```
ID3D11Device::CreateInputLayout: The provided input signature expects to read an element with SemanticName/Index: 'Transform'/0, but the declaration doesn't provide a matching name.
D3D11Device::CreateInputLayout: The provided input signature expects to read an element with SemanticName/Index: 'Transform'/1, but the declaration doesn't provide a matching name.
D3D11Device::CreateInputLayout: The provided input signature expects to read an element with SemanticName/Index: 'Transform'/2, but the declaration doesn't provide a matching name.
D3D11Device::CreateInputLayout: The provided input signature expects to read an element with SemanticName/Index: 'Transform'/3, but the declaration doesn't provide a matching name.
D3D11Device::CreateInputLayout: The provided input signature expects to read an element with SemanticName/Index: 'Color'/0, but the declaration doesn't provide a matching name.

[Error Code] 0x80070057 (2147942487)
[Error String] E_INVALIDARG
[Description] The parameter is incorrect.

```

The error is thrown on `CreateInputLayout` before I draw anything to screen. I previously had this whole setup working with normal non instanced drawing. I understand that the error means the input layout doesn't match the shader declaration but I can't see which part does not match. `VSIn` contains a semantic name for `Position`, `Normal`, `Transform` and `Color`.

Research:

So for what I have tried after reading the above:

* Use D3D11\_APPEND\_ALIGNED\_ELEMENT instead of manually calculating the offsets
* Split up the Transform matrix into four float4s with numbered semantic names
* Binding just the color and removing the transform from both the input description and the shader (same error but only concerning color).
* Ensure the shader that is loaded is the correct shader
* Delete the generated .cso file to make sure the shader recompiles
* Change the semantic names to different strings in case of reserved identifiers

# Answer
The problem was I was not calculating the number of elements in the `CreateInputLayout` call. It was fixed at 2 elements.

Incorrect

```
pDevice->Get()->CreateInputLayout(
            layout, 2u,
            out.pBytecodeBlob->GetBufferPointer(),
            out.pBytecodeBlob->GetBufferSize(),
            &out.pInputLayout
);

```

Correct

```
int iNumElements = sizeof(layout) / sizeof(D3D11_INPUT_ELEMENT_DESC);
pDevice->Get()->CreateInputLayout(
            layout, iNumElements,
            out.pBytecodeBlob->GetBufferPointer(),
            out.pBytecodeBlob->GetBufferSize(),
            &out.pInputLayout
);

```
> 3 votes

# Answer
In the input layout, you are including the color attribute in the same vertex buffer slot as the transform matrix. Edit the color attribute element in the input layout to use vb slot 2:

```
{"Color", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 2, 0, D3D11_INPUT_PER_INSTANCE_DATA, 1}

```
> 0 votes

---
Tags: c++, directx, directx11, hlsl
---


# Question
Title: Custom Unity shader makes mesh look different
I am very much new to custom shaders. My actual problem is that I want to fade a mesh in and out via C# in Unity. However, the materials on the mesh I am using are opaque and setting them to transparent was causing me headaches with how the mesh appears (parts of the mesh were showing through the front / facing the camera in weird ways).

So I turned to shaders and I looked up a very basic shader implementation. Once this shader is applied to the material, I'm able to set the alpha channel quite easily while maintaining the general look of the mesh.

However, just changing from the Standard shader to this basic one, causes the mesh to look different. I thought it was lighting related, but I have tried to search for more information and I'm coming up short. I also wondered whether it was the Blend part of it below but I have tried a few combinations and none seem to work.

Here's the shader I'm using ... I believe this is just the most basic they can be:

```
Shader "Custom/TransparentShader"
{
    Properties
    {
        _Color("Color", Color) = (1,1,1,1)
        _MainTex("Texture", 2D) = "white" {}
    }
        SubShader
    {
        Blend SrcAlpha OneMinusSrcAlpha

        Pass {
            CGPROGRAM

            #include "UnityCG.cginc"

            #pragma vertex vert
            #pragma fragment frag

            sampler2D _MainTex;
            float4 _MainTex_ST;

            fixed4 _Color;

            struct appdata {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f {
                float4 position : SV_POSITION;
                float2 uv : TEXCOORD0;
            };

            v2f vert(appdata v) {
                v2f o;
                o.position = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag(v2f i) : SV_TARGET{
                fixed4 col = tex2D(_MainTex, i.uv);
                col *= _Color;
                return col;
            }

            ENDCG
        }
    }
}

```

Is there an obvious (noobie) reason the mesh looks so different with this basic shader?

# Answer
> 0 votes
The lack of actual light calculations causes this. The standard unity shader applies many lighting techniques that make that mesh stand out more. In your shader, you only use color to blend your texture.

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


# Question
Title: Detecting the avatar's position in relation to the camera's angle
How to detect the avatar's position in relation to the camera's angle.

I want to detect whether the camera is facing the avatar's lef, right or back side.

What's the best way to do this?

# Answer
> 1 votes
You can use InverseTransformPoint to get the camera's position expressed in the local coordinate space of the avatar. Then you just need to check which component of that vector is farthest from zero, and in what direction.

I've shown a version that categorizes all 6 pyramids around the avatar (including "top" and "bottom"), but you can delete the `y` sections if you just want to categorize positions in 4 wedges — left/right/front/back.

```
public enum Side {
    Left,
    Right,
    Top,
    Bottom,
    Front,
    Back
}

public Side WhichSideOf(Vector3 position, Transform relativeTo) {
    var local = relativeTo.InverseTransformPoint(position);

    var squared = Vector3.Scale(local, local);

    if (squared.x > squared.y) {
        if (squared.x > squared.z) {
            return local.x > 0 ? Side.Right : Side.Left;
        } else {
            return local.z > 0 ? Side.Front : Side.Back;
        }
    } else if (squared.y > squared.z) {
        return local.y > 0 ? Side.Top : Side.Bottom;
    } else {
        return local.z > 0 ? Side.Front : Side.Back;
    }
}

```

# Answer
> -1 votes
On top of my head, I would create a forward, left, right, and back vector on the "Avatar". You can then calculate the vector between the camera and avatar and use that as a dot product. From there, I *THINK* that the highest dot value is the one facing the camera most.

---
Tags: unity, camera, angles, avatar
---


# Question
Title: Unity Data files: Players getting around Steam by replacing the demo's data files with the full version's data and then refunding it
A player just reported that it's easy to **play the full version of my (fully offline) Unity game for free** by just:

1. Buy the full game.
2. Back up the data files.
3. Refund the full game.
4. Get the demo version.
5. Replace the demo's data files with the full version's data files.

I know that **Steam disables refunding after a soft limit**, so you can't just do this for every game...

But even so **how could I defend against this?** There must be easy solution for this, right?

Thanks in advance!

**UPDATE**:

There are two approaches to fix this issue:

* Make your own *.exe* so Steam can differentiate the Demo and the Full version. (See the answer of Anomalous Underdog below for details)
* Check with Steam API if the user owns the game at startup and quit if something is not right.

*"In your base game, you could periodically call BIsSubscribedApp( 1346210 ) to determine whether or not the user owns a license to the base game."* \- Steam

# Answer
> 3 votes
Create your own .exe file for launching the game. You will have to be knowledgeable in C/C++ and the Windows API (if you are building for Windows). See instructions in the manual (check each page in that section).

By creating your own code for the .exe file, you could potentially do anything conceivable in C/C++, like performing offline checks, making sure the files present are really only the demo files, obfuscating/encrypting your data, etc.

Your game can still be cracked in the usual ways that any C/C++ application could be cracked (and if you go deep into this it will be a game of cat-and-mouse between you and the pirates, even the stuff I mentioned are easily beaten by any competent cracker), but it should be easy to prevent that simple method you've explained.

Note: The reason why Steam doesn't detect a change when you replace the executable is because the .exe file of any Windows Standalone build is all the same (if they are from the same Unity version at least), doesn't matter what project it was built from (you can verify this by doing md5/sha checksum of the .exe file of any Unity Windows standalone build).

In this way, as far as Steam is concerned, the .exe file of a demo version looks the same as the .exe file of the full version, because the binary data inside them is the same.

When you build a Unity project, this .exe file is just copied over and renamed to whatever you specified. The job of this .exe file is to simply launch the Unity engine.

The WinMain function of that .exe file is extremely simple, it just calls a function called `UnityMain`. `UnityMain` is within the `UnityPlayer.dll` file (you can find that dll in the same folder that the .exe file is in). That's the Unity engine (Windows version) C/C++ source code compiled as a dll (and it's closed source). It's the starting point of the Unity engine in Windows (the other Unity dll files you can find in the build are C# stuff).

Explaining all that is pretty off-topic but my point is that the .exe file does nothing more than launch Unity. It doesn't care what game data is given to it.

Unity provides you the source code and Visual Studio solution of the .exe file in:

*wherever you installed Unity*/Editor/Data/PlaybackEngines/WindowsStandaloneSupport/Source/WindowsPlayer

You could use that Visual Studio solution as a starting point when making your own .exe file.

---
Tags: unity, steam, piracy
---


title: Transforming 3d point for depth testing

text:
# Question
Title: Transforming 3d point for depth testing
I have a ray and its direction is (`o`,`d`). Multiply it by the model matrix to rotate the model.

```
o = uCamera.xyz, d = GenRay();
o = vec3(uModel * vec4(o,1));
d = vec3(uModel * vec4(d,0));

```

Then beam, `RayMarchLeaf(o, d, t, color, normal);` where get the position vec3 `t` of the collision of the beam. (in model coordinates). Then traslate `t` to world coordinates :

```
t = vec3(inverse(uModel) * vec4(t,1)); // map to world pos;

```

ok, we have a 3d camera coordinate and a point. For Depth value, we can use `length(uCamera.xyz - t)`, but this is not accurate. My camera is moving and rotating in 3d space.
**How to accurate calculate depth value to store in texture?**

# Answer
> 0 votes
What i need - just multiply world coordinate by the product of view and projection matrices then do perspective divide.

```
mat4 viewproj = uProjection * uView; //calculate viewproj
vec4 clip_space_coord = viewproj * t; //do transform
//perspectice division (done automatically by the hardware between
//vertex and fragment shader stages, so you don't actually need to do this
//if you do this in a vertex shader and then continue to the fragment)
clip_space_coord = clip_space_coord / clip_space_coord.w; // perspective devide;

```

# Answer
> 0 votes
There is no direct correct answer to this as each engine's depth texture is packed differently. And also differ depending on the math behind it.

But as a broad answer is instead to unpack the depth value back to 3d, you can calculate the distance from there. To do this, you could multiply the depth value with the inverse View\*Projection ( ClipspaceToWorldSpace ).

Here is an example code on how I rebuild the 3d position in the unity engine.

```
float2 uv = i.vPosition.xy / _ScreenParams.xy;
GBufferOutput gBuffer = UnpackGBuffer( uv );

float z = tex2D( _CameraDepthTexture, uv);
float linearZ = Linear01Depth( z );
float w = linearZ * _ProjectionParams.z;
float x = uv.x * 2.0 - 1.0;
float y = uv.y * 2.0 - 1.0;
float4 vProjectedPos = float4( x, y, z, 1.0 );
float4 vPositionVS = mul( mProjectionToView, vProjectedPos );
vPositionVS.xyz *= w;

float4 vWorldPosition = mul( mViewToWorld, float4( vPositionVS.xyz, 1.0 ) );

```

Where: UV = is the screen position coordinates. Z = depth value on texture.

It might not be the best solution in the world, but it does the trick! I hope this helps!

---
Tags: matrix, transformation, ray
---


# Question
Title: Is it possible to mark a Unity prefab variant as deprecated?
I'm building a game at the moment and a classic issue has come up, of having a complicated prefab variant in use, which happens to have a fundamental problem in its design and needs to be replaced. This is often done to a new prefab variant that only barely differs, and I'll typically name it something like `<original name>.2` to differentiate.

(Usually it's something silly like forgetting to rotate by an empty parent game object that doesn't have an animator attached, something like that... nothing that can easily be swapped out of the original prefab.)

This works great. However, there's always the possibility that I'm going to be popping that deprecated original prefab into a slot that expects the new one, and warnings like we get with the `[Obsolete]` annotation on class code would be really useful and quite the time saver, I wouldn't even have to run the program to know I've done something wrong. Since prefab variants follow much the same pattern as classes and subclasses, I'm wondering:

Do prefabs have an equivalent to the `[Obsolete]` attribute? Can I tell Unity directly to keep it, but not let me use it without throwing a fuss?

# Answer
Personally I would not recommend leaving deprecated prefabs in your project. If you're not careful, those deprecated files are *extremely* confusing for new team members, or when doing maintenance years down the road when you no longer remember every little detail. It also makes searching your project more tedious since your search results will include deprecated files.

I'd suggest either deleting the bad prefab after creating a new version, or just modifying the bad prefab to fix it. If you ever need the old version again (why would you?) - that's what version control is for.

If you absolutely must keep the old prefab for some really legitimate reason and not out of a fear of ever deleting anything, you should **rename it** and include the word "Deprecated" in the new name.

**Rationale**

Deprecation is normally used in the context of public APIs/packages, where *your team is creating* code or other assets that will be *used by other teams*. You mark an API or other asset as deprecated when it's no longer supported and will be removed in a future version; the only reason you're keeping it around is for backwards compatibility, so developers that use your API/package don't have to immediately update their code to keep their project working.

When you are working on an *internal* project solo or with a small team, there's not a lot of reason to keep around deprecated files. You don't have to worry about breaking someone else's project when you remove an old version of a file (unless you're working on a shared library that is used by multiple internal projects). The biggest concern is if you are working on a large team where multiple developers might be currently working with the asset that you want to get rid of; then you may need to coordinate with them to make sure you don't do something that causes merge conflicts.

**If you want to replace a broken prefab because it's not possible to fix the prefab**, there's a way to replace the prefab, (usually) without breaking existing references to that prefab:

1. Create the new prefab that works correctly.
2. Minimize Unity and do not open it again until you reach step 5.
3. In your operating system's file browser (e.g. Explorer, Finder), find and delete the prefab file, but ***not*** the corresponding .meta file.
4. Delete the .meta file for the new prefab. Rename the new prefab with the same name as the old prefab.
5. Open Unity again.

What we've done here is replace the old prefab with a new prefab **with the same GUID** (this is defined in the .meta file). Any components that referenced the old prefab by GUID will generally still have their references to the new prefab. However, **references to a specific script on the prefab will no longer be valid if the new prefab doesn't have the same script**.
> 3 votes

---
Tags: unity, prefabs
---


# Question
Title: Diamond square texture: too-diamond-ish?
I wrote a small JavaScript implementation of the Diamond-Square height map/texture algorithm and the result is much more industrial-looking than I expected. I can trace a diamond pattern throughout (maybe I should have expected that given the name? ).

Any idea what I could be doing wrong?

Here's the code I'm using:

```
const textureCanvas = document.getElementById('texture');
const ctx = textureCanvas.getContext('2d');

const levelInput = document.getElementById('level');
const topLeftHeightInput = document.getElementById('tl');
const topRightHeightInput = document.getElementById('tr');
const bottomLeftHeightInput = document.getElementById('bl');
const bottomRightHeightInput = document.getElementById('br');

levelInput.addEventListener('input', render);
topLeftHeightInput.addEventListener('input', render);
topRightHeightInput.addEventListener('input', render);
bottomLeftHeightInput.addEventListener('input', render);
bottomRightHeightInput.addEventListener('input', render);

render();

function render () {
  const level = Number(levelInput.value);
  const span = Math.pow(2,level) + 1;
  textureCanvas.width = span;
  textureCanvas.height = span;

  // initialize height data container
  const heightData = Array(span);
  for (let x = 0; x < span; x++) {
    heightData[x] = Array(span);
  }

  // compute heights via Diamond Square algorithm
  heightData[0][0] = Number(topLeftHeightInput.value);
  heightData[span - 1][0] = Number(topRightHeightInput.value);
  heightData[0][span - 1] = Number(bottomLeftHeightInput.value);
  heightData[span - 1][span - 1] = Number(bottomRightHeightInput.value);
  const maxHeight = Math.max(
    heightData[0][0],
    heightData[span - 1][0],
    heightData[0][span - 1],
    heightData[span - 1][span - 1],
    diamondSquare(heightData, level) // performs diamond square algorithm
  );

  // convert heights to image data for canvas
  const imageData = ctx.createImageData(span, span);
  const { data } = imageData;
  for (let y = 0; y < span; y++) {
    for (let x = 0; x < span; x++) {
      const brightness = Math.round(heightData[x][y] / maxHeight * 255);
      data[y * span * 4 + x * 4 + 0] = brightness; // r
      data[y * span * 4 + x * 4 + 1] = brightness; // g
      data[y * span * 4 + x * 4 + 2] = brightness; // b
      data[y * span * 4 + x * 4 + 3] = 255;        // a
    }
  }

  ctx.putImageData(imageData, 0, 0);
}

// implementation based on visual description at:
// https://en.wikipedia.org/wiki/Diamond-square_algorithm#Visualization
// NOTE: mutates heightData.
function diamondSquare (heightData, level) {
  let maxHeight = 0;

  if (level < 1) {
    return maxHeight;
  }

  const interval = Math.pow(2, level);
  const half = Math.pow(2, level - 1);

  // diamond step
  for (let yOffset = 0; yOffset + 1 < heightData.length; yOffset += interval) {
    for (let xOffset = 0; xOffset + 1 < heightData.length; xOffset += interval) {
      heightData[xOffset + half][yOffset + half] = (
        heightData[xOffset + 0][yOffset + 0] +
        heightData[xOffset + half * 2][yOffset + 0] +
        heightData[xOffset + 0][yOffset + half * 2] +
        heightData[xOffset + half * 2][yOffset + half * 2]
      ) / 4 + Math.random() * interval;

      maxHeight = Math.max(
        maxHeight,
        heightData[xOffset + half][yOffset + half]
      );
    }
  }

  // square step
  for (let yOffset = 0; yOffset + 1 < heightData.length; yOffset += interval) {
    for (let xOffset = 0; xOffset + 1 < heightData.length; xOffset += interval) {
      const noTopCorner = yOffset <= 0;
      heightData[xOffset + half][yOffset + 0] = (
        (noTopCorner ? 0 : heightData[xOffset + half][yOffset - half]) +
        heightData[xOffset + half][yOffset + half] +
        heightData[xOffset + 0][yOffset + 0] +
        heightData[xOffset + half * 2][yOffset + 0]
      ) / (noTopCorner ? 3 : 4) + Math.random() * interval;
      const noBottomCorner = yOffset + half * 2 + 1 >= heightData.length;
      heightData[xOffset + half][yOffset + half * 2] = (
        heightData[xOffset + half][yOffset + half] +
        (noBottomCorner ? 0 : heightData[xOffset + half][yOffset + half * 3]) +
        heightData[xOffset + 0][yOffset + half * 2] +
        heightData[xOffset + half * 2][yOffset + half * 2]
      ) / (noBottomCorner ? 3 : 4) + Math.random() * interval;
      const noLeftCorner = xOffset <= 0;
      heightData[xOffset + 0][yOffset + half] = (
        heightData[xOffset + 0][yOffset + 0] +
        heightData[xOffset + 0][yOffset + half * 2] +
        (noLeftCorner ? 0 : heightData[xOffset - half][yOffset + half]) +
        heightData[xOffset + half][yOffset + half]
      ) / (noLeftCorner ? 3 : 4) + Math.random() * interval;
      const noRightCorner = xOffset + half * 2 + 1 >= heightData.length;
      heightData[xOffset + half * 2][yOffset + half] = (
        heightData[xOffset + half * 2][yOffset + 0] +
        heightData[xOffset + half * 2][yOffset + half * 2] +
        heightData[xOffset + half][yOffset + half] +
        (noRightCorner ? 0 : heightData[xOffset + half * 3][yOffset + half])
      ) / (noRightCorner ? 3 : 4) + Math.random() * interval;

      maxHeight = Math.max(
        maxHeight,
        heightData[xOffset + half][yOffset + half],
        heightData[xOffset + half][yOffset + 0],
        heightData[xOffset + half][yOffset + half * 2],
        heightData[xOffset + 0][yOffset + half],
        heightData[xOffset + half * 2][yOffset + half]
      );
    }
  }

  return Math.max(maxHeight, diamondSquare(heightData, level - 1));
}
```

```
  <h1>Diamond Square texturing</h1>
  <div id="inputs">
    <label>
      Level <input id="level" type="number" step="1" min="1" max="20" value="8">
    </label>
    <br/>
    <label>
      Top-left-height
      <input id="tl" type="number" step="0.1" min="0" max="20" value="2">
    </label>
    <br/>
    <label>
      Top-right-height
      <input id="tr" type="number" step="0.1" min="0" max="20" value="17">
    </label>
    <br/>
    <label>
      Bottom-left-height
      <input id="bl" type="number" step="0.1" min="0" max="20" value="4">
    </label>
    <br/>
    <label>
      Bottom-right-height
      <input id="br" type="number" step="0.1" min="0" max="20" value="9">
    </label>
  </div>
  <canvas id="texture"></canvas>

```

# Answer
Your code cites the Wikipedia article, which in turn has a section called "Artifacts and Extensions" that observes a potential problem:

> The diamond-square algorithm was analyzed by Gavin S. P. Miller in SIGGRAPH 1986 who described it as flawed because the algorithm produces noticeable vertical and horizontal "creases" due to the most significant perturbation taking place in a rectangular grid.

And a solution:

> The grid artifacts were addressed in a generalized algorithm introduced by J.P. Lewis. In this variant the weights on the neighboring points are obtained by solving a small linear system motivated by estimation theory, rather than being fixed.

Some of these artifacts are present in the example image on Wikipedia. Here's the original image & a copy where I've flagged some of the artifacts. I marked 'high artifacts' in yellow & 'low artifacts' in pink:

I did the flagging by free hand, so they might be off by a few pixels here & there, but we can noticed some trends: the artifacts tend to manifest as horizontal & vertical lines & the lines tend to align with each in a grid pattern. Your are also grid aligned, but tend to show up as lines cutting at 45 degrees. So I think there's something else going on here. If I understand your code correctly, it looks like you're doing a diamond step & a square step for each level - my understanding is that the diamond and square steps are supposed to be performed alternately.
> 2 votes

# Answer
While this is an old question, it still ranks on google and the marked answer does not explain the artefacts seen in the output.

I have just implemented this algorithm (for fun) in c# using linqpad and had what seems to be exactly the same problem. I managed to figure out that the pattern appears due to the way one calculates the random values that are always added to the pixels. If you only allow positive random numbers, it seems the original corners are "left behind" and remain low throught the process. These then cause the repeating pattern seen throughout. If you ensure the random number generated for each pixel is in the range -1 -\> +1 before any other calculations then the pattern is eliminated.

There may be other ways to accomplish the same outcome, but I found this the easiest way (other attempts failed), I then normalise my data to the range 0-\>1 before rendering. Performance is not a consideration for me.

**TLDR - make your random numbers go from -1 to +1**
> 2 votes

---
Tags: textures, javascript, procedural-generation, terrain, heightmap
---


# Question
Title: τ = r × F, In unity3d/PhysX how do we define r?
How does PhysX define/calculate the distance from the center of mass where we apply the force to produce a torque?

# Answer
> 1 votes
This depends on how you are applying the torque.

* The AddTorque method (by default) interprets the `Vector3` parameter as a torque in world space. That means the engine does not need to compute a radius at all: it's already baked into the value you pass as input (ie. the argument is already a product of force times distance, measured in Newton-metres).

So if I call `body.AddTorque(new Vector3(0, 0, 1))`, this could be interpreted as a force of 1N in the world y+ direction applied to a point 1m from the center of mass along the world x+ axis:

$$\tau = \begin{bmatrix}1m \\ 0 \\ 0\end{bmatrix} \times \begin{bmatrix}0 \\ 1N \\ 0\end{bmatrix} = \begin{bmatrix}0 \\ 0 \\ 1Nm\end{bmatrix}$$

...or as a force of 10 N in the x+ direction applied 0.1 m from the center of mass along the world y- axis:

$$\tau = \begin{bmatrix}0 \\ -0.1m \\ 0\end{bmatrix} \times \begin{bmatrix}10N \\ 0 \\ 0\end{bmatrix} = \begin{bmatrix}0 \\ 0 \\ 1Nm\end{bmatrix}$$

Either way, the net torque and the resulting rotation is the same. So the radius exists only in your interpretation, or in the calculations you do to determine the torque you want to apply when forming your argument to pass.

This is also the case if you use `ForceMode.Force` as the second parameter (here the naming is misleading, but the documentation page linked above explains how to interpret it in this case). You can also use other modes to interpret the `Vector3` argument differently:

+ `ForceMode.Acceleration` treats the input as an angular acceleration, measured in \\$\frac {^\circ} {s^2}\\$. This acts over the course of one simulation step and ignores the mass of the body.
    + `ForceMode.Impulse` treats the input as an instantaneous change in angular momentum, measured in \\$\frac {kg \cdot m} {s}\\$. This ignores the length of the simulation step and is affected by the mass of the body (heavier bodies will rotate less, given the same impulse).
    + `ForceMode.VelocityChange` treats the input as an instantaneous change in angular velocity, measured in \\$\frac {^\circ} {s}\\$. This acts ignores both the length of the simulation step and the body's mass, similar to modifying `body.angularVelocity` directly.

AddRelativeTorque is similar, except that the input is given in the body's local coordinate system, rather than the world coordinate system.

For completeness, other methods act as follows...
* The AddForce method applies the force through the center of mass, so no torque results from using this method.
* The AddForceAtPosition method applies the force through the point you provide in world space, so the radius is the distance between that point and the center of mass.

AddRelativeForce is similar, except that the input is given in the body's local coordinate system, rather than the world coordinate system.
* In the case of a collision, the radius is the distance of the point of contact from the center of mass.

---
Tags: unity, physics, mathematics, physx, torque
---


# Question
Title: How are NP-Hard problems managed in game development contexts?
When NP-Hard problems arise in game development, how are such problems dealt with? Through heuristics or solvers or a combination of both?

# Answer
In my experience, the main way NP-Hard problems are solved in game development involves relying on the fact that our **instances tend to be quite small**.

We usually don't need to solve NP-Hard problems involving millions of customers or billions of rows in a "Big Data" style database, where the complexity class hits hardest.

**When the problems are player-facing**, ie. the gameplay challenge depends on a human figuring out the solution, then the problem sizes are implicitly bounded by the **limits on human reasoning** and working memory.

If your \\$n\\$ is on the order of a couple dozen, then it doesn't matter if the best known algorithm for a problem is \\$O(e^n)\\$, and you may even be able to brute force exact solutions to some problems with \\$O(n!)\\$ complexity.

A recent example I encountered was in developing a solver routine as part of a level generator for a deductive puzzle game - to ensure the puzzles it generated could be successfully completed without guessing. The rules of the puzzle game make it a Boolean satisfiability problem equivalent to 3-SAT, and so NP-Hard. But taking into account limits on human reasoning, I limit my search to deductions that involve at most a dozen variables and a dozen clauses (or so). That keeps the search for a deducible solution pruned tightly enough that even a very naïve exponential algorithm can solve a full puzzle in milliseconds.

When the problem is not meant to be player-solvable, we still have other factors that can mitigate the difficulty.

If the problem is in decision-making by **AI agents**...

* There are usually **only a few sophisticated agents** in a single game scene, like a handful of AI opponents in a strategy game, or a few dozen enemy combatants in a shooter. An expensive AI routine isn't too bad if you only need to run it a few times.

Games with large numbers of AI agents tend to have them follow simpler logic like swarming, using steering behaviours or flow fields, rather than complex optimization routines.
* It's often OK if those agents make decisions on **human-perceivable time scales**. We don't need them to react to a change in game state within a single frame - in fact, a delay proportional to human reaction and decision-making speeds can make the AI appear more realistic and fair than one that always reacts instantaneously. So we can afford to offload a heavy optimization calculation to a background thread, or time-slice our processing of it, so each agent only computes a new optimal move every few seconds, using simpler reflex behaviours in between strategic updates.
* **We often don't care if the AI makes the very best decision possible**. In fact, sometimes a solution that's too clever/thinking too many steps ahead can look to the player like a bug, or like the AI is behaving randomly. Often we prefer predictable and obviously-explainable behaviour over optimal behaviour. That lets us apply a relaxation and solve a simpler version of the problem, use heuristics, or apply bounded reasoning to trade-off optimality for computation speed and memory efficiency.

If the problem arises in **procedural generation of content**, this is often work that can be done on a background thread while the player is playing previously-generated content, so it's OK if it takes some time to finish.

We'll also frequently use **chunking techniques** to reduce the density of data points our algorithms need to act on - say replacing a fine grid of the game map with a navmesh consisting of a much smaller number of much larger polygonal nodes, and solving spatial problems on this reduced graph. This again can trade off exact optimality for time and memory savings, but the **player often won't know what's exactly optimal** anyway, or we can **disguise/explain-away sub-optimal behaviour** using the game's fiction and art (eg. this unit sometimes looks a bit awkward trying to get into the best attack position according to its complex evaluation function? Make its model/sprite and animations look lumbering and clumsy so that's part of its character!)

That last point touches on a great get-out-of-jail-free card we have in game development: **our worlds are made up.** If the design of a particular game rule demands solving a computationally intractable problem, rather than inventing a revolutionary algorithm to solve it, we can just **change the rules** to something simpler to compute. That's a liberty that folks working in real-world domains like scientific computing, high-frequency trading, etc. don't have such easy access to.
> 18 votes

---
Tags: optimization
---


# Question
Title: Model is oriented correctly in the Unity asset browser but flips 180 degrees when added to the scene?
I have modeled two pinball flippers in Houdini. I exported them as OBJ files and imported them into Unity 2021.3. They look correct in the asset view:

They also look correct when I open them with the default Windows 3D model viewer.

However, as soon as I drag them into the scene, they flip 180 degrees about the Y axis:

My camera is oriented correctly and I have verified that I am using the correct axes in the modeling program. So what is causing this to happen and is there a way I can fix it? I know I can child them to an empty GameObject and rotate them that way but I'd like to fix the root cause, if possible.

**EDIT:** Here is the orientation of the right flipper in Houdini. I am saving the geometry as `flipper_right.obj`:

In Unity I am simply dragging it from the asset browser into the scene:

# Answer
> 2 votes
The first thing to understand is that Unity uses a left-handed coordinate system with the convention:

* x+ = "right"
* y+ = "up"
* z+ = "forward"

(You can see this in the naming of the static property basis vectors in the `Vector3` type)

That means that Unity will expect most assets to be modelled/arranged in their prefab parent to "face" in the z+ direction.

When you're browsing assets, you usually want to be looking *at* the *front* of the asset - to see the face of a character for example, not the back of their head. That means that the Unity asset preview looks at the assets *from* the z+ side, meaning that it's looking *back* along the z axis. You can verify this by making a quick little prefab with colour-coded nubs pointing along each positive axis, then looking at how it's oriented in the preview:

So, that solves your first problem: the object is *not* changing its transformation between the asset preview and the scene view. You just happen to have your scene view camera placed behind the object in the z axis, while the asset preview assumes you want to look at objects from in front.

Now, what's going on with the difference between Houdini and Unity?

Houdini uses a different coordinate system. It's right-handed, which means that to convert to Unity's left-handed scheme, one position axis needs to be negated. Houdini's export to Unity chooses to negate the x axis. So something that points in the x- direction in Houdini will point in the x+ direction in Unity. This conversion step is necessary so that if you're modelling a chiral object like a hand, a left hand in Houdini should import as a left hand in Unity, rather than an inside-out right hand (which is what you'd get without the negation).

You have not shown us the transform inspector for your flipper object, but if you find it's imported with an unwanted rotation, you can tick the "Bake Axis Conversion" box in the mesh import settings inspector to apply transformation changes to the vertex data itself, rather than the rotation property.

---
Tags: unity, models, obj, import
---


# Question
Title: How to handle keyboard input arrow keys for a 2.5D Platformer
I need a higher level abstraction for keyboard input for a 2.5D platformer. Like I know left and right is pressed, but I want to consider things like, left is held down for more than one second, start running, right is pressed while left is just released so slow down and turn, things like that.

What are some considerations on this regard?

# Answer
The way I process keys presses in my applications is I have 2 lists ranging from 0-127 (all ASCII keys). One is for a `key_duration_state` and the other for a `key_hold_state`. I don't know what sort of event listener you're using, but take a generic `onKeyDown/Up(int key)` listener function for example. This functions job is to let you know when a key has been pressed, where `key` was the value of the key pressed. I have it return `1` as long as the key is still pressed, and `0` when it's released. All I need in order to register every ASCII keys press/release state is pass my list to the function. Same goes for duration. Just increment that keys duration\_state as long as its pressed. Then reset it to zero upon release:

```
// tells if its pressed
bool onKeyDown(int key) {
    key_hold_state[key] = 1;
    key_duration_state[key]++;
}

// tells if its released
bool onKeyUp(int key) {
    key_hold_state[key] = 0;
    key_duration_state[key] = 0;
}

```

What I do to determine if a key is being held for a duration is use my list `key_hold_state` which stores whether the key is pressed down or not. Then I have another function, say `isHeldFor(int duration)` which checks if that key was held for the duration:

```
bool wasHeldFor1s = keyListener.isHeldFor('A', DURATION_1s);

```

```
bool isHeldFor(int key, int duration) {
    return duration_held_state[key] >= duration);
}

```

This is just my approach. There could be a better way, but storing every keys states into lists is a good move. Keeps it clear, concise, and organized.
> 2 votes

---
Tags: input, platformer, 2.5d
---


# Question
Title: Does the scale of a background image affect performance?
I have a background that's a half-square shape.

If I increase the size of the background, for example by adjusting the scale of the model from 1x to 10000x, will this affect the performance of the game?

# Answer
> 1 votes
**No, scale should not affect performance as a general rule.**

Under the hood, scale is handled as part of the matrix multiplication in the graphics pipeline that transforms vertices from model space to screen space. This matrix multiplication happens no matter what scale value you use, and multiplying by 1 has the same cost as multiplying by 1000, so increasing the scale number itself does not cost anything extra.

There are two potential exceptions, where increasing scale has a side effect that *can* affect performance, but they should not apply to your case:

* When an object gets bigger, it can occupy more pixels on the screen. That means the pixel shader of its material gets invoked more times, and you spend more of your fill rate (the maximum number of times your GPU can write a pixel value into an output buffer in a unit of time) drawing it. For an expensive shader, or cases where your game is fill rate bound, this can affect performance.

In your case, since a background image is usually covering the whole screen anyway, you should not observe a difference due to this effect.
* When an object has a physics collider, that collider needs to be sorted into acceleration structures to optimize collision checks and physics calculations. When objects are very very large, it's harder to cull them during collision checking because they could potentially be touching so many places in your scene. That can increase processing costs.

Large and heavy objects can also make some collision and constraint resolution calculations less stable - especially when they collide with much smaller/lighter objects, and this can cause visible jitters or glitches. Usually physics engines are optimized to work best with objects ranging from a few tenths of units to tens of units in size, so keeping most objects in this range can be good for stability.

But again, in your case, background images usually don't have any physics associated with them, so you should not expect this to apply here.

Overall, the very best way to find out how something affects performance in your game, running on your target hardware, is to **try it and use the profiler** to measure the impact. This will get you verifiable evidence, rather than hearsay from strangers on the Internet, so always make this your go-to method for learning about your game's performance.

---
Tags: unity, performance, scale
---


# Question
Title: Libgdx zoom and pan the map at the same time
I was able to do the zoom logic and pan logic, but like in google maps, I want to be able to zoom to the map and at the same time pan the map near to it.

Example

starting position:

zoom to kennedy airport:

As you can see the map is not zoomed to the center ( New York label), because the mouse pointer was on the kennedy airport and a pan is added.

How do the same with libgdx ?

code for map zoom:

```
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Dialog;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.ScreenUtils;

public class GameScreen extends BaseScreen {

    private Image map;

    public GameScreen(Launcher launcher) {
        super(launcher);
    }

    @Override
    public void show() {
        batch = new SpriteBatch();
        // create ui
        stage = new Stage();
        skin = new Skin(Gdx.files.internal("defaultSkin/uiskin.json"));
        final Dialog dialog = new Dialog("Welcome", skin, "dialog") {
            public void result(Object obj) {
                System.out.println("Closed dialog!");
            }
        };
        dialog.setPosition(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);
        dialog.text("Hello World ! Try to move with mouse and zoom with mouse wheel");
        dialog.button("Close", true); // sends "true" as the result
        dialog.pack();
        dialog.setVisible(true);
        // stage.addActor(dialog);
        // init camera
        camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        // init map image
        map = new Image(new Texture("map/World-map4.png"));
        map.setSize(1080, 720);
        // init input processor
        InputMultiplexer multi = new InputMultiplexer();
        multi.addProcessor(stage);
        multi.addProcessor(new InputProcessor() {

            @Override
            public boolean touchUp(int screenX, int screenY, int pointer, int button) {
                return false;
            }

            @Override
            public boolean touchDragged(int screenX, int screenY, int pointer) {
                return false;
            }

            @Override
            public boolean touchDown(int screenX, int screenY, int pointer, int button) {
                System.out.println("clicked: " + screenX + "," + screenY);
                return false;
            }

            @Override
            public boolean mouseMoved(int screenX, int screenY) {
                return false;
            }

            @Override
            public boolean keyUp(int keycode) {
                return false;
            }

            @Override
            public boolean keyTyped(char character) {
                return false;
            }

            @Override
            public boolean keyDown(int keycode) {
                System.out.println("Key down: " + keycode);
                int step = 20;
                int dx = 0;
                int dy = 0;
                if (keycode == Keys.LEFT) {
                    dx = -step;
                }
                if (keycode == Keys.RIGHT) {
                    dx = step;
                }
                if (keycode == Keys.UP) {
                    dy = step;
                }
                if (keycode == Keys.DOWN) {
                    dy = -step;
                }
                camera.translate(dx, dy);
                return true;
            }

            @Override
            public boolean scrolled(float amountX, float amountY) {
                // arbitrary max zoomIn and max zoomOut values here
                if (camera.zoom - amountY >= -0.8f && camera.zoom - amountY <= 2) {
                    camera.zoom -= (float) amountY / 10f;
                    System.out.println("zoom  :" + camera.zoom);
                }
                return true;
            }
        });

        Gdx.input.setInputProcessor(multi);
    }

    @Override
    public void render(float delta) {
        ScreenUtils.clear(0, 0.36f, 0.65f, 1);
        camera.update();
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        map.draw(batch, 1);
        batch.end();
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }

    @Override
    public void dispose() {

    }

}

```

So following Basic's suggestion:

the main idea is to:

* given the viewport center
* given the mouse position
* calculate tx and ty ( screen relative, not world relative )
* translate the screen of a fraction of tx andty ( for example tx/2 and ty/2 )
* zoom

# Answer
Fundamentally, you need to perform the following steps:

* Work out where you want to pan the view to (relative position to current center)
* Pan the camera
* Zoom in

You already have the code for 2 and 3...

```
camera.translate(dx, dy);

camera.zoom -= (float) amountY / 10f;

```

`dx` and `dy` are how far to move the camera horizontally/vertically at the current zoom level.

`amountY` is how much you want to zoom in by.

So all you need is a method that takes the relative coordinates and zoom level, then applies both...

```
void MoveAndZoom(float dx, float dy, float zoom) {
    camera.translate(dx, dy);
    camera.zoom -= (float) zoom / 10f;
}

```

And call it from the appropriate input method (eg touchdown gives you screen coordinates of the touch point which you can use to calculate `dx` and `dy`)
> 0 votes

---
Tags: libgdx
---


# Question
Title: Does Screen.orientation not work in simulator?
I use the `Screen.orientation` property to reposition my UI when the screen is rotated. But when I rotate the simulator to left or right, `Screen.orientation` does not seem to detect the screen change.

Why is that?

```
if (    Screen.orientation == ScreenOrientation.LandscapeLeft
     && Screen.orientation == ScreenOrientation.LandscapeRight )
{
     Button.transform.localPosition = new Vector3(112, -425.690063f, 0);
}
else
{
     Button.ShowandHide.transform.localPosition = new Vector3(112, -253.609131f, 0);
}

```

If I use `Screen.height > Screen.width`, will that work?

# Answer
> 3 votes
This is not a problem with `Screen.orientation` \- you just have a bug in your code.

This `if` condition:

```
if (    Screen.orientation == ScreenOrientation.LandscapeLeft
     && Screen.orientation == ScreenOrientation.LandscapeRight )

```

Says "If `Screen.orientation` is *simultaneously both* `LandscapeLeft` AND `LandscapeRight`..."

But obviously the phone can't be *both* laying to the left AND laying to the right at the same time. Macroscopic objects like phones don't get to occupy two contradictory states in superposition.

So this condition is impossible, and always evaluates to `false`, meaning your `else` block is always the one that executes.

It looks like what you want here is:

```
if (    Screen.orientation == ScreenOrientation.LandscapeLeft
     || Screen.orientation == ScreenOrientation.LandscapeRight )

```

That double-pipe `||` is "OR" not "AND". So we'll execute the first block if the phone is *either* lying to the left, OR lying to the right.

The `else` block will then trigger only if *neither* of those is true (ie. the phone is standing vertically - upright or upside-down).

Be sure to proofread your code for typos like this. 90% of the time, when you encounter a problem that looks like "is this engine used by thousands of developers and successful games completely and utterly broken, or did I just make a mistake somewhere?" the answer is usually that you made a mistake somewhere.

---
Tags: unity, mobile, screen, orientation
---